diff --git "a/3447.jsonl" "b/3447.jsonl" new file mode 100644--- /dev/null +++ "b/3447.jsonl" @@ -0,0 +1,626 @@ +{"seq_id":"269471886","text":"import numpy as np\nfrom math import cos, sin\n\nfrom utils import Utils\n\nclass Engine:\n\n meshes = []\n triangles = np.array([])\n\n @staticmethod\n def rotate(point: tuple, rotation: tuple) -> tuple:\n cx = cos(rotation[0])\n cy = cos(rotation[1])\n cz = cos(rotation[2])\n sx = sin(rotation[0])\n sy = sin(rotation[1])\n sz = sin(rotation[2])\n\n return Engine.rotate_cs(point, (cx, cy, cz), (sx, sy, sz))\n\n def rotate_cs(point: tuple, cos: tuple, sin: tuple) -> tuple:\n cx, cy, cz = cos\n sx, sy, sz = sin\n\n return [\n point[0] * (cz*cy-sz*sx*sy) - point[1] * sz * cx + point[2] * (cz*sy+sz*sx*cy),\n point[0] * (sz*cy+cz*sx*sy) + point[1] * cz * cx + point[2] * (sz*sy-cz*sx*cy),\n point[0] * cx * -sy + point[1] * sx + point[2] * cx * cy\n ]\n\n\n\n @staticmethod\n def calc_normal(p1: tuple, p2: tuple, p3: tuple) -> tuple:\n v1 = Utils.sub_vec_r(p2, p1)\n v2 = Utils.sub_vec_r(p3, p1)\n cr = Utils.cross(v1, v2)\n Utils.normalize(cr)\n \n return cr\n\nclass V:\n def __init__(self) -> None:\n self.x = 0\n","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"327118149","text":"from django.db.models import Model\nfrom django.db.models.fields import Field\n\n\nclass OptionsLazy:\n\n def __init__(self, name, klass):\n self.name = name\n self.klass = klass\n\n def __get__(self, instance=None, owner=None):\n return self.klass(owner)\n\n\nclass OptionsBase(type):\n def __new__(cls, *args, **kwargs):\n new_class = super().__new__(cls, *args, **kwargs)\n if new_class.model_class and new_class.meta_name:\n setattr(new_class.model_class, new_class.meta_name, OptionsLazy(new_class.meta_name, new_class))\n return new_class\n\n\nclass Options(metaclass=OptionsBase):\n\n meta_class_name = None\n meta_name = None\n attributes = None\n model_class = None\n\n def __init__(self, model):\n self.model = model\n\n for key, default_value in self._get_attributes(model).items():\n setattr(self, key, self._getattr(key, default_value))\n\n def _get_attributes(self, model):\n return self.attributes\n\n def _getattr(self, name, default_value):\n meta_models = [b for b in self.model.__mro__ if issubclass(b, Model)]\n for model in meta_models:\n meta = getattr(model, self.meta_class_name, None)\n if meta:\n value = getattr(meta, name, None)\n if value is not None:\n return value\n return default_value\n\n\ndef field_init(self, *args, **kwargs):\n \"\"\"\n Patches a Django Field's `__init__` method for easier usage of optional `kwargs`. It defines a `humanized` attribute\n on a field for better display of its value.\n \"\"\"\n humanize_func = kwargs.pop('humanized', None)\n if humanize_func:\n def humanize(val, inst, *args, **kwargs):\n return humanize_func(val, inst, field=self, *args, **kwargs)\n self.humanized = humanize\n else:\n self.humanized = self.default_humanized\n getattr(self, '_init_chamber_patch_')(*args, **kwargs)\n\n\nField.default_humanized = None\nField._init_chamber_patch_ = Field.__init__ # pylint: disable=W0212\nField.__init__ = field_init\n","sub_path":"chamber/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350878558","text":"def ciag1(* liczby):\n if len(liczby) == 0:\n return 0\n else:\n wynik = liczby[0]\n for i in liczby:\n wynik *= i\n return wynik\nprint(ciag1())\nprint(ciag1(1,2,3,4,5,6,7))","sub_path":"lab3/zad7.py","file_name":"zad7.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270628564","text":"from PIL import Image\nimport pytesseract\n\nimport cv2\nimport numpy as np\n\nimport time\nimport sys\nimport math\nimport os\n\nfrom matplotlib import pyplot as plt\n\ndef main():\n #folder = os.path.abspath(\"./input\")\n #output = os.path.abspath(\"./output\")\n #files = os.listdir(folder)\n\n #for file in files:\n # print(file)\n\n verA = \"./input/a.JPG\"\n\n worstCasePath = \"./input/2017122800008FWR3SV44.TIF\"\n loadingErrorCasePath = \"./input/085a17f2-f5c4-411d-bbcf-8e7303498fa.tif\"\n\n #print(os.path.exists(loadingErrorCasePath))\n #print(os.path.isfile(loadingErrorCasePath))\n\n image = cv2.imread(verA)\n\n if image is None:\n sys.exit(\"Image was not loaded properly\")\n\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n cv2.imwrite(\"./output/gray.jpg\", gray)\n\n height, width = gray.shape\n\n median = cv2.medianBlur(gray, 3)\n cv2.imwrite(\"./output/median.jpg\", median)\n\n invert = cv2.bitwise_not(median)\n cv2.imwrite(\"./output/invert.jpg\", invert)\n\n kernel = np.ones((3, 3), np.uint8)\n dilate = cv2.dilate(invert, kernel, iterations = 1)\n cv2.imwrite(\"./output/medianDilate.jpg\", dilate)\n\n blank = np.zeros((height, width, 3), np.uint8)\n fakeImage, contours, hierarchy = cv2.findContours(invert, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n contoursImage = cv2.drawContours(blank, contours, -1, (0, 255, 0), 1)\n cv2.imwrite(\"./output/medianDilateContours.jpg\", contoursImage)\n\n heightSum = 0;\n widthSum = 0;\n\n for contour in contours:\n area = cv2.contourArea(contour)\n x,y,w,h = cv2.boundingRect(contour)\n heightSum += h\n widthSum += w\n\n avgHeight = heightSum / len(contours)\n avgWidth = widthSum / len(contours)\n\n h, w = gray.shape[:2]\n\n boxes = np.zeros((height, width, 3), np.uint8)\n dots = np.zeros((height, width, 3), np.uint8)\n mask = np.zeros((height, width), np.uint8)\n #boxes = cv2.cvtColor(boxes, cv2.COLOR_GRAY2BGR)\n lines = gray.copy()\n lines = cv2.cvtColor(lines, cv2.COLOR_GRAY2BGR)\n\n id = 0\n hierarchy = hierarchy[0]\n\n for contour in contours:\n\n epsilon = 0.1 * cv2.arcLength(contour, True)\n approx = cv2.approxPolyDP(contour, epsilon, True)\n\n x,y,w,h = cv2.boundingRect(approx)\n\n vPadding = 5\n hPadding = 15\n\n #if h <= avgHeight and w <= avgWidth:\n # color = (255, 255, 0)\n #else:\n # color = (0, 0, 255)\n\n color = (255, 0, 0)\n\n #area = cv2.contourArea(contour)\n M = cv2.moments(contour)\n cx = int(M['m10']/M['m00']) if M['m00'] else 0\n cy = int(M['m01']/M['m00']) if M['m00'] else 0\n\n if cx != 0 and cy != 0:\n cv2.circle(dots, (cx, cy), 2, color, -1)\n\n mask = cv2.rectangle(mask, (x - hPadding, y - vPadding), (x + w + hPadding, y + h + vPadding), 255, -1)\n boxes = cv2.rectangle(boxes, (x - hPadding, y - vPadding), (x + w + hPadding, y + h + vPadding), color, 1)\n lines = cv2.line(lines, (x - hPadding, y + h + vPadding), (x + w + hPadding, y + h + vPadding), color, 1)\n\n id += 1\n\n cv2.imwrite(\"./output/mask.jpg\", mask)\n cv2.imwrite(\"./output/dots.jpg\", dots)\n cv2.imwrite(\"./output/medianDilateContoursEdgesBoxes.jpg\", boxes)\n cv2.imwrite(\"./output/medianDilateContoursEdgesLines.jpg\", lines)\n\n blank = np.zeros((height, width, 3), np.uint8)\n fakeImage, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n contoursImage = cv2.drawContours(blank, contours, -1, (0, 255, 0), 1)\n cv2.imwrite(\"./output/maskContours.jpg\", contoursImage)\n\n masked = mask - gray\n cv2.imwrite(\"./output/masked.jpg\", masked)\n\n maskedInvert = 255 - masked\n cv2.imwrite(\"./output/maskedInvert.jpg\", maskedInvert)\n\n final = np.zeros((height, width, 3), np.uint8)\n\n for contour in contours:\n area = cv2.contourArea(contour)\n x, y, w, h = cv2.boundingRect(contour)\n region = maskedInvert[y:y+h, x:x+w]\n\n output = pytesseract.image_to_data(region, output_type = pytesseract.Output.DICT)\n rows = len(output[\"level\"])\n\n for z in range(0, rows):\n\n level = output[\"level\"][z]\n pageNumber = output[\"page_num\"][z]\n blockNumber = output[\"block_num\"][z]\n paragraphNumber = output[\"par_num\"][z]\n lineNumber = output[\"line_num\"][z]\n wordNumber = output[\"word_num\"][z]\n left = output[\"left\"][z]\n top = output[\"top\"][z]\n width = output[\"width\"][z]\n height = output[\"height\"][z]\n confidence = output[\"conf\"][z]\n text = output[\"text\"][z]\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n color = (255, 255, 255)\n fontScale = 0.5\n lineType = 1\n\n finalX = x + left\n finalY = y + top\n\n if confidence != -1 and text != \"\" and final[finalY][finalX][0] != 255:\n cv2.putText(final, text, (finalX, finalY + int(height / 2)), font, fontScale, color, lineType)\n cv2.putText(final, str(confidence), (finalX + width + 5, finalY + height + 5), font, fontScale, (0, 255, 0), lineType)\n\n final = cv2.rectangle(final, (finalX, finalY), (finalX + width, finalY + height), color, 1)\n\n\n cv2.imwrite(\"./output/final.jpg\", final)\n\n sys.exit(0)\n\n blur = cv2.GaussianBlur(masked, (7, 7), 0)\n cv2.imwrite(\"./output/blur.jpg\", blur)\n\n data = []\n\n output = pytesseract.image_to_data(maskedInvert, output_type = pytesseract.Output.DICT)\n rows = len(output[\"level\"])\n final = np.zeros((height, width, 3), np.uint8)\n\n for z in range(0, rows):\n\n level = output[\"level\"][z]\n pageNumber = output[\"page_num\"][z]\n blockNumber = output[\"block_num\"][z]\n paragraphNumber = output[\"par_num\"][z]\n lineNumber = output[\"line_num\"][z]\n wordNumber = output[\"word_num\"][z]\n left = output[\"left\"][z]\n top = output[\"top\"][z]\n width = output[\"width\"][z]\n height = output[\"height\"][z]\n confidence = output[\"conf\"][z]\n text = output[\"text\"][z]\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n color = (255, 255, 255)\n fontScale = 0.5\n lineType = 2\n\n if confidence != -1 and text != \"\":\n size = cv2.getTextSize(text, font, fontScale, lineType)\n cv2.putText(final, text, (left, top), font, fontScale, color, lineType)\n textWidth = size[0][0]\n textHeight = size[0][1]\n cv2.putText(final, str(confidence), (left + textWidth, top + textHeight), font, fontScale, (0, 255, 0), lineType)\n\n cv2.imwrite(\"./output/final.jpg\", final)\n\n sys.exit(0)\n\n height = 27\n width = 401\n\n output = pytesseract.image_to_data(Image.open('./input/testLine.jpg'), output_type = pytesseract.Output.DICT)\n rows = len(output[\"level\"])\n final = np.zeros((height, width, 3), np.uint8)\n\n for z in range(0, rows):\n\n level = output[\"level\"][z]\n pageNumber = output[\"page_num\"][z]\n blockNumber = output[\"block_num\"][z]\n paragraphNumber = output[\"par_num\"][z]\n lineNumber = output[\"line_num\"][z]\n wordNumber = output[\"word_num\"][z]\n left = output[\"left\"][z]\n top = output[\"top\"][z]\n width = output[\"width\"][z]\n height = output[\"height\"][z]\n confidence = output[\"conf\"][z]\n text = output[\"text\"][z]\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n color = (0, 0, 255)\n fontScale = 0.5\n lineType = 2\n\n cv2.putText(final, text, (left, top), font, fontScale, color, lineType)\n\n\n cv2.imwrite(\"./output/final.jpg\", final)\n\n sys.exit(0)\n\n print(output)\n print(len(output[\"level\"]))\n print(len(output[\"page_num\"]))\n print(len(output[\"block_num\"]))\n print(len(output[\"par_num\"]))\n print(len(output[\"line_num\"]))\n print(len(output[\"word_num\"]))\n print(len(output[\"left\"]))\n print(len(output[\"top\"]))\n print(len(output[\"width\"]))\n print(len(output[\"height\"]))\n print(len(output[\"conf\"]))\n print(len(output[\"text\"]))\n\n sys.exit(0)\n\n outputSize = len(output)\n columns = 12\n\n print(outputSize)\n print(outputSize / columns)\n\n print(output.expandtabs())\n\n sys.exit(0)\n\n output = pytesseract.run_and_get_output(Image.open('./output/masked.jpg'), 'txt', lang='spa', config='', nice=0)\n output = output.split(\"\\t\")\n print(output)\n output = output.split(\"\\t\")\n\n sys.exit(0)\n\n image = cv2.imread(\"./input/2017122800008FWR3SV44.TIF\")\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n median = cv2.medianBlur(gray, 5)\n gaussian = cv2.GaussianBlur(gray, (5, 5), 0)\n blur = cv2.blur(gray, (5, 5))\n bilateral = cv2.bilateralFilter(gray, 9, 75, 75)\n ret3, otsu = cv2.threshold(gaussian, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n\n kernel = np.ones((1, 1), np.uint8)\n dilate = cv2.dilate(gray, kernel, iterations = 1)\n erode = cv2.erode(dilate, kernel, iterations = 1)\n\n ret,binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n ret,trunc = cv2.threshold(gray, 127, 255, cv2.THRESH_TRUNC)\n ret,tozero = cv2.threshold(gray, 127, 255, cv2.THRESH_TOZERO)\n\n height, width = gray.shape\n contoursImage = np.zeros((height, width, 3), np.uint8)\n fakeImage, contours, hierarchy = cv2.findContours(median,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n contoursImage = cv2.drawContours(contoursImage, contours, -1, (0,255,0), 1)\n\n cv2.imwrite(\"./output/gray.jpg\", gray)\n cv2.imwrite(\"./output/median.jpg\", median)\n cv2.imwrite(\"./output/gaussian.jpg\", gaussian)\n cv2.imwrite(\"./output/blur.jpg\", blur)\n cv2.imwrite(\"./output/bilateral.jpg\", bilateral)\n cv2.imwrite(\"./output/otsu.jpg\", otsu)\n cv2.imwrite(\"./output/binary.jpg\", binary)\n cv2.imwrite(\"./output/trunc.jpg\", trunc)\n cv2.imwrite(\"./output/tozero.jpg\", tozero)\n cv2.imwrite(\"./output/dilate.jpg\", dilate)\n cv2.imwrite(\"./output/erode.jpg\", erode)\n cv2.imwrite(\"./output/contours.jpg\", contoursImage)\n\n sys.exit(0)\n\n #blur = cv2.GaussianBlur(gray, (5,5), 0)\n threshold = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 2)\n\n #invert = cv2.bitwise_not(threshold)\n\n #kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3,3))\n #dilate = cv2.dilate(invert, kernel, iterations = 1)\n\n height, width = dilate.shape\n\n mask = np.zeros((height + 2, width + 2), np.uint8)\n\n flood = threshold.copy()\n\n maxPoint = (-1, -1)\n maxArea = -1\n\n for y in range(0, height):\n for x in range(0, width):\n if flood[y][x] >= 128:\n\n mask[:] = 0\n\n area = cv2.floodFill(flood, mask, (x, y), 64)[0]\n\n if area > maxArea:\n maxArea = area\n maxPoint = (x, y)\n\n mask[:] = 0\n\n cv2.floodFill(flood, mask, maxPoint, 255)\n\n boxes = flood.copy()\n\n for y in range(0, height):\n for x in range(0, width):\n if boxes[y][x] == 64:\n boxes[y][x] = 0\n\n fakeImage, contours, hierarchy = cv2.findContours(boxes, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n contoursImage = np.zeros((height, width, 1), np.uint8)\n contoursImage = cv2.drawContours(contoursImage, contours, -1, (255, 255, 255), 5)\n\n corners = cv2.cornerHarris(np.float32(contoursImage), 2, 3, 0.04)\n\n cv2.imwrite(\"2.jpg\", gray)\n cv2.imwrite(\"3.jpg\", blur)\n cv2.imwrite(\"4.jpg\", threshold)\n cv2.imwrite(\"5.jpg\", invert)\n cv2.imwrite(\"6.jpg\", dilate)\n cv2.imwrite(\"7.jpg\", flood)\n cv2.imwrite(\"8.jpg\", boxes)\n cv2.imwrite(\"9.jpg\", contoursImage)\n cv2.imwrite(\"10.jpg\", corners)\n\n #print(pytesseract.image_to_string(image).encode(\"utf-8\"))\n\n\nmain()\n","sub_path":"src/prev/singlePageProcess.py","file_name":"singlePageProcess.py","file_ext":"py","file_size_in_byte":11749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"16229205","text":"#!/usr/bin/env python\n# \n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport psycopg2\n\n\ndef connect(database_name=\"tournament\"):\n \"\"\"Setup the connect method to make connection with the database and also setup \n the cursor. An error message is displayed if there is problem with the conection.\n \"\"\"\n try:\n db = psycopg2.connect(\"dbname={}\".format(database_name))\n cursor = db.cursor()\n return db, cursor\n except:\n print(\"Error : Please verify the databse name in the .sql file\")\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\n Used cursor() to execute SQL command to DELETE all data from the matches table.\n \"\"\"\n db, cursor = connect()\n cursor.execute(\"DELETE FROM matches;\")\n db.commit()\n db.close ()\n\n\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\n Used cursor() to execute SQL command to DELETE all data from the Players table.\n \"\"\" \n db, cursor = connect()\n cursor.execute(\"DELETE FROM Players;\")\n db.commit()\n db.close ()\n\n\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\n Executed SQL command to COUNT all rows from the Players table.\n Then Used c.fetchone()[0] to obtain the count value and return it.\n \"\"\"\n db, cursor = connect()\n cursor.execute(\"SELECT COUNT(*) FROM Players;\")\n countPy = cursor.fetchone()[0]\n db.close ()\n return countPy\n\n\n\ndef registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n\n The database assigns a unique serial id number for the player. (This\n should be handled by your SQL database schema, not in your Python code.)\n\n Args: \n name: the player's full name (need not be unique).\n Executed INSERT into players table, %s allows the Query to understand 'name'.\n \"\"\"\n db, cursor = connect()\n cursor.execute(\"INSERT INTO Players (name) VALUES (%s)\",(name,))\n db.commit()\n db.close()\n\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n\n The first entry in the list should be the player in first place, or a player\n tied for first place if there is currently a tie.\n\n Returns:\n A list of tuples, each of which contains (id, name, wins, matches):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: the number of matches the player has won\n matches: the number of matches the player has played\n\n Used cursor.fetchall the results of the SQL Query are converted to a list of tuples and the is returned.\n \"\"\"\n db, cursor = connect()\n cursor.execute(\"SELECT player_id, name, player_wins, player_matches FROM Players ORDER BY player_wins DESC\")\n standings = [(int(row[0]), str(row[1]), int(row[2]),int(row[3])) \n for row in cursor.fetchall()]\n db.close ()\n return standings\n\n\ndef reportMatch(winner, loser): \n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n\n\n The SQL Query UPDATE the 'Players' and 'Matches' tables with winner and loser infromation.\n \"\"\"\n db, cursor = connect()\n cursor.execute(\"UPDATE Players SET player_wins = player_wins + 1 WHERE player_id = (%s)\",(winner,))\n cursor.execute(\"UPDATE Players SET player_matches = player_matches + 1 WHERE player_id = (%s) OR player_id = (%s)\",(winner,loser,))\n cursor.execute(\"INSERT INTO Matches VALUES (DEFAULT, (%s) ,(%s))\",(winner,loser,))\n db.commit()\n db.close()\n\n\ndef swissPairings(): \n\n \"\"\"Returns a list of pairs of players for the next round of a match.\n \n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n \n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1: the first player's unique id\n name1: the first player's name\n id2: the second player's unique id\n name2: the second player's name\n\n Used a for loop the increments by 2 the list of standings can be converted into a list of pairings.\n rowfetch[i]+rowfetch[i+1] allows the for loop to look at 2 playerIDs at the same time and add them to the tuple.\n \"\"\"\n db, cursor = connect()\n cursor.execute(\"SELECT player_id, name FROM Players ORDER BY player_wins DESC\")\n rowfetch = cursor.fetchall()\n pairings =[]\n for i in range(0,(len(rowfetch)-1),2):\n if rowfetch[i+1]:\n pairings.append(rowfetch[i]+rowfetch[i+1])\n\n db.close ()\n return pairings\n\n\n","sub_path":"tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":4836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"40767859","text":"import csv\nimport os.path\nimport matplotlib \nmatplotlib.rcParams.update({'font.size': 10})\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport torch\nimport argparse\nfrom rlkit.torch import pytorch_util as ptu\n# Logger Params\nparser = argparse.ArgumentParser()\nparser.add_argument('--exp_name', type=str, default='max2')\nparser.add_argument('--ar', type=float, default=10.) # action range\nparser.add_argument('--log_dir', type=str, default='PRGGaussiank1hidden32oaonaceersdadcigpna')\nparser.add_argument('--seed', type=int, default=0)\nargs = parser.parse_args()\n\npre_path = './Data/'+args.exp_name+'ar'+str(args.ar)+'/'+args.log_dir\nplot_file = pre_path+'/'+'seed'+str(args.seed)+'/alpha.png'\n\nfrom sequential_differential_game import SequentialDifferentialGame\nenv = SequentialDifferentialGame(game_name=args.exp_name)\n\nxs = np.linspace(-1,1,100)\nys = np.linspace(-1,1,100)\na1s = np.zeros((100,100))\nca1s = np.zeros((100,100))\na2s = np.zeros((100,100))\nca2s = np.zeros((100,100))\n\nd_path = pre_path+'/'+'seed'+str(args.seed)+'/params.pkl'\ndata = torch.load(d_path,map_location='cpu')\n\na1net = data['trainer/log_alpha_n'][0]\nca1net = data['trainer/log_calpha_n'][0]\na2net = data['trainer/log_alpha_n'][1]\nca2net = data['trainer/log_calpha_n'][1]\nwith torch.no_grad():\n for i,x in enumerate(xs):\n for j,y in enumerate(ys):\n a_input = torch.tensor([x,y,x,y]).float()[None,:]\n a1 = a1net(a_input)\n ca1 = ca1net(a_input)\n a2 = a2net(a_input)\n ca2 = ca2net(a_input)\n a1s[j,i] = a1[0]\n ca1s[j,i] = ca1[0]\n a2s[j,i] = a2[0]\n ca2s[j,i] = ca2[0]\n\nplt.figure()\n\nplt.subplot(2,2,1)\nplt.contourf(xs,ys,a1s)\nplt.gca().set_aspect('equal', 'box')\nplt.xlim(-1,1)\nplt.ylim(-1,1)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('a1')\n\nplt.subplot(2,2,2)\nplt.contourf(xs,ys,a2s)\nplt.gca().set_aspect('equal', 'box')\nplt.xlim(-1,1)\nplt.ylim(-1,1)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('a2')\n\nplt.subplot(2,2,3)\nplt.contourf(xs,ys,ca1s)\nplt.gca().set_aspect('equal', 'box')\nplt.xlim(-1,1)\nplt.ylim(-1,1)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('ca1')\n\nplt.subplot(2,2,4)\nplt.contourf(xs,ys,ca2s)\nplt.gca().set_aspect('equal', 'box')\nplt.xlim(-1,1)\nplt.ylim(-1,1)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('ca2')\n\nplt.savefig(plot_file)\nplt.close()","sub_path":"tests/SequentialDifferentialGame/plot_alpha.py","file_name":"plot_alpha.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"502928341","text":"import os\nimport re\nimport ntpath\nfrom bs4 import BeautifulSoup\nimport nltk\nfrom string import punctuation\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize \nfrom nltk.tokenize import sent_tokenize\nfrom nltk.stem import PorterStemmer\n\nmy_stopwords = set(stopwords.words('english') + list(punctuation))\n\n\ndef get_text(file):\n read_file = open(file, \"r\")\n text = read_file.readlines()\n text = ' '.join(text);\n return text\n\ndef clear_html(text):\n soup = BeautifulSoup(text, 'html.parser')\n return soup.get_text()\n\ndef remove_special_character(text):\n string = re.sub('[^\\w\\s]', '',text)\n string = re.sub('\\s+', ' ', string)\n string = string.strip()\n return string\n\ndef path_leaf(path):\n head, tail = ntpath.split(path)\n return tail or ntpath.basename(head)\n\ndef rename_files(string):\n listString = string.split('.')\n return listString[0]+\"_word.\"+listString[1]\n\ndef listToString(s): \n \n str1 = \"\" \n \n for ele in s: \n str1 += ele \n \n return str1 \n\ndef write_file(string_file, words):\n dir_name_file = './output/'+string_file\n\n os.makedirs(os.path.dirname(dir_name_file), exist_ok=True)\n with open(dir_name_file, \"w\") as f:\n f.write(listToString(words))\n\nlist_path = []\n\nfor root, dirs, files in os.walk('./input'):\n for file in files:\n list_path.append(root+\"/\"+file)\n\nj = 0 \nfor j in range(len(list_path)):\n read_file = open(list_path[j], \"r\")\n a = read_file.read()\n # goi xu ly cac ham da dinh nghia\n # print(remove_special_character(clear_html(get_text(list_path[j]))))\n\ni = 0\nfor i in range(len(list_path)):\n text = get_text(list_path[i])\n text_cleared = clear_html(text)\n\n sents = sent_tokenize(text_cleared)\n sents_cleared = [remove_special_character(s) for s in sents]\n text_sents_join = ''.join(sents_cleared)\n\n words = word_tokenize(text_sents_join)\n\n words = [word.lower() for word in words]\n\n words = [word for word in words if word not in my_stopwords]\n\n\n\nps = PorterStemmer()\nwords = [ps.stem(word) for word in words]\n\nk = 0 \nfor k in range(len(list_path)):\n list_file_des = rename_files(path_leaf(list_path[k]));\n \n write_file(list_file_des, words)\n \n\n\n\n# in ra cac dong\nprint(words)\n\n\n","sub_path":"1760221.py","file_name":"1760221.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"81607765","text":"import adv.adv_test\nfrom core.advbase import *\nfrom adv import addis\nfrom module.bleed import mBleed\nfrom slot.a import *\n\ndef module():\n return Addis\n\nclass Addis(addis.Addis):\n def prerun(this):\n this.s2buff = Selfbuff(\"s2_shapshifts1\",1, 10,'ss','ss')\n this.s2str = Selfbuff(\"s2_str\",0.25,10)\n this.bleedpunisher = Modifier(\"bleed\",\"att\",\"killer\",0.08)\n this.bleedpunisher.get = this.getbleedpunisher\n this.bleed = mBleed(\"g_bleed\",0).reset()\n\n\n def s1_proc(this, e):\n if this.s2buff.get():\n this.s2buff.buff_end_timer.timing += 2.5\n this.s2str.buff_end_timer.timing += 2.5\n log('-special','s1_with_s2')\n mBleed(\"s1\", 1.32).on()\n else:\n this.afflics.poison('s1',100,0.53)\n\n\n\nif __name__ == '__main__':\n conf = {}\n adv.adv_test.test(module(), conf,verbose=0, mass=0)\n\n","sub_path":"adv/addis.py.means.py","file_name":"addis.py.means.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"310442578","text":"import sys\n\nsys.path.append(r\"F:\\api_framework\")\nfrom base.runmethod import RunMethod\nfrom data.get_data import GetData\nfrom base.common_method import *\nimport json\nimport time\nimport requests\nfrom utils.commonutil import CommonUtil\nfrom data.dependent_data import DependentData\nfrom utils.send_email import SendEmail\nfrom utils.operation_json import OperationJson\nfrom utils.operation_header import OPerationHeader\nfrom utils.write_result import *\nfrom utils.operation_excel import OperationExcel\nfrom utils.Excel_Obj import *\nfrom utils.Log import *\nfrom config import config_global\n\n\nclass TestRun(object):\n def __init__(self):\n self.run_method = RunMethod()\n self.data = GetData()\n self.common_util = CommonUtil()\n self.send_email = SendEmail()\n self.excel = OperationExcel()\n self.sheet_obj = self.excel.get_data()\n\n def test_run(self):\n\n res = None\n pass_count = []\n fail_count = []\n skip_count = []\n # 获取多少行\n rows_count = self.data.get_case_lines()\n\n for i in range(2, rows_count + 1):\n run_num = [2, 1]\n is_run = self.data.get_is_run(i)\n message = self.data.get_api_msg(i)\n api_name = self.data.get_api_name(i)\n if is_run:\n\n url_path = self.data.get_request_url(i)\n\n url = config_global.base_url[0] + url_path\n\n method = self.data.get_request_method(i)\n\n data = self.data.get_request_data(i)\n\n code = self.data.get_http_code_data(i)\n\n expect = self.data.get_expect_data(i)\n\n headers = self.data.get_request_headers(i)\n\n depend_Value = self.data.get_depend_value(i) # tiquzhi\n\n set_key = self.data.get_set_key(i)\n\n wait_key = self.data.get_waiting_replace_key(i)\n\n actual_key = self.data.get_actual_replace_key(i)\n\n header = get_header_value()\n\n if data != None:\n if '88888888' in data:\n data = data.replace(\"88888888\", \"17154654546\")\n data = json.loads(data)\n\n if headers != None:\n try:\n with open(depend_data_path, 'r', encoding='utf-8') as f:\n header_value = json.load(f)\n header[headers] = header_value[\"token\"]\n\n except Exception as e:\n logging.info(\"错误为:\", e)\n\n depend_case = self.data.is_depend(i)\n\n if depend_case != None:\n self.depend_data = DependentData(depend_case)\n # 获取的依赖响应\n depend_response_data = self.depend_data.get_data_for_key(i)\n\n # 获取依赖的key\n depend_key = self.data.get_depend_field(i)\n\n # 更新参数值\n data[depend_key] = depend_response_data\n '''待提取的key'''\n if wait_key != None:\n\n try:\n with open(depend_data_path, 'r', encoding='utf-8') as f:\n\n dependvalue = f.read()\n\n depend_value_dict = json.loads(dependvalue)\n\n wait_key_list = str_for_list(wait_key)\n actual_key_list = str_for_list(actual_key)\n\n for index_num in range(len(wait_key_list)):\n Wait_key = wait_key_list[index_num]\n Act_key = actual_key_list[index_num]\n depend_value_key = depend_value_dict[Act_key]\n data[Wait_key] = depend_value_key\n\n except Exception as e:\n logging.info(\"错误为:\", e)\n\n def fail_run():\n response = self.run_method.run_main(method, url, data, header)\n res = response[0]\n # print('response---->',response)\n # print('res---->',res)\n global http_code\n http_code = response[1]\n\n # print(type(http_code), http_code)\n\n # 断言\n\n if int(code) == http_code:\n\n if self.common_util.is_contain(expect, res):\n logging.info('\\033[1;32;m%s接口:%s->接口执行通过\\033[0m' % (api_name, message))\n writeTestResult(excelObj.get_data(), rowNo=i, testResult='pass')\n pass_count.append(i)\n\n if depend_Value != None:\n self.depend_data = DependentData(depend_case)\n self.depend_data.save_depend_value(res, depend_Value, set_key)\n\n\n else:\n fail = run_num[0]\n fail -= 1\n run_num[0] = fail\n\n while run_num[0]:\n fail_num = run_num[1]\n run_num[1] = run_num[1] + 1\n print('第%s次执行失败,开始第%s次执行。。。' % (fail_num, fail_num + 1))\n\n time.sleep(1)\n logging.info(\"\\033[0;43;41m%s接口:%s->接口执行失败\\033[0m\" % (api_name, message))\n\n fail_run()\n\n writeTestResult(excelObj.get_data(), rowNo=i, testResult='faild', errorInfo=res)\n fail_count.append(i)\n\n\n else:\n fail = run_num[0]\n fail -= 1\n run_num[0] = fail\n\n while run_num[0]:\n fail_num = run_num[1]\n run_num[1] = run_num[1] + 1\n\n print('第%s次执行失败,开始第%s次执行。。。' % (fail_num, fail_num + 1))\n\n time.sleep(1)\n logging.info(\"\\033[0;43;41m%s->接口执行失败\\033[0m\" % message)\n\n fail_run()\n\n writeTestResult(excelObj.get_data(), rowNo=i, testResult='faild', errorInfo=res)\n fail_count.append(i)\n\n fail_run()\n else:\n logging.info('%s接口:%s->接口不执行' % (api_name, message))\n skip_count.append(i)\n writeTestResult(excelObj.get_data(), rowNo=i, testResult='skip')\n\n # 发送邮件\n logging.info(\"正在发送邮件,请等待。。。\")\n # self.send_email.send_main(pass_count,fail_count,skip_count)\n\n\nif __name__ == '__main__':\n # run = RuTest()\n # run.test_run()\n pass\n","sub_path":"main/run_test123.py","file_name":"run_test123.py","file_ext":"py","file_size_in_byte":6986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"47270822","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Author: Dominik Gresch \n# Date: 01.02.2015 17:55:46 CET\n# File: mail.py\n\nimport subprocess\n\ndef send(subj='', msg='', dest='greschd@gmx.ch'):\n \"\"\"\n Sends an Email to dest, with given subject (subj) and message (msg)\n \"\"\"\n proc1 = subprocess.Popen(['echo', msg], stdout=subprocess.PIPE)\n proc2 = subprocess.Popen(['mail', '-s', subj, dest], stdin=proc1.stdout)\n proc1.stdout.close()\n return proc2.communicate()[0]\n\n\n","sub_path":"ptools/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"277276243","text":"import numpy as np\nimport matplotlib.pyplot as plt \n# Benjamin Klimko, PHYS 416, Spring 2018\n# Program to find the spectral radius of a matrix involved with the Lax scheme for the advection equation\ndef power1(A,X,eps,max1):\n\t# function to compute the maximum eigenvalue (lambda) of a Matrix A and\n\t# its corresponding eigen vector (eigenvector)\n\t# X is some base vector row matrix, input\n\t# eps is the tolerance you want the eigenvalue to be computed to\n\t# max1 is the maximum number of iteractions allowed\n\tlamda=0.0\n\tcnt=1\n\txnew=X\n\txold=0*X\n\terr=np.linalg.norm(X)\n\txnew = xnew/max(abs(xnew))\n\twhile err>eps and cnt < max1:\n\t\txold=xnew\n\t\tck = max(abs(xnew))\n\t\txnew=np.dot(A,xnew)/ck\n\t\tcnt = cnt+1\n\t\terr = np.linalg.norm(xold-xnew)\n\tif (cnt >=max1):\n\t\tprint('max number of iterations exceeded')\n\teigenvector = xnew/np.linalg.norm(xnew)\n\tlamda = ck\n\treturn lamda,eigenvector\n\n# set Lax scheme matrices\nB = np.zeros((51,51))\nC = np.zeros((51,51))\nx = np.random.randint(5, size=(51,1))\nth = np.linspace(0.1,1.5, 15)\npowval = np.array([])\neigenvals = np.array([])\nonenorm = np.array([])\ninfnorm = np.array([])\n\nfor idx in range(1,50):\n\tB[idx, idx-1] = -1\n\tB[idx, idx+1] = 1\n\tC[idx, idx-1] = 1\n\tC[idx, idx+1] = 1\n\n# matrix edge cases\nB[0,1] = 1\nB[0, -1] = -1\nB[-1,0] = 1\nB[-1,-2] = -1\nC[0,1] = 1\nC[0, -1] = 1\nC[-1,0] = 1\nC[-1,-2] = 1\n\nfor frac in th:\n\tprint('tau/h =', str(frac))\n\tA = ((1/2)*C) - ((frac/2)*B)\n\t# x=np.array([[3.], [2.], [1.]])\n\t\n\teigenvalues = np.linalg.eigvals(A)\n\n\t# get max eigenvalue\n\t# emax = np.amax(eigenvalues)\n\temax = eigenvalues.max()\n\teigenvals = np.append(eigenvals, emax)\n\n\teigenvalue1,eigenvector1=power1(A,x,1.0e-3,20) # power method\n\tpowval = np.append(powval, eigenvalue1)\n\n\teigenvalue2 = np.linalg.norm(A, 1) # 1-norm\n\tonenorm = np.append(onenorm, eigenvalue2)\n\n\teigenvalue3 = np.linalg.norm(A, np.inf) # infinity norm\n\tinfnorm = np.append(infnorm, eigenvalue3)\n\n\tprint('max eigenvalue from numpy eig =',emax)\n\n\tprint('max eigenvalue from powermethod =',eigenvalue1)\n\n\tprint('max eigenvalue from 1-norm =',eigenvalue2)\n\n\tprint('max eigenvalue from inf-norm =',eigenvalue3)\n\n# plot results\nplt.figure()\nplt.plot(th, powval, label='Power method')\nplt.plot(th, eigenvals, label='Numpy eig function')\nplt.plot(th, onenorm, label='1-norm')\nplt.plot(th, infnorm, label='Infinity norm')\nplt.legend()\nplt.show()","sub_path":"Chapter 9 Work/chap9_problem9.py","file_name":"chap9_problem9.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"509619364","text":"from django.http import JsonResponse\nfrom django.views.generic import View\n\n\nclass TestView(View):\n def get(self, request):\n data = {\n 'success': True,\n 'massage': 'This is the test view',\n 'method': request.method\n }\n return JsonResponse(data=data, status=200)\n","sub_path":"src/eLearning/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"543547678","text":"from django.shortcuts import render,render_to_response, redirect\nfrom django.template import RequestContext\nfrom django.contrib.auth import authenticate\nfrom signup.forms import AuthenticationForm, RegistrationForm, WriteForm ,CommentForm\nfrom django.contrib.auth import login , authenticate, logout\n\nfrom django.http import HttpResponse,HttpResponseRedirect,Http404\nfrom django.core.urlresolvers import reverse\nfrom .models import User,Post,Comments\nfrom django.contrib.auth.decorators import login_required\n\ndef inc():\n pass\ninc.var=0\n#@login_required\ndef Index(request):\n posts=Post.objects.order_by('time')[::-1][inc.var:inc.var+1]\n comments=Comments.objects.all()[0:5]\n return render(request,'signup/home.html',{'posts':posts,'commentsform':CommentForm,'comments':comments})\n #if request.user.is_authenticated():\n # return render(request,'signup/home.html',{},context_instance=RequestContext(request))\n #else:\n # return render(request,'signup/signin.html',{'form':AuthenticationForm,})\n\ndef Signin_Form(request):\n return render(request,'signup/signin.html',{'form': AuthenticationForm,})\n\ndef Signin(request):\n if request.method == 'POST':\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n user = authenticate(username=request.POST['username'], password=request.POST['password'])\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect(reverse('signup:index'),context_instance = RequestContext(request))\n else:\n form = AuthenticationForm()\n\ndef Signup(request):\n return render(request,'signup/signup.html',{'form': RegistrationForm,})\n\n\n#def Home(request):\n #return render(request,'signup/home.html',{},context_instance=RequestContext(request))\n\ndef Write(request):\n return render(request,'signup/write.html',{'form': WriteForm,})\n\ndef Signout(request):\n \"\"\"\n Log out view\n \"\"\"\n logout(request)\n return redirect('/')\n\ndef Update_Db(request):\n \"\"\"\n User registration view.\n \"\"\"\n if request.method == 'POST':\n form = RegistrationForm(data=request.POST)\n if form.is_valid():\n user = form.save()\n return redirect('/')\n else:\n form = RegistrationForm()\n return render_to_response('signup/index.html', {'form': form,}, context_instance=RequestContext(request))\n\ndef Post_Write(request):\n form=WriteForm(request.POST)\n if form.is_valid():\n instance=form.save(commit=False)\n instance.writer=request.user\n instance.save()\n inc.var=0\n return redirect(reverse('signup:index'))\n else:\n return redirect('/')\n\ndef Comment_Write(request):\n form=CommentForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect(reverse('signup:index'))\n else:\n return redirect('/')\n\ndef Next(request):\n if (inc.var==Post.objects.count()-1):\n return redirect('/')\n else:\n inc.var+=1\n return redirect(reverse('signup:index'))\n\ndef Back(request):\n if (inc.var==0):\n return redirect('/')\n else:\n inc.var-=1\n return redirect(reverse('signup:index'))\n","sub_path":"signup/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"100418873","text":"#!/bin/env python\n\nimport os, subprocess\nfrom datetime import datetime\nimport plotly\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport pandas as pd\n\ncsv_file = os.getenv('CSV_FILE','./excalibur_population.csv')\nplotly_username = os.getenv('PLOTLY_USERNAME')\nplotly_api_key = os.getenv('PLOTLY_API_KEY')\nplotly.tools.set_credentials_file(username=plotly_username,api_key=plotly_api_key)\n\nif os.path.exists(csv_file):\n file = open(csv_file, 'a')\nelse:\n file = open(csv_file, 'w')\n file.write('utc,count\\n')\n\nnow = datetime.now().replace(microsecond=0).isoformat()\nonline_players = subprocess.check_output(\"curl --silent 'https://www.excalibur.ws' | awk -F '' '{print $2}' | awk -F'' '{print $1}' | xargs\", shell=True).strip()\n\nfile.write(f\"{now},{str(online_players, 'utf-8')}\\n\")\nfile.close()\n\nlayout = go.Layout(\n title='Excalibur population',\n xaxis=dict(title='UTC',rangemode='nonnegative'),\n yaxis=dict(title='Players'),\n autosize=False,\n)\n\ndf = pd.read_csv(csv_file)\n\ndata = [go.Scatter(\n x=df['utc'],\n y=df['count'])]\n\nfig = go.Figure(data=data, layout=layout) \n\nplot_uri = py.plot(fig,filename='excalibur_population')\n\nprint(plot_uri)\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"203494681","text":"# python init_ac_agent.py --board-size 19 agents/ac/ac_v1.hdf5\r\n\r\nimport argparse\r\nimport h5py\r\n\r\nfrom keras.models import Model\r\nfrom keras.layers import Conv2D, Dense, Flatten, Input\r\nimport dlgo.networks\r\nfrom dlgo import encoders\r\nfrom dlgo import rl\r\n\r\n\r\n# 12.5\r\ndef main():\r\n \"\"\"\r\n board_input = Input(shape=encoder.shape(), name='board_input')\r\n\r\n # Add as many convolutional layers as you like\r\n conv1 = Conv2D(64, (3, 3),\r\n padding='same',\r\n activation='relu')(board_input)\r\n conv2 = Conv2D(64, (3, 3),\r\n padding='same',\r\n activation='relu')(conv1)\r\n conv3 = Conv2D(64, (3, 3),\r\n padding='same',\r\n activation='relu')(conv2)\r\n\r\n flat = Flatten()(conv3)\r\n # This example uses hidden layers of size 512.\r\n # Experiment to find the best size.\r\n # The three hidden layers don't need to be the same size\r\n processed_board = Dense(512)(flat)\r\n\r\n # This output yields the policy function\r\n policy_hidden_layer = Dense(512, activation='relu')(processed_board)\r\n policy_output = Dense(encoder.num_points(), activation='softmax')(policy_hidden_layer)\r\n\r\n # This output yields the value function\r\n value_hidden_layer = Dense(512, activation='relu')(processed_board)\r\n value_output = Dense(1, activation='tanh')(value_hidden_layer)\r\n\r\n model = Model(inputs=board_input,\r\n outputs=[policy_output, value_output])\r\n \"\"\"\r\n # added from gh repo\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('--board-size', type=int, default=19)\r\n parser.add_argument('--network', default='large')\r\n parser.add_argument('--hidden-size', type=int, default=512)\r\n parser.add_argument('output_file')\r\n args = parser.parse_args()\r\n\r\n encoder = encoders.get_encoder_by_name('sevenplane', args.board_size)\r\n board_input = Input(shape=encoder.shape(), name='board_input')\r\n\r\n processed_board = board_input\r\n network = getattr(dlgo.networks, args.network)\r\n for layer in network.layers(encoder.shape()):\r\n processed_board = layer(processed_board)\r\n\r\n policy_hidden_layer = Dense(args.hidden_size, activation='relu')(processed_board)\r\n policy_output = Dense(encoder.num_points(), activation='softmax')(policy_hidden_layer)\r\n\r\n value_hidden_layer = Dense(args.hidden_size, activation='relu')(processed_board)\r\n value_output = Dense(1, activation='tanh')(value_hidden_layer)\r\n\r\n model = Model(inputs=[board_input], outputs=[policy_output, value_output])\r\n\r\n new_agent = rl.ACAgent(model, encoder)\r\n with h5py.File(args.output_file, 'w') as outf:\r\n new_agent.serialize(outf)\r\n #\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"init_ac_agent.py","file_name":"init_ac_agent.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"640650594","text":"from django.conf.urls import url\nfrom . import views #importing views of this app to joind them to URLS\n\napp_name= 'blog' #to find app's url better and faster\n\nurlpatterns = [\n url(r'^$', views.index , name='index' ), #we used as_view() function to reach Index class of our view\n url(r'^(?P[0-9]+)$', views.post_detail , name='post-detail' ),\n url(r'^(?P[0-9]+)/add-comment/$', views.comment_handler , name='post-like-handle' ),\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"351488853","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nuse purchases.txt\nThe input file entries of each line are tab delimitted, except\nthe multi-word names which is space delimitted.\n\"\"\"\nimport sys\n\n\ndef mapper():\n totval = 0.\n totnum = 0\n\n # 2012-01-01 \\t 09:00\t\\t San Jose \\t Men's Clothing \\t 214.05 \\t Amex\n for line in sys.stdin:\n data = line.strip().split(\"\\t\")\n if(len(data) != 6):\n continue\n date, time, store, cat, amount, method = data\n\n totval += float(amount)\n totnum += 1\n\n print(\"{0}\\t{1}\".format(totnum, totval))\n\nmapper()\n\n# method of string streaming\nstr_input = \"first sec 2q34dfrd5 e\"\n\n\ndef str_2_std_in():\n import io\n sys.stdin = io.StringIO(str_input)\n for line in sys.stdin:\n data = line.strip().split(\"\\t\")\n print(data)\n sys.stdin = sys.__stdin__\n # to get contents, sys.stdin.read()\n","sub_path":"mapper_total.py","file_name":"mapper_total.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280233759","text":"try:\n from astropy.io import fits as pyfits\nexcept ImportError:\n from astropy.io import fits as pyfits\n\nimport matplotlib.pyplot as plt\nimport stregion\n\nimport math\n\nfrom mpl_toolkits.axes_grid1 import ImageGrid\nimport pywcsgrid2\n\n\nfrom demo_helper import pyfits_card_fromstring\n\n\ndef get_test_header():\n cards = pyfits.CardList()\n for l in open(\"sample_fits01.header\"):\n card = pyfits_card_fromstring(l.strip())\n cards.append(card)\n h = pyfits.Header(cards)\n return h\n\nif 1:\n\n region_list = [\"test_text.reg\", \"test_context.reg\"]\n\n h = get_test_header()\n\n n = len(region_list)\n nx = int(math.ceil(n**.5))\n ny = int(math.ceil(1.*n/nx))\n\n\n fig = plt.figure(1, figsize=(7,5))\n fig.clf()\n nrows_ncols = (ny, nx)\n grid= ImageGrid(fig, 111, nrows_ncols,\n ngrids=n, add_all=True, share_all=True,\n axes_class=(pywcsgrid2.Axes, dict(header=h)))\n\n ax = grid[0]\n ax.set_xlim(300, 1300)\n ax.set_ylim(300, 1300)\n ax.set_aspect(1)\n\n #plt.imshow(d, origin=\"lower\", cmap=plt.cm.gray_r)\n\n from mpl_toolkits.axes_grid.anchored_artists import AnchoredText\n\n for ax, reg_name in zip(grid, region_list):\n r = stregion.open(reg_name).as_imagecoord(h)\n\n patch_list, text_list = r.get_mpl_patches_texts()\n for p in patch_list:\n ax.add_patch(p)\n for t in text_list:\n ax.add_artist(t)\n\n\n atext = AnchoredText(reg_name.replace(\"_\", r\"\\_\"),\n loc=2)\n ax.add_artist(atext)\n\n plt.draw()\n plt.show()\n","sub_path":"examples/demo_region03.py","file_name":"demo_region03.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248146391","text":"def checkPeriodContinuity(train_df, test_df):\n def filterSort(X_df):\n return X_df[(X_df['country'] == 1)].sort_values(by=[\"period\"]).set_index(\"period\")\n\n def printLine(X_df_sorted):\n start_span = 130\n end_span = 150\n prefix = 1\n suffix = \"_diffImports(kmt)\"\n print(X_df_sorted.ix[start_span:end_span, [str(prefix) + suffix, str(prefix + 1) + suffix]])\n\n train_df_sorted = filterSort(train_df)\n test_df_sorted = filterSort(test_df)\n printLine(train_df_sorted)\n printLine(test_df_sorted)\n\ndef countryTypeFeature(train_df):\n print(train_df.sort_values(by=[\"period\", \"country\"])[[\"period\", \"country\", \"Target\"]].head(30))\n sorted_train_df = train_df.sort_values(by=['period', 'country'])\n df_oilImporters = sorted_train_df.ix[\n sorted_train_df[\"oilImporters_1\"] == 1, [\"period\", \"country\", \"Target\", \"meanProd\"]]\n df_oilExporters = sorted_train_df.ix[\n sorted_train_df[\"oilExporters_1\"] == 1, [\"period\", \"country\", \"Target\", \"meanProd\"]]\n print(df_oilImporters.head())\n","sub_path":"tools/stats_dataframe.py","file_name":"stats_dataframe.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"117905984","text":"# -*- coding: utf-8 -*-\nfrom model.contact import Contact\n\ndef test_add_address_book(app, db, json_contacts, check_ui):\n contact = json_contacts\n old_contact = db.get_contact_list()\n app.contact.create_address_book(contact)\n #assert len(old_contact) + 1 == app.contact.count()\n new_contact = db.get_contact_list()\n old_contact.append(contact)\n assert sorted(old_contact, key=Contact.id_or_max) == sorted(new_contact, key=Contact.id_or_max)\n if check_ui:\n assert sorted(new_contact, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(),key=Contact.id_or_max)\n\n","sub_path":"test/test_add_address_book.py","file_name":"test_add_address_book.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"351947546","text":"#!/usr/bin/python\n# Copyright: Ansible Project\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'certified'}\n\n\nDOCUMENTATION = '''\n---\nmodule: s3_bucket_facts\nshort_description: get information about an s3 bucket\ndescription:\n - Module search for s3 buckets\nversion_added: \"2.7\"\nrequirements: [ boto3 ]\noptions:\n name:\n description:\n - name of the S3 bucket\nextends_documentation_fragment:\n - aws\n'''\n\nEXAMPLES = '''\n- s3_bucket_facts:\n name: example-bucket\n'''\n\nRETURN = '''\ns3_bucket\n\n \"creation_date\": \"2014-04-09T16:21:02+00:00\",\n \"name\": \"example-bucket\"\n\nhttps://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.list_buckets\n'''\n\n\ntry:\n import botocore\nexcept ImportError:\n pass # caught by AnsibleAWSModule\n\nfrom ansible.module_utils.aws.core import AnsibleAWSModule\nfrom ansible.module_utils._text import to_native\nfrom ansible.module_utils.ec2 import boto3_conn, get_aws_connection_info, ec2_argument_spec, camel_dict_to_snake_dict\n\n\ndef get_s3_bucket(module, client):\n \"\"\"[summary]\n\n [description]\n\n Arguments:\n module {[type]} -- [description]\n client {[type]} -- [description]\n \"\"\"\n try:\n buckets = camel_dict_to_snake_dict(client.list_buckets())['buckets']\n for bucket in buckets:\n if bucket['name'] == module.params.get('name'):\n return bucket\n except botocore.exceptions.ClientError as e:\n module.fail_json_aws(e, msg='Unexpected error {0}'.format(to_native(e)))\n return False\n\n\ndef main():\n \"\"\"\n Module action handler\n \"\"\"\n argument_spec = ec2_argument_spec()\n argument_spec.update(dict(\n id=dict(),\n name=dict(),\n ))\n\n module = AnsibleAWSModule(argument_spec=argument_spec,\n supports_check_mode=True)\n\n region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)\n client = boto3_conn(\n module,\n conn_type='client',\n resource='s3',\n region=region,\n endpoint=ec2_url,\n **aws_connect_kwargs)\n\n # only support pre-constructed domain_name or now\n bucket = get_s3_bucket(module, client)\n\n module.exit_json(changed=False, ansible_facts=bucket)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/s3_bucket_facts.py","file_name":"s3_bucket_facts.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"458812366","text":"\"\"\"\nPA6.py - implementing a bloom filter\nDate - -03/10/21 \nAuthor - Daniel Throop\nClass - COSC 3100\n\n\"\"\"\n\nimport numpy as np\nimport random\nLENGTH = 4096\nMASK = 0xfff\n\ndef hasher5(ix):\n\treturn (17377*ix**2>>4)&MASK, ((17377*(ix+5)**2)>>8)&MASK,((10607*(ix+7)**2)>>2)&MASK, ((21193*(ix+9)**2)>>12)&MASK, ((35527*(ix+11)**2)>>10)&MASK \n\nclass Bloom:\n\tdef __init__(self, LENGTH, MASK, hasher):\n\t\tself.length = LENGTH\n\t\tself.mask = MASK\n\t\tself.array = np.zeros(LENGTH, dtype = bool)\n\t\tself.hasher = hasher\n\n\tdef insert(self, x):\n\t\t# returns indices to insert number into bloom filter\n\t\tindices = hasher5(x)\n\t\t# sets specific indices equal to True \n\t\tself.array[indices[0]] = True\n\t\tself.array[indices[1]] = True\n\t\tself.array[indices[2]] = True\n\t\tself.array[indices[3]] = True\n\t\tself.array[indices[4]] = True\n\t\tprint(\"Inserted: \" + str(x))\n\n\tdef look_up(self, x):\n\t\t# returns indices to look up number in bloom filter\n\t\tindices = hasher5(x)\n\t\tif(np.all([self.array[indices[0]], self.array[indices[1]], self.array[indices[2]], self.array[indices[3]], self.array[indices[4]]])):\n\t\t\t# number is probably in bloom filter\n\t\t\treturn True\n\t\t# the number is not in the bloom filter\n\t\treturn False\n\n# creating bloom filter\nmy_bloom = Bloom(LENGTH, MASK, hasher5)\n\n# inserting 200 random integers\nfor i in random.sample(range(my_bloom.length), 200):\n\tmy_bloom.insert(i)\n\nprint(\"200 random integers inserted.\")\n\n# generate 100000 random integers to check false positive rate\ncount = 0\nfor i in range(100000):\n\tx = random.randint(200, 10000000)\n\tif(my_bloom.look_up(x)):\n\t\tcount += 1\n\n# print number of false positives\nprint(\"Number of false positives: \" + str(count))\n\n\n\n\n\n\n\n\n","sub_path":"Programming_Assignments/6/PA6.py","file_name":"PA6.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"91505570","text":"n = int(input())\nk = int(input())\n\nprint(\"The value of n & k are\",n,k)\n\ns = []\nwhile n > 0:\n val = int(input())\n s.append(val)\n n -= 1\n\nprint(\"S is:\", s)\n\ns = sorted(s, reverse=True)\nv = [c for c in s if c >= k]\nprint(\"v is:\", v)\nprint(len(v))","sub_path":"contests/next_rounds.py","file_name":"next_rounds.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"373190849","text":"class Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n if len(nums)>0:\n lower = 0\n upper = len(nums)-1\n if upper != lower:\n mid = (upper + lower)/2\n nums = self.divide(nums, lower, mid)\n nums = self.divide(nums, mid + 1, upper)\n nums = self.merge(nums, lower, upper)\n\n\n def divide(self, nums, lower, upper):\n if upper == lower:\n return nums\n mid = (upper + lower)/2\n nums = self.divide(nums, lower, mid)\n nums = self.divide(nums, mid + 1, upper)\n return self.merge(nums, lower, upper)\n\n\n def merge(self, nums, lower, upper):\n if upper == lower:\n return nums\n mid = (upper + lower)/2\n count = 0\n for i in xrange(lower, mid+1):\n if nums[i] == 0:\n count += 1\n i = count\n j = mid + 1\n while j <= upper and nums[j] != 0:\n nums[j - count] = nums[j]\n j += 1\n while i != 0:\n nums[j-i] = 0\n i -= 1\n return nums\n","sub_path":"moveZeroes.py","file_name":"moveZeroes.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76349809","text":"# Add the functions in this file\nimport json\nimport math\n\ndef load_journal(path):\n f = open(path)\n journal = json.load(f)\n f.close()\n return journal\n\n# print(load_journal('journal.json'))\n\ndef compute_phi(path,event):\n journal = load_journal(path)\n n11, n00, n10, n01 = 0, 0, 0, 0\n for item in journal:\n if event in item['events']:\n if item['squirrel'] == True:\n n11 += 1 \n else:\n n10 += 1\n elif item['squirrel'] == True:\n n01 += 1\n else:\n n00 += 1\n n1p = n11 + n10\n n0p = n01 + n00\n np0 = n00 + n10\n np1 = n11 + n01\n corr = (n11 * n00 - n10 * n01) / math.sqrt(n1p * n0p * np1 * np0)\n return corr\n\n\ndef compute_correlations(path):\n corr = {}\n journal = load_journal(path)\n for item in journal:\n for e in item[\"events\"]:\n if e not in corr:\n corr[e] = compute_phi(path,e)\n return corr\n\n\ndef diagnose(path):\n corr = compute_correlations(path)\n key_list = list(corr.keys())\n val_list = list(corr.values())\n hp = val_list.index(max(val_list))\n hp_event = key_list[hp]\n hn = val_list.index(min(val_list))\n hn_event = key_list[hn]\n return hp_event, hn_event\n","sub_path":"correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"498140294","text":"j=input(\"Enter 'E' to encode, 'D' to decode, 'X' to exit - \")\nj=j.upper()\nif j=='E':\n me=[]\n print(\"Enter the message to encode\")\n c=input(\"Message - \")\n s=list(c)\n for l in s:\n l=int(ord(l))\n me.append(l)\n print (\"Encoded message - \",me)\nelif j=='D':\n print(\"Enter # to stop\")\n md=\"\"\n while True:\n d=input(\"Value - \")\n if d=='#':\n break\n md=md+chr(int(d))\n print(\"Decoded message - \",md)\ninput()\n","sub_path":"ASCii.py","file_name":"ASCii.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"427160549","text":"# encoding: utf-8\nimport os\nimport unittest\nfrom selenium import webdriver\nfrom tests.lib.pages import AdCreatePage, LoginPage, AdsCampaignsPage, AdEditPage\n\n\nclass TargetMailRuTestCase(unittest.TestCase):\n def setUp(self):\n self.login = 'tech-testing-ha2-13'\n self.domain = '@bk.ru'\n self.password = os.environ['TTHA2PASSWORD']\n\n browser = os.environ.get('TTHA2BROWSER', 'FIREFOX')\n\n self.driver = webdriver.Remote(\n command_executor='http://127.0.0.1:4444/wd/hub',\n desired_capabilities=getattr(webdriver.DesiredCapabilities, browser).copy()\n )\n\n self.__authorize()\n\n def tearDown(self):\n self.driver.quit()\n\n def __authorize(self):\n login_page = LoginPage(self.driver)\n login_page.authorize(self.login, self.domain, self.password)\n\n def __get_ad_create_page_image_path(self):\n project_dir = os.path.dirname(os.path.dirname(__file__))\n image_path = os.path.join(project_dir, 'resources', 'image.png')\n\n return image_path\n\n def test_authorization(self):\n ad_create_page = AdCreatePage(self.driver)\n\n assert ad_create_page.is_authorized(self.login, self.domain)\n\n def __fill_ad_create_page_banner_info(self, ad_create_page):\n ad_create_page.campaign_name.clear()\n ad_create_page.campaign_name = 'Campaign!'\n ad_create_page.banner_title = 'Title'\n ad_create_page.banner_text = 'Text text text'\n ad_create_page.banner_url = 'www.example.com'\n\n ad_create_page.banner_image = self.__get_ad_create_page_image_path()\n\n def test_ad_create_page_banner_image_uploading(self):\n ad_create_page = AdCreatePage(self.driver)\n\n self.__fill_ad_create_page_banner_info(ad_create_page)\n\n assert ad_create_page.banner_image_preview_display == 'block'\n\n def __fill_ad_create_page_target_restrict(self, ad_create_page, value):\n ad_create_page.target_restrict_switch.click()\n ad_create_page.get_target_restrict_by_value(value).click()\n\n def __clean_up_last_ad_campaign(self, ad_campaigns_page):\n ad_campaigns_page.delete_first_campaign_button.click()\n\n def test_ad_create_page_do_not_fill_restrict_and_region(self):\n ad_create_page = AdCreatePage(self.driver)\n\n self.__fill_ad_create_page_banner_info(ad_create_page)\n\n default_target_region = ad_create_page.get_target_region_chosen()\n\n ad_create_page.submit_button.click()\n\n ad_campaigns_page = AdsCampaignsPage(self.driver, force_load=False)\n ad_campaigns_page.edit_first_campaign_button.click()\n\n ad_edit_page = AdEditPage(self.driver, force_load=False)\n\n assert ad_edit_page.target_restrict_switch.text() == u'Не учитывать'\n assert ad_edit_page.get_target_region_chosen() == default_target_region\n\n self.driver.back()\n self.__clean_up_last_ad_campaign(ad_campaigns_page)\n\n def test_ad_create_page_fill_restrict_and_region(self):\n target_restrict_value = '12+'\n target_region_value = u'Европа'\n\n ad_create_page = AdCreatePage(self.driver)\n\n self.__fill_ad_create_page_banner_info(ad_create_page)\n self.__fill_ad_create_page_target_restrict(ad_create_page, target_restrict_value)\n\n ad_create_page.deselect_all_target_region_chosen()\n region = ad_create_page.get_target_region_by_name(target_region_value)\n region.click()\n\n assert ad_create_page.target_restrict_switch.text() == target_restrict_value\n assert ad_create_page.get_target_region_chosen() == [target_region_value]\n\n ad_create_page.submit_button.click()\n\n ad_campaigns_page = AdsCampaignsPage(self.driver, force_load=False)\n ad_campaigns_page.edit_first_campaign_button.click()\n\n ad_edit_page = AdEditPage(self.driver, force_load=False)\n\n assert ad_edit_page.target_restrict_switch.text() == target_restrict_value\n assert ad_edit_page.get_target_region_chosen() == [target_region_value]\n\n self.driver.back()\n self.__clean_up_last_ad_campaign(ad_campaigns_page)\n\n def test_ad_create_page_fill_restrict_and_region_with_suggester(self):\n target_restrict_value = '0+'\n target_region_value = u'Европа'\n\n ad_create_page = AdCreatePage(self.driver)\n\n self.__fill_ad_create_page_banner_info(ad_create_page)\n self.__fill_ad_create_page_target_restrict(ad_create_page, target_restrict_value)\n\n ad_create_page.deselect_all_target_region_chosen()\n ad_create_page.target_region_suggester = target_region_value + '\\n'\n\n assert ad_create_page.target_restrict_switch.text() == target_restrict_value\n assert ad_create_page.get_target_region_chosen() == [target_region_value]\n\n ad_create_page.submit_button.click()\n\n ad_campaigns_page = AdsCampaignsPage(self.driver, force_load=False)\n ad_campaigns_page.edit_first_campaign_button.click()\n\n ad_edit_page = AdEditPage(self.driver, force_load=False)\n\n assert ad_edit_page.target_restrict_switch.text() == target_restrict_value\n assert ad_edit_page.get_target_region_chosen() == [target_region_value]\n\n self.driver.back()\n self.__clean_up_last_ad_campaign(ad_campaigns_page)","sub_path":"tests/target_mail_ru.py","file_name":"target_mail_ru.py","file_ext":"py","file_size_in_byte":5285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579494365","text":"#merge tow lists\ndef mergeSortedLists(listA, listB):\n newList = list()\n a = 0;\n b = 0;\n\n while a < len (listA) and b < len(listB):\n if listA[a] < listB[b]:\n newList.append(listA[a])\n a+=1\n else:\n newList.append(listB[b])\n b+=1\n\n # add the rest\n while a < len(listA):\n newList.append(listA[a])\n a+=1\n while b < len (listB):\n newList.append(listB[b])\n b+=1\n return newList\n \nlist1 = [4,6,7,9]\nlist2 = [1,2,5,7,8,9]\n\nprint(list1)\nprint(list2)\n\nprint(mergeSortedLists(list1, list2))","sub_path":"datastructures/merge_lists.py","file_name":"merge_lists.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"205134397","text":"from datetime import timedelta\nfrom decimal import Decimal\nfrom unittest.mock import patch\n\nfrom django.test import TestCase\nfrom django.utils.timezone import now\nfrom model_bakery import baker\nfrom requests_mock import Mocker\nfrom rest_framework.test import APIClient\nfrom rest_framework_simplejwt.tokens import RefreshToken\n\nfrom cashback.api import ChoiceField\nfrom cashback.client import SaldoAPI\nfrom cashback.models import Vendedor, Compra\nfrom cashback.utils import digito_mod11\n\n\nclass VendedorTests(TestCase):\n def setUp(self):\n self.cpf_magico = '15350946056'\n self.cpf_magico_formatado = '153.509.460-56'\n self.vendedor = baker.make('cashback.Vendedor')\n\n def test_nome_junta_first_name_e_last_name(self):\n first_name_e_last_name = self.vendedor.first_name + ' ' + self.vendedor.last_name\n self.assertEqual(self.vendedor.nome, first_name_e_last_name)\n\n def test_nome_atribui_first_name_e_last_name(self):\n first_name = 'Fulano'\n last_name = 'da Silva'\n nome = f'{first_name} {last_name}'\n vendedor = baker.make('cashback.Vendedor')\n vendedor.nome = nome\n self.assertEqual(vendedor.first_name, first_name)\n self.assertEqual(vendedor.last_name, last_name)\n\n def test_separar_nome_sobrenome_none_retorna_none_e_none(self):\n first, last = Vendedor.separar_nome_sobrenome(None)\n self.assertIsNone(first)\n self.assertIsNone(last)\n\n def test_separar_nome_sobrenome_apenas_um_nome(self):\n nome = 'Fulano'\n first, last = Vendedor.separar_nome_sobrenome(nome)\n self.assertEqual(first, nome)\n self.assertIsNone(last)\n\n def test_sanitizar_cpf_vazio_invalido(self):\n self.assertIsNone(Vendedor.sanitizar_cpf(None))\n\n def test_sanitizar_cpf_semnumeros_invalido(self):\n self.assertIsNone(Vendedor.sanitizar_cpf('qwertyuiop'))\n\n def test_sanitizar_cpf_poucos_numeros_invalido(self):\n self.assertIsNone(Vendedor.sanitizar_cpf('123'))\n\n def test_sanitizar_cpf_muitos_numeros_invalido(self):\n self.assertIsNone(Vendedor.sanitizar_cpf('123456789012'))\n\n def test_sanitizar_cpf_cpf_magico_valido(self):\n self.assertEqual(Vendedor.sanitizar_cpf(self.cpf_magico), self.cpf_magico)\n\n def test_sanitizar_cpf_invalido(self):\n cpf_invalido = '12345678912'\n self.assertIsNone(Vendedor.sanitizar_cpf(cpf_invalido))\n\n def test_sanitizar_cpf_cpf_magico_formatado_valido(self):\n self.assertEqual(Vendedor.sanitizar_cpf(self.cpf_magico_formatado), self.cpf_magico)\n\n def test_str_retorna_nome(self):\n self.assertEqual(str(self.vendedor), self.vendedor.nome)\n\n\nclass CompraTests(TestCase):\n def setUp(self):\n self.cpf_magico = '15350946056'\n self.compra = baker.make('cashback.Compra')\n\n def test_cashback_zero_sem_valor(self):\n self.compra.valor = 0\n self.assertEqual(self.compra.cashback, 0)\n\n def test_cashback_zero_sem_percentual(self):\n self.compra.percentual_cashback = 0\n self.assertEqual(self.compra.cashback, 0)\n\n def test_cachback_percentual_negativo(self):\n self.compra.percentual_cashback = -1\n with self.assertRaises(ValueError):\n _ = self.compra.cashback\n\n def test_cachback_percentual_maior_que_vinte(self):\n self.compra.percentual_cashback = 21\n with self.assertRaises(ValueError):\n _ = self.compra.cashback\n\n def test_cashback_calculado_corretamente(self):\n self.compra.valor = 200\n self.compra.percentual_cashback = 10\n self.assertAlmostEqual(self.compra.cashback, 20)\n\n def test_status_inicial_em_validacao(self):\n self.assertNotEqual(self.compra.vendedor.cpf, self.cpf_magico)\n self.assertEqual(self.compra.get_status_inicial(), \"V\")\n\n def test_status_inicial_cpf_magico(self):\n self.compra.vendedor.cpf = self.cpf_magico\n self.assertEqual(self.compra.get_status_inicial(), \"A\")\n\n def test_save_preenche_status(self):\n self.compra.status = None\n self.compra.save()\n self.assertIsNotNone(self.compra.status)\n\n def test_percentual_cashback_valor_negativo(self):\n valor = -1\n self.assertAlmostEqual(self.compra.get_percentual_cashback(valor), 0)\n\n def test_percentual_cashback_valor_1(self):\n valor = 1\n self.assertAlmostEqual(self.compra.get_percentual_cashback(valor), 10)\n\n def test_percentual_cashback_valor_999(self):\n valor = 999\n self.assertAlmostEqual(self.compra.get_percentual_cashback(valor), 10)\n\n def test_percentual_cashback_valor_1000(self):\n valor = 1000\n self.assertAlmostEqual(self.compra.get_percentual_cashback(valor), 15)\n\n def test_percentual_cashback_valor_1500(self):\n valor = 1500\n self.assertAlmostEqual(self.compra.get_percentual_cashback(valor), 15)\n\n def test_percentual_cashback_valor_1501(self):\n valor = 1501\n self.assertAlmostEqual(self.compra.get_percentual_cashback(valor), 20)\n\n def test_percentual_cashback_valor_99999(self):\n valor = 99999\n self.assertAlmostEqual(self.compra.get_percentual_cashback(valor), 20)\n\n def test_save_atualiza_cashback_ultimos_30_dias(self):\n cpf = \"35770006005\"\n trinta_e_um_dias = now() - timedelta(days=31)\n trinta_dias = now() - timedelta(days=30)\n\n vendedor = Vendedor.objects.create(cpf=cpf)\n\n # Essa compra não deve impactar no somatóro. % original é de 20%\n compra_trinta_e_um_dias = Compra.objects.create(codigo=\"123457\", vendedor=vendedor, valor=Decimal(2000),\n data=trinta_e_um_dias)\n\n # Essa compra deve impactar no somatório. % original é de 10%\n compra_trinta_dias = Compra.objects.create(codigo=\"123458\", vendedor=vendedor, valor=Decimal(999),\n data=trinta_dias)\n self.assertEqual(compra_trinta_dias.percentual_cashback, 10)\n\n # Com essa compra o novo percentual deve subir para 15%\n compra = Compra()\n compra.codigo = \"123459\"\n compra.vendedor = vendedor\n compra.data = now()\n compra.valor = Decimal(100)\n compra.save()\n self.assertEqual(compra.percentual_cashback, 15)\n\n # Essa compra não deve ter sido alterada\n compra_trinta_e_um_dias.refresh_from_db()\n self.assertEqual(compra_trinta_e_um_dias.percentual_cashback, 20)\n\n # Essa compra deve ter sido alterada para 15%\n compra_trinta_dias.refresh_from_db()\n self.assertEqual(compra_trinta_dias.percentual_cashback, 15)\n\n def test_save_atualiza_cashback_ultimos_30_dias_mesmo_vendedor(self):\n cpf = \"35770006005\"\n cpf_outro_vendedor = \"87103564019\"\n trinta_dias = now() - timedelta(days=30)\n\n vendedor = Vendedor.objects.create(cpf=cpf, username=\"vendedor\")\n outro_vendedor = Vendedor.objects.create(cpf=cpf_outro_vendedor, username=\"outro-vendedor\")\n\n # Essa compra não deve impactar no somatóro pois é de outro vendedor\n compra_outro_vendedor = Compra.objects.create(codigo=\"234567\", vendedor=outro_vendedor, valor=Decimal(2000),\n data=trinta_dias)\n\n # Essa compra deve impactar no somatório. % original é de 10%\n compra_trinta_dias = Compra.objects.create(codigo=\"234568\", vendedor=vendedor, valor=Decimal(999),\n data=trinta_dias)\n self.assertEqual(compra_trinta_dias.percentual_cashback, 10)\n\n # Com essa compra o novo percentual deve subir para 15%\n compra = Compra(codigo=\"234569\", vendedor=vendedor, data=now(), valor=Decimal(100))\n compra.save()\n self.assertEqual(compra.percentual_cashback, 15)\n\n # Essa compra não deve ter sido alterada\n compra_outro_vendedor.refresh_from_db()\n self.assertEqual(compra_outro_vendedor.percentual_cashback, 20)\n\n # Essa compra deve ter sido alterada para 15%\n compra_trinta_dias.refresh_from_db()\n self.assertEqual(compra_trinta_dias.percentual_cashback, 15)\n\n\nclass UtilsTests(TestCase):\n\n def test_digito_mod11_vazio_retorna_zero(self):\n self.assertEqual(digito_mod11([]), 0)\n\n def test_digito_mod11_cpf_magico(self):\n cpf_magico = [1, 5, 3, 5, 0, 9, 4, 6, 0, 5, 6]\n self.assertEqual(digito_mod11(cpf_magico[:9]), cpf_magico[9])\n self.assertEqual(digito_mod11(cpf_magico[:10]), cpf_magico[10])\n\n\nclass ChoiceFieldTest(TestCase):\n def test_to_representation_allow_blank(self):\n field = ChoiceField(choices=(), allow_blank=True)\n self.assertEqual(field.to_representation(\"\"), \"\")\n\n def test_to_representation_convert_to_value(self):\n key = 'foo'\n value = 'bar'\n choices = (\n (key, value)\n )\n field = ChoiceField(choices=choices)\n self.assertEqual(field.to_representation(value), value)\n\n\nclass SaldoAPITest(TestCase):\n\n def setUp(self):\n self.client = SaldoAPI()\n self.client.base_url = \"http://test.com\"\n self.cpf = \"12312312323\"\n\n def test_get_config_from_settings(self):\n url = 'http://example.com'\n token = 'foo'\n with self.settings(SALDO_API=url, SALDO_API_TOKEN=token):\n client = SaldoAPI()\n self.assertEqual(client.base_url, url)\n self.assertEqual(client.session.headers, {\"token\": token})\n\n def test_invalid_response_400_from_api(self):\n with Mocker() as request_mocker:\n request_mocker.get('http://test.com/v1/cashback', status_code=400)\n self.assertIsNone(self.client.get_saldo(self.cpf))\n\n def test_invalid_response_500_from_api(self):\n with Mocker() as request_mocker:\n request_mocker.get('http://test.com/v1/cashback', status_code=500)\n self.assertIsNone(self.client.get_saldo(self.cpf))\n\n def test_invalid_json_from_api(self):\n with Mocker() as request_mocker:\n mocked_response = {\n \"statusCode\": 404,\n \"body\": {\n \"credit\": 1234\n }\n }\n request_mocker.get('http://test.com/v1/cashback', json=mocked_response)\n self.assertIsNone(self.client.get_saldo(self.cpf))\n\n def test_saldo_sucesso(self):\n with Mocker() as request_mocker:\n mocked_response = {\n \"statusCode\": 200,\n \"body\": {\n \"credit\": 2345\n }\n }\n request_mocker.get('http://test.com/v1/cashback', json=mocked_response)\n self.assertAlmostEqual(self.client.get_saldo(self.cpf), 23.45)\n\n\nclass APITest(TestCase):\n\n def setUp(self):\n self.client = APIClient()\n self.payload_vendedor = {\"login\": \"dev\", \"nome\": \"Dev da Silva\", \"email\": \"dev@boticario.com.br\", \"senha\": \"dev@12345\", \"cpf\": \"15350946056\"}\n self.payload_compra = {\"codigo\": \"123456\", \"valor\": \"100\", \"cpf\": \"15350946056\"}\n\n def autenticate_client(self, client=None, cpf=None):\n if not cpf:\n cpf = self.payload_vendedor[\"cpf\"]\n if not client:\n client = self.client\n\n vendedor = Vendedor.objects.filter(cpf=cpf).first()\n if not vendedor:\n vendedor = Vendedor.objects.create_user(username='Foo', email='foo@example.com', password='foo@bar',\n cpf=cpf)\n refresh = RefreshToken.for_user(vendedor)\n client.credentials(HTTP_AUTHORIZATION=f'Bearer {refresh.access_token}')\n\n def test_criar_vendedor_sucesso(self):\n response = self.client.post('/v1/vendedor', self.payload_vendedor, format='json')\n self.assertEqual(response.status_code, 201)\n\n def test_criar_vendedor_sucesso_senha_escondida(self):\n response = self.client.post('/v1/vendedor', self.payload_vendedor, format='json')\n data = response.json()\n self.assertEqual(data[\"senha\"], \"******\")\n\n def test_criar_vendedor_em_branco_400(self):\n payload = {}\n response = self.client.post('/v1/vendedor', payload, format='json')\n self.assertEqual(response.status_code, 400)\n\n def test_criar_vendedor_cpf_invalido(self):\n self.payload_vendedor[\"cpf\"] = \"123\"\n response = self.client.post('/v1/vendedor', self.payload_vendedor, format='json')\n self.assertEqual(response.status_code, 400)\n data = response.json()\n self.assertEqual(data[\"cpf\"], [\"CPF 123 inválido\"])\n\n def test_criar_vendedor_email_obrigatorio(self):\n del self.payload_vendedor[\"email\"]\n response = self.client.post('/v1/vendedor', self.payload_vendedor, format='json')\n self.assertEqual(response.status_code, 400)\n data = response.json()\n self.assertEqual(data[\"email\"], [\"Este campo é obrigatório.\"])\n\n def test_login_vendedor_sucesso(self):\n login = \"teste\"\n senha = \"senha@123\"\n Vendedor.objects.create_user(username=login, password=senha)\n payload = {\"login\": login, \"senha\": senha}\n response = self.client.post('/v1/vendedor/login', payload, format='json')\n data = response.json()\n self.assertEqual(response.status_code, 200)\n self.assertIn(\"access\", data)\n self.assertIn(\"refresh\", data)\n\n def test_login_vendedor_incorreto(self):\n payload = {\"login\": \"teste\", \"senha\": \"senha\"}\n response = self.client.post('/v1/vendedor/login', payload, format='json')\n data = response.json()\n self.assertEqual(response.status_code, 400)\n self.assertEqual({'erro': 'Login ou senha incorretos'}, data)\n\n def test_login_vendedor_em_branco(self):\n response = self.client.post('/v1/vendedor/login', {}, format='json')\n data = response.json()\n self.assertEqual(response.status_code, 400)\n self.assertIn(\"login\", data)\n self.assertIn(\"senha\", data)\n\n def test_login_vendedor_refresh_token_sucesso(self):\n login = \"token\"\n senha = \"senha@456\"\n Vendedor.objects.create_user(username=login, password=senha)\n response = self.client.post('/v1/vendedor/login', {\"login\": login, \"senha\": senha}, format='json')\n data = response.json()\n self.assertEqual(response.status_code, 200)\n self.assertIn(\"refresh\", data)\n refresh = data[\"refresh\"]\n response = self.client.post('/v1/vendedor/refresh_token', {\"refresh\": refresh}, format='json')\n self.assertEqual(response.status_code, 200)\n self.assertIn(\"access\", data)\n\n def test_login_vendedor_refresh_token_invalido(self):\n payload = {\"refresh\": \"foo\"}\n response = self.client.post('/v1/vendedor/refresh_token', payload, format='json')\n data = response.json()\n self.assertEqual(response.status_code, 400)\n self.assertEqual({\"refresh\": [\"Token inválido\"]}, data)\n\n def test_login_vendedor_refresh_sem_token(self):\n response = self.client.post('/v1/vendedor/refresh_token', {}, format='json')\n data = response.json()\n self.assertEqual(response.status_code, 400)\n self.assertEqual({\"refresh\": [\"Este campo é obrigatório.\"]}, data)\n\n def test_compra_precisa_de_login(self):\n response = self.client.post('/v1/compra')\n self.assertEqual(response.status_code, 401)\n\n def test_compra_options_autenticado(self):\n self.autenticate_client()\n response = self.client.options('/v1/compra')\n self.assertEqual(response.status_code, 200)\n\n def test_compra__cpf_invalido(self):\n cpf_venda = '1234567891'\n self.autenticate_client()\n self.payload_compra['cpf'] = cpf_venda\n response = self.client.post('/v1/compra', data=self.payload_compra, format=\"json\")\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json(), {\"cpf\": [f\"CPF {cpf_venda} inválido\"]})\n\n def test_compra_invalida_cpf_diferente(self):\n cpf_autenticado = '15350946056'\n cpf_venda = '67674926044'\n self.autenticate_client(cpf=cpf_autenticado)\n self.payload_compra['cpf'] = cpf_venda\n Vendedor.objects.create_user(username='test', email='test@example.com', password='test@123', cpf=cpf_venda)\n response = self.client.post('/v1/compra', data=self.payload_compra, format=\"json\")\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json(), {\"cpf\": [\"Não é permitido inserir uma compra para outro CPF\"]})\n\n def test_compra__cpf_inexistente(self):\n cpf_autenticado = '15350946056'\n cpf_venda = '67674926044'\n self.autenticate_client(cpf=cpf_autenticado)\n self.payload_compra['cpf'] = cpf_venda\n response = self.client.post('/v1/compra', data=self.payload_compra, format=\"json\")\n self.assertEqual(response.status_code, 400)\n self.assertEqual(response.json(), {\"cpf\": [f\"Objeto com cpf={cpf_venda} não existe.\"]})\n\n def test_compra__cpf_sanitizado(self):\n cpf_venda = '153.509.460-56'\n cpf_limpo = '15350946056'\n Vendedor.objects.create_user(username='Foo', email='foo@example.com', password='foo@bar',\n cpf=cpf_limpo)\n self.autenticate_client()\n self.payload_compra['cpf'] = cpf_venda\n response = self.client.post('/v1/compra', data=self.payload_compra, format=\"json\")\n data = response.json()\n self.assertEqual(response.status_code, 201)\n self.assertEqual(data[\"cpf\"], cpf_limpo)\n\n def test_compra_apenas_ultimos_30_dias_sucesso(self):\n self.autenticate_client()\n data = now() - timedelta(days=30)\n self.payload_compra[\"data\"] = data.isoformat()\n response = self.client.post('/v1/compra', data=self.payload_compra, format=\"json\")\n data = response.json()\n self.assertEqual(response.status_code, 201)\n\n def test_compra_apenas_ultimos_30_dias_erro(self):\n self.autenticate_client()\n data = now() - timedelta(days=31)\n self.payload_compra[\"data\"] = data.isoformat()\n response = self.client.post('/v1/compra', data=self.payload_compra, format=\"json\")\n data = response.json()\n self.assertEqual(response.status_code, 400)\n self.assertEqual(data, {\"data\": [\"Não é possível inserir uma compra de mais de 30 dias atrás\"]})\n\n def test_compra_atualiza_cashback_ultimos_30_dias(self):\n \"\"\"Apenas para ter uma versão integrada dessa mesma funcionalidade. Mas o teste do model já antende\"\"\"\n cpf = \"35770006005\"\n trinta_e_um_dias = now() - timedelta(days=31)\n trinta_dias = now() - timedelta(days=30)\n self.autenticate_client(cpf=cpf)\n vendedor = Vendedor.objects.filter(cpf=cpf).first()\n\n # Essa compra não deve impactar no somatóro. % original é de 20%\n compra_trinta_e_um_dias = Compra.objects.create(codigo=\"123457\", vendedor=vendedor, valor=Decimal(2000), data=trinta_e_um_dias)\n\n # Essa compra deve impactar no somatório. % original é de 10%\n compra_trinta_dias = Compra.objects.create(codigo=\"123458\", vendedor=vendedor, valor=Decimal(999), data=trinta_dias)\n self.assertEqual(compra_trinta_dias.percentual_cashback, 10)\n\n # Com essa compra o novo percentual deve subir para 15%\n payload = {\n \"codigo\": \"123459\",\n \"cpf\": cpf,\n \"data\": now().isoformat(),\n \"valor\": \"100\",\n }\n response = self.client.post('/v1/compra', data=payload, format=\"json\")\n data = response.json()\n self.assertEqual(response.status_code, 201)\n self.assertEqual(data[\"percentual_cashback\"], 15)\n\n # Essa compra não deve ter sido alterada\n compra_trinta_e_um_dias.refresh_from_db()\n self.assertEqual(compra_trinta_e_um_dias.percentual_cashback, 20)\n\n # Essa compra deve ter sido alterada para 15%\n compra_trinta_dias.refresh_from_db()\n self.assertEqual(compra_trinta_dias.percentual_cashback, 15)\n\n def test_compra_com_sucesso(self):\n self.autenticate_client()\n response = self.client.post('/v1/compra', data=self.payload_compra, format=\"json\")\n data = response.json()\n self.assertEqual(response.status_code, 201)\n self.assertIn(\"codigo\", data)\n self.assertIn(\"cpf\", data)\n self.assertIn(\"data\", data)\n self.assertIn(\"percentual_cashback\", data)\n self.assertIn(\"cashback\", data)\n self.assertIn(\"valor\", data)\n\n def test_listagem_compras_do_vendedor_precisa_autenticacao(self):\n cpf = '08948135015'\n response = self.client.get(f'/v1/vendedor/{cpf}/compras')\n self.assertEqual(response.status_code, 401)\n\n def test_listagem_compras_do_vendedor(self):\n cpf = '08948135015'\n cpf_outro_vendedor = \"41615628029\"\n trinta_e_um_dias = now() - timedelta(days=31)\n\n vendedor = Vendedor.objects.create(cpf=cpf, username=\"vendedor\")\n outro_vendedor = Vendedor.objects.create(cpf=cpf_outro_vendedor, username=\"outro-vendedor\")\n\n Compra.objects.create(codigo=\"345678\", vendedor=outro_vendedor, valor=Decimal(500), data=trinta_e_um_dias)\n Compra.objects.create(codigo=\"345679\", vendedor=vendedor, valor=Decimal(500), data=trinta_e_um_dias)\n Compra.objects.create(codigo=\"345670\", vendedor=vendedor, valor=Decimal(500), data=trinta_e_um_dias)\n\n self.autenticate_client(cpf=cpf)\n response = self.client.get(f'/v1/vendedor/{cpf}/compras')\n data = response.json()\n self.assertEqual(response.status_code, 200)\n\n # Verifica os atributos da paginação\n self.assertEqual(type(data), dict)\n self.assertIn(\"count\", data)\n self.assertIn(\"next\", data)\n self.assertIn(\"previous\", data)\n self.assertIn(\"results\", data)\n\n # Verificação dos itens em si\n results = data[\"results\"]\n self.assertEqual(len(results), 2)\n self.assertIn(\"codigo\", results[0])\n self.assertIn(\"valor\", results[0])\n self.assertIn(\"data\", results[0])\n self.assertIn(\"percentual_cashback\", results[0])\n self.assertIn(\"cashback\", results[0])\n self.assertIn(\"status\", results[0])\n\n def test_listagem_compras_outro_vendedor(self):\n cpf = '08948135015'\n cpf_outro_vendedor = \"41615628029\"\n\n Vendedor.objects.create(cpf=cpf, username=\"vendedor\")\n Vendedor.objects.create(cpf=cpf_outro_vendedor, username=\"outro-vendedor\")\n\n self.autenticate_client(cpf=cpf)\n response = self.client.get(f'/v1/vendedor/{cpf_outro_vendedor}/compras')\n data = response.json()\n self.assertEqual(response.status_code, 400)\n self.assertEqual(data, {\"erro\": \"Não é possível acessar a listagem de vendas de outro vendedor\"})\n\n def test_acumulado_cashback_precisa_autenticacao(self):\n cpf = '15350946056'\n response = self.client.get(f'/v1/vendedor/{cpf}/saldo')\n self.assertEqual(response.status_code, 401)\n\n def test_acumulado_cashback_outro_vendedor(self):\n cpf = '08948135015'\n cpf_outro_vendedor = \"41615628029\"\n\n Vendedor.objects.create(cpf=cpf, username=\"vendedor\")\n Vendedor.objects.create(cpf=cpf_outro_vendedor, username=\"outro-vendedor\")\n\n self.autenticate_client(cpf=cpf)\n response = self.client.get(f'/v1/vendedor/{cpf_outro_vendedor}/saldo')\n data = response.json()\n self.assertEqual(response.status_code, 400)\n self.assertEqual(data, {\"erro\": \"Não é possível acessar o saldo de outro vendedor\"})\n\n def test_acumulado_cashback_resposata_invalida_api_retorna_500(self):\n with patch.object(SaldoAPI, 'get_saldo', return_value=None) as mock_client:\n cpf = '15350946056'\n self.autenticate_client(cpf=cpf)\n response = self.client.get(f'/v1/vendedor/{cpf}/saldo')\n self.assertEqual(response.status_code, 500)\n mock_client.assert_called_once_with(cpf)\n\n def test_acumulado_cashback_integrado(self):\n cpf = '15350946056'\n self.autenticate_client(cpf=cpf)\n response = self.client.get(f'/v1/vendedor/{cpf}/saldo')\n self.assertEqual(response.status_code, 200)\n self.assertIn(\"saldo\", response.json())\n","sub_path":"src/cashback/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":24408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"382746546","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-i686/egg/collective/contentgenerator/setuphandlers.py\n# Compiled at: 2009-01-19 09:24:11\nfrom collective.contentgenerator.ContentGenerator import ContentSetup\nfrom collective.contentgenerator.UserGenerator import UserSetup\n\ndef runSetup(context, content, users):\n \"\"\" Runs the content and user generation methods \"\"\"\n if context.readDataFile('collective.contentgenerator_various.txt') is None:\n return\n portal = context.getSite()\n cs = ContentSetup()\n cs.customize(portal, context, content)\n cu = UserSetup()\n cu.customize(portal, context, users)\n return\n\n\ndef setupVarious(context):\n \"\"\" Run this content / user creation after standard generic setup\n This default setting just adds minimal token content for testing\n Default settings for test content = 1 min ~ 1 Mb \"\"\"\n content = {'sectioncount': 1, 'foldercount': 1, 'itemcount': 2, 'imagecount': 1, 'bigimagecount': 0, 'multiply': 1, 'profile': 'default'}\n users = {'groups': 2, 'memberships': 2, 'local': True, 'users': 10}\n runSetup(context, content, users)\n\n\ndef setupIntranet(context):\n \"\"\" Run this content / user creation after standard generic setup handling\n Default settings for intranet ~ 10 mins ~ 200 Mb \"\"\"\n content = {'sectioncount': 3, 'foldercount': 5, 'itemcount': 10, 'imagecount': 5, 'bigimagecount': 5, 'multiply': 2, 'profile': 'intranet'}\n users = {'groups': 10, 'memberships': 10, 'local': False, 'users': 100}\n runSetup(context, content, users)\n\n\ndef setupPublic(context):\n \"\"\" Run this content / user creation after standard generic setup handling\n Default settings for public site ~ 20 mins ~ 200 Mb \"\"\"\n content = {'sectioncount': 5, 'foldercount': 10, 'itemcount': 20, 'imagecount': 5, 'bigimagecount': 1, 'multiply': 2, 'profile': 'public'}\n users = {'groups': 500, 'memberships': 20, 'local': True, 'users': 2000}\n runSetup(context, content, users)","sub_path":"pycfiles/collective.contentgovernance-1.1/setuphandlers.py","file_name":"setuphandlers.py","file_ext":"py","file_size_in_byte":2129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"296872384","text":"from keras.preprocessing import image\nfrom keras.callbacks import ReduceLROnPlateau, BaseLogger, ProgbarLogger, RemoteMonitor\nfrom keras.applications.vgg19 import preprocess_input\nimport tensorflow as tf\nfrom PIL import Image\nimport numpy as np\nimport pickle\nimport sys\nimport cv2\nimport os\n\nsys.path.append('..')\nfrom utils.config import Config\nfrom models.nn_model import NNModel\n\n\ndef build_dataset_generator():\n\n train_datagen = image.ImageDataGenerator(\n preprocessing_function=preprocess_input,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n fill_mode='nearest',\n )\n\n val_datagen = image.ImageDataGenerator(\n preprocessing_function=preprocess_input,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.2,\n zoom_range=0.2,\n fill_mode='nearest',\n )\n\n train_generator = train_datagen.flow_from_directory(\n f'{Config.DATASET_DIR}/{Config.ENTITY_NAME}/train',\n target_size=Config.TARGET_SIZE,\n batch_size=Config.BATCH_SIZE\n )\n\n validation_generator = val_datagen.flow_from_directory(\n f'{Config.DATASET_DIR}/{Config.ENTITY_NAME}/val',\n target_size=Config.TARGET_SIZE,\n batch_size=Config.BATCH_SIZE\n )\n\n return train_generator, validation_generator\n\n\ndef train():\n\n import keras.backend as K\n K.clear_session()\n tf.reset_default_graph()\n\n model = NNModel().build()\n reduce_lr_callback = ReduceLROnPlateau(monitor='val_loss',\n factor=0.1,\n patience=3,\n min_lr=0)\n\n train_generator, validatation_generator = build_dataset_generator()\n\n model.compile(optimizer=Config.OPTIMIZER,\n loss=Config.LOSS, metrics=Config.METRICS)\n\n history = model.fit_generator(train_generator,\n steps_per_epoch=train_generator.n//train_generator.batch_size,\n epochs=Config.EPOCHS,\n validation_data=validatation_generator,\n validation_steps=validatation_generator.n//validatation_generator.batch_size,\n class_weight='auto',\n callbacks=[reduce_lr_callback])\n\n Config.MODEL = model\n Config.DEFAULT_GRAPH = tf.get_default_graph()\n\n Config.MODEL_NAME = \"nn_model\"\n Config.LABELS_TO_CLASSES = train_generator.classes\n\n if not os.path.isdir(f'data/{Config.ENTITY_NAME}'):\n print(os.path.isdir(f'data/{Config.ENTITY_NAME}'))\n os.makedirs(f'data/{Config.ENTITY_NAME}')\n\n model.save(\n f'data/{Config.ENTITY_NAME}/{Config.MODEL_NAME}_{Config.ITERATION}.model')\n\n pickle.dump(train_generator.classes, open(\n f'data/{Config.ENTITY_NAME}/{Config.MODEL_NAME}_{Config.ITERATION}_classes.p', 'wb'))\n\n return history, \"Model Trained Successfully!\"\n","sub_path":"utils/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"579881975","text":"from django.urls import path\nfrom .views import (\n switch_type_view,\n switch_branch_view,\n)\n\napp_name=\"switches\"\nurlpatterns = [\n path('', switch_type_view, name=\"switch_type\"),\n path('branch/', switch_branch_view, name=\"switch_branch\"),\n]\n","sub_path":"switch1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"160264396","text":"#!/usr/bin/env python\n\nimport rospy\nfrom std_msgs.msg import String, Bool\nimport os, sys\nfrom trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint\nfrom sensor_msgs.msg import JointState\nimport time\nfrom osrf_gear.srv import VacuumGripperControl\nimport json \n\nclass RobotArmGripper:\n\n def __init__(self,flag):\n self.flag = flag\n # self.status_json = {\n # 'Testcase_0': False,\n # 'Testcase_1': False,\n # 'Testcase_2': False,\n # 'Testcase_3': False,\n # 'Testcase_4': False\n # }\n\n def grip(self,flag):\n try:\n gripper_control = rospy.ServiceProxy('/ariac/arm1/gripper/control', VacuumGripperControl)\n response = gripper_control(flag)\n if flag == False:\n pub = rospy.Publisher('/ariac/arm1/backToInitialCommand',String, queue_size=10)\n pub.publish('True')\n self.flag = True\n except rospy.ServiceException as exc:\n self.grip(flag)\n\n def armLocation(self,data):\n jt0 = data.position[0]\n jt1 = data.position[1]\n jt2 = data.position[2]\n jt3 = data.position[3]\n jt4 = data.position[4]\n jt5 = data.position[5]\n jt6 = data.position[6]\n\n # -0.35, 3.14, -0.5, 2.3, 3.05, -1.59, 0.126\n # 1.18, 1.507, 0.38, -0.38, 1.55, 1.75, 0.127\n approx_state_1 = (-0.35 - jt1)**2 + (3.14 - jt3)**2 + (-0.5 - jt2)**2 + (2.3-jt0)**2 + (3.05-jt4)**2 + (-1.59-jt5)**2 + (0.126-jt6)**2\n approx_state_2 = (1.18 - jt1)**2 + (1.507 - jt3)**2 + (0.38 - jt2)**2 + (-0.38 -jt0)**2 + (1.55-jt4)**2 + (1.75-jt5)**2 + (0.127-jt6)**2\n # print (approx_state_1,'-',approx_state_2)\n if approx_state_1 <= 0.005:\n self.grip(True)\n # self.status_json['Testcase_2'] = True\n # pub_status_test_case_0 = rospy.Publisher('/ariac/arm1/testcase/status',String,queue_size=10)\n # pub_status_test_case_0.publish(json.dumps(self.status_json))\n if approx_state_2 <= 0.005:\n self.grip(False) \n # self.status_json['Testcase_4'] = True\n # pub_status_test_case_0 = rospy.Publisher('/ariac/arm1/testcase/status',String,queue_size=10)\n # pub_status_test_case_0.publish(json.dumps(self.status_json))\n\n def arm_location_call(self): \n while not rospy.is_shutdown() and self.flag == False:\n sub = rospy.Subscriber('/ariac/arm1/joint_states', JointState, self.armLocation)\n rospy.sleep(1)\n\nif __name__ == '__main__':\n try:\n rospy.init_node(\"arm_state_1\", log_level=rospy.DEBUG)\n rate = rospy.Rate(1)\n except:\n pass\n initRoboArm = RobotArmGripper(False)\n initRoboArm.arm_location_call()","sub_path":"gear/src/gear_control/scripts/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"636310075","text":"import hashlib\nimport os\nimport threading\n\n# Moved in Python 2 -> 3, used only here.\n# Not adding to dvc.utils.compat to not load http.server for non-test runs.\ntry:\n from http.server import HTTPServer\nexcept ImportError:\n from BaseHTTPServer import HTTPServer\n\nfrom RangeHTTPServer import RangeRequestHandler\n\n\nclass TestRequestHandler(RangeRequestHandler):\n checksum_header = None\n\n def end_headers(self):\n # RangeRequestHandler only sends Accept-Ranges header if Range header\n # is present, see https://github.com/danvk/RangeHTTPServer/issues/23\n if not self.headers.get(\"Range\"):\n self.send_header(\"Accept-Ranges\", \"bytes\")\n\n # Add a checksum header\n if self.checksum_header:\n file = self.translate_path(self.path)\n\n if not os.path.isdir(file) and os.path.exists(file):\n with open(file, \"r\") as fd:\n encoded_text = fd.read().encode(\"utf8\")\n checksum = hashlib.md5(encoded_text).hexdigest()\n self.send_header(self.checksum_header, checksum)\n\n RangeRequestHandler.end_headers(self)\n\n\nclass ETagHandler(TestRequestHandler):\n checksum_header = \"ETag\"\n\n\nclass ContentMD5Handler(TestRequestHandler):\n checksum_header = \"Content-MD5\"\n\n\nclass StaticFileServer:\n _lock = threading.Lock()\n\n def __init__(self, handler=\"etag\"):\n self._lock.acquire()\n handler_class = ETagHandler if handler == \"etag\" else ContentMD5Handler\n self._httpd = HTTPServer((\"localhost\", 0), handler_class)\n self._thread = None\n\n def __enter__(self):\n self._thread = threading.Thread(target=self._httpd.serve_forever)\n self._thread.daemon = True\n self._thread.start()\n return self._httpd\n\n def __exit__(self, *args):\n self._httpd.socket.close()\n self._httpd.shutdown()\n self._httpd.server_close()\n self._lock.release()\n","sub_path":"tests/utils/httpd.py","file_name":"httpd.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"178281546","text":"import cv2\nimport numpy as np\n\n\ndef kernel_generator(size):\n kernel = np.zeros((size, size), dtype=np.int8)\n for i in range(size):\n for j in range(size):\n if i < j:\n kernel[i][j] = -1\n elif i > j:\n kernel[i][j] = 1\n return kernel\n\n\ndef emboss(img, val, s):\n height, width = img.shape[:2]\n y = np.ones((height, width), np.uint8) * 128\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n kernel = kernel_generator(val) # generating kernel for bottom left kernel\n kernel = np.rot90(kernel, s) # switching kernel according to direction\n res = cv2.add(cv2.filter2D(gray, -1, kernel), y)\n return res\n","sub_path":"emboss.py","file_name":"emboss.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"506462520","text":"import random\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as mpatches\r\nimport math\r\nimport time\r\nstart_time=time.time()\r\n\r\nclass Network:\r\n\r\n def __init__(self, sizes):\r\n self.num_layers = len(sizes)\r\n self.sizes = sizes\r\n self.biases = [np.random.randn(y, 1) for y in sizes[1:]]\r\n self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])]\r\n\r\n def feedforward(self, a):\r\n for b, w in zip(self.biases, self.weights):\r\n a = sigmoid(np.dot(w, a)+b)\r\n return a\r\n\r\n def SGD(self, training_data, mini_batch_size, eta):\r\n n = len(training_data)\r\n self.progress_epochs=[]\r\n epoch=0\r\n predicted_y=[float(self.feedforward(i)*maximum) for i in x]\r\n while percent_accuracy(predicted_y, actual_y) < 93:\r\n cost_epoch=self.MSE(training_data_)\r\n self.progress_epochs.append(cost_epoch)\r\n if epoch % 100 == 0:\r\n print(\"Cost For Epoch \", epoch, \": \", cost_epoch)\r\n print(\"Average Accuracy \", percent_accuracy(predicted_y, actual_y))\r\n random.shuffle(training_data)\r\n mini_batches = [\r\n training_data[k:k+mini_batch_size]\r\n for k in range(0, n, mini_batch_size)]\r\n for mini_batch in mini_batches:\r\n self.update_mini_batch(mini_batch, eta)\r\n epoch += 1\r\n predicted_y=[float(net.feedforward(i)*maximum) for i in x]\r\n def update_mini_batch(self, mini_batch, eta):\r\n nabla_b = [np.zeros(b.shape) for b in self.biases]\r\n nabla_w = [np.zeros(w.shape) for w in self.weights]\r\n for x, y in mini_batch:\r\n delta_nabla_b, delta_nabla_w = self.backprop(x, y)\r\n nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]\r\n nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]\r\n self.weights = [w-(eta/len(mini_batch))*nw\r\n for w, nw in zip(self.weights, nabla_w)]\r\n self.biases = [b-(eta/len(mini_batch))*nb\r\n for b, nb in zip(self.biases, nabla_b)]\r\n\r\n def backprop(self, x, y):\r\n nabla_b = [np.zeros(b.shape) for b in self.biases]\r\n nabla_w = [np.zeros(w.shape) for w in self.weights]\r\n # feedforward\r\n activation = x\r\n activations = [x] # list to store all the activations, layer by layer\r\n zs = [] # list to store all the z vectors, layer by layer\r\n for b, w in zip(self.biases, self.weights):\r\n z = np.dot(w, activation)+b\r\n zs.append(z)\r\n activation = sigmoid(z)\r\n activations.append(activation)\r\n # backward pass\r\n delta = self.cost_derivative(activations[-1], y) * \\\r\n sigmoid_prime(zs[-1])\r\n nabla_b[-1] = delta\r\n nabla_w[-1] = np.dot(delta, activations[-2].transpose())\r\n # Note that the variable l in the loop below is used a little\r\n # differently to the notation in Chapter 2 of the book. Here,\r\n # l = 1 means the last layer of neurons, l = 2 is the\r\n # second-last layer, and so on. It's a renumbering of the\r\n # scheme in the book, used here to take advantage of the fact\r\n # that Python can use negative indices in lists.\r\n for l in range(2, self.num_layers):\r\n z = zs[-l]\r\n sp = sigmoid_prime(z)\r\n delta = np.dot(self.weights[-l+1].transpose(), delta) * sp\r\n nabla_b[-l] = delta\r\n nabla_w[-l] = np.dot(delta, activations[-l-1])\r\n return (nabla_b, nabla_w)\r\n\r\n def cost_derivative(self, output_activations, y):\r\n return (output_activations-y)\r\n def MSE(self, data):\r\n cost = [(i[1]-float(self.feedforward(i[0])*maximum))**2 for i in data]\r\n return sum(cost)/len(cost)\r\ndef sigmoid(z):\r\n return 1.0/(1.0+np.exp(-z))\r\n\r\ndef sigmoid_prime(z):\r\n return sigmoid(z)*(1-sigmoid(z))\r\n\r\ndef g(x):\r\n return (x**2+4)/x\r\n\r\ndef f(x):\r\n return (g(x) + np.random.normal(g(x), abs(g(x)/10)))/2\r\n\r\ndef percent_accuracy(predicted_y_data, actual_y_data):\r\n percent_accuracy_all=[]\r\n for i, j in zip(predicted_y_data, actual_y_data):\r\n if i 100:\r\n accuracy=accuracy-100\r\n percent_accuracy_all.append(abs(accuracy))\r\n average_accuracy=100-sum(percent_accuracy_all)/len(percent_accuracy_all)\r\n return average_accuracy\r\n\r\ndef MSE_poly(test_data):\r\n cost=[(i[1]-poly(i[0]))**2 for i in test_data]\r\n return sum(cost)/len(cost)\r\nlearning_rate = 6.5\r\ntraining_bounds = [1.6, 6.3]\r\nnum_training_samples = 20\r\npoly_degree = 10\r\n\r\ntraining_data = [(i, f(i)) for i in np.linspace(training_bounds[0], training_bounds[1], num_training_samples)]\r\ntraining_data_ = training_data\r\ntraining_data_x = [i[0] for i in training_data]\r\ntraining_data_y = [i[1] for i in training_data]\r\n\r\nmaximum=max([i[1] for i in training_data])\r\ntraining_data_scaled = [(i[0], i[1]/maximum) for i in training_data]\r\n\r\nx=np.linspace(training_bounds[0], training_bounds[1], 100)\r\ngeneral_trend_y=[g(i) for i in x]\r\nactual_y=f(x)\r\nnet=Network([1, 12, 1])\r\nnet.SGD(training_data_scaled, 1, learning_rate)\r\npredicted_y=[float(net.feedforward(i)*maximum) for i in x]\r\n\r\n\r\n\r\ngeneral_trend_tuples=[(i, g(i)) for i in np.linspace(training_bounds[0], training_bounds[1], num_training_samples)]\r\n\r\nend_time=time.time()\r\n\r\npoly_start=time.time()\r\npoly = np.poly1d(np.polyfit(training_data_x, training_data_y, poly_degree))\r\npoly_predicted_y=[poly(i) for i in x]\r\nplt.plot(x, poly_predicted_y)\r\npoly_end=time.time()\r\n\r\nplt.plot(x, predicted_y)\r\nplt.plot(x, actual_y, label='Function with Noise')\r\nplt.plot(x, general_trend_y, label='Pure Function')\r\nprint(\"ARTIFICIAL NEURAL NETWORK MODEL:\")\r\nprint(\"Mean-Squared-Error Cost: \", net.MSE(general_trend_tuples))\r\nprint(\"Average Percentage Accuracy: \", percent_accuracy(predicted_y, actual_y), \"%\")\r\nprint(\" --- %s Seconds Elapsed ---\" % (end_time - start_time))\r\nprint(\"POLYNOMIAL REGRESSION MODEL:\")\r\nprint(\"Mean-SquareError Cost: \", MSE_poly(general_trend_tuples))\r\nprint(\"Average Percentage Accuracy: \", percent_accuracy(poly_predicted_y, actual_y), \"%\")\r\nprint(\" --- %s Seconds Elapsed ---\" % (poly_end - poly_start))\r\n\r\nprint(\"\")\r\nprint()\r\nplt.show()\r\nepochs=[i for i in range(1, len(net.progress_epochs)+1)]\r\nprint(net.progress_epochs)\r\nplt.plot(epochs, net.progress_epochs)\r\nplt.show()\r\ninput()\r\n","sub_path":"Unorganized Files/3 Layer Prototypes/Programs/network v5 - Copy.py","file_name":"network v5 - Copy.py","file_ext":"py","file_size_in_byte":6554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"450577762","text":"\n\n#calss header\nclass _WASH():\n\tdef __init__(self,): \n\t\tself.name = \"WASH\"\n\t\tself.definitions = [u'to clean something using water: ', u'to clean yourself, or a part of yourself, with water and usually soap: ', u'If a particular material or piece of clothing washes well, it is not damaged or spoiled by repeated washing.', u'If water washes somewhere, it flows there, usually repeatedly: ', u'(of the sea) to carry something or someone to or away from a place: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_wash.py","file_name":"_wash.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175681839","text":"\n\n#calss header\nclass _WANT():\n\tdef __init__(self,): \n\t\tself.name = \"WANT\"\n\t\tself.definitions = [u'a lack of something: ', u'needing: ', u'needs: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_want.py","file_name":"_want.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"231737120","text":"\"\"\"\nYou can see the actual code file [here](text_generator.py).\n\"\"\"\n\nimport string\nimport random\nfrom collections import defaultdict\n\n\ndef remove_punction(text):\n \"\"\"\n Removes the punctuation from a given string\n \"\"\"\n return text.translate(str.maketrans(\"\", \"\", string.punctuation))\n\n\ndef get_trigrams(data):\n \"\"\"\n Generates the trigrams of an array of elements. For example, if `data = [a, b, c, d]` then the\n output will be `[[a,b,c], [b,c,d]]`.\n \"\"\"\n for i in range(len(data) - 2):\n yield data[i:i + 3]\n\n\ndef get_ngrams(degree, data):\n \"\"\"\n Generates the n-grams of an array of elements. For example, if `data = [a, b, c, d]` and\n `degree = 2` then the output will be `[[a,b], [b,c], [c,d]]`. This is just a generic\n version of the `get_trigrams` function, here for reference.\n \"\"\"\n for i in range(len(data) - degree + 1):\n yield data[i:i + degree]\n\n\ndef weighted_choice(states):\n \"\"\"\n Given a dictionary of keys and weights, choose a random key based on its weight.\n \"\"\"\n n = random.uniform(0, sum(states.values()))\n for key, val in states.items():\n if n < val:\n return key\n n -= val\n\n # Something went wrong, don't make a choice.\n return None\n\n\nif __name__ == '__main__':\n # Load some data from a text file named `data.txt`\n # Open the file containing the data, and read it into a variable.\n # The file might look something like:\n \"\"\"\n `\n WORK IN PRAGUE\\n\n Low comedy's got the new shine.\\n\n Defiant luster.\\n\n The three film score.\\n\n No claims between updates and rehearsals.\\n\n Always admired.\\n\n `\n \"\"\"\n file = open(\"data.txt\")\n data = file.read()\n\n # Clean up the data by removing punctuation and replacing newlines (`\\n`) with spaces.\n # Cleaning is *typically* the hardest part, since you'll encounter a lot of weird stuff\n # out in the wild.\n data = remove_punction(data).replace('\\n', ' ')\n parsed_data = data.split(' ')\n\n # Create the Markov Chain. I use `defaultdict` as a simple (error-free) counter. This just\n # means that every key in the dictionary has a default value. If a key isn't in the dictionary\n # then it will automatically have a value generated. The `lambda: defaultdict(int)` means the\n # default value will be *another* dictionary which sets the default values to zero.\n #\n # So if you wrote `markov['test']` you would get a `defaultdict`. Going one step further,\n # you could write `markov['a']['b']` which would result in 0. This let's you write a counter\n # in the form `markov['a']['b'] += 1` without getting a `KeyError`.\n markov = defaultdict(lambda: defaultdict(int))\n\n # Now split the input data into trigrams for parsing.\n for (w1, w2, w3) in get_trigrams(parsed_data):\n # Use lowercase to normalize the data.\n w1 = w1.lower()\n w2 = w2.lower()\n w3 = w3.lower()\n\n # Update the tally for this combination.\n markov[(w1, w2)][w3] += 1\n\n # You can use the following code for a preview of the Markov Chain probabilites:\n # `for state in markov: print('%r => %r' % (state, markov[state]))`\n\n # Use random to pick a random initial state (or set it yourself).\n start_state = random.choice(list(markov.keys()))\n # You can preview it by writing ```print(\"Initial State: %s\" % repr(start_state))```\n\n # Now start 'walking' along the Markov Chain to generate stuff. Unfortunately, the hard part\n # is knowing when to stop. Here I say I want sentences no longer than 15 words, and if there's\n # a dead-end, stop immediately. Naturally, there's much better ways to do this.\n s1, s2 = start_state\n max_length = 15\n result = [s1, s2]\n for i in range(max_length):\n next_state = weighted_choice(markov[(s1, s2)])\n if next_state is None: break\n result.append(next_state)\n s1 = s2\n s2 = next_state\n\n # Now we convert the data to regular string.\n generated_text = ' '.join(result) + '.'\n print(\"Generated Text: %s\" % generated_text)\n\n # Enjoy! Sometimes Markov Chains are great, sometimes they are finicky, and you probably\n # need a lot of data to get coherent/good results from them. They're definitely a good\n # starting place for content generation, though.\n","sub_path":"code/text_generator.py","file_name":"text_generator.py","file_ext":"py","file_size_in_byte":4312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610126213","text":"def load_D(filename):\n '''\n 读取数据库\n :param filename:文件名\n :return:\n D:数据库\n '''\n with open(filename, \"r\") as file:\n D = []\n for line in file:\n transaction = set(line.rstrip(' \\r\\n').split(\" \"))\n D.append(transaction)\n return D\n\ndef save_L(L):\n with open(\"support.txt\", \"w\") as file:\n count = 1\n for item_set in L:\n for item_set1 in item_set:\n item = list(map(int, item_set1))\n print(count, \":\", item)\n file.write(str(item)+'\\n')\n count += 1\n\ndef create_C1(D):\n '''\n 创建第1轮迭代候选集\n :param D: 数据库\n :return:\n C1:第1轮迭代候选集\n '''\n C1 = set()\n for transaction in D:\n for item in transaction:\n item_set = frozenset([item])\n C1.add(item_set)\n return C1\n\ndef is_apriori(Ci_item, Lisub1):\n '''\n 根据先验规则,判断是否是频繁项集\n :param Ci_item:第i轮迭代候选集候选项\n :param Lisub1:第i-1轮迭代频繁项集\n :return:\n 判断结果\n '''\n for item in Ci_item:\n Ci_sub = Ci_item - frozenset(item)\n if Ci_sub not in Lisub1:\n return False\n return True\n\ndef create_Ci(Lisub1, k):\n '''\n 创建第i轮迭代候选集\n :param Lisub1:第i-1轮迭代频繁项集\n :param k:第i轮频繁项集项数\n :return:\n Ci:第i轮迭代候选集\n '''\n Ci = set()\n Lisub1_len = len(Lisub1)\n Lisub1_list = list(Lisub1)\n for i in range(Lisub1_len):\n for j in range(1, Lisub1_len):\n list1 = list(Lisub1_list[i])\n list2 = list(Lisub1_list[j])\n list1.sort()\n list2.sort()\n if list1[0:k-2] == list2[0:k-2] and list1 != list2:\n Ci_item = Lisub1_list[i] | Lisub1_list[j]\n if is_apriori(Ci_item, Lisub1):\n Ci.add(Ci_item)\n return Ci\n\n\ndef generate_Li_by_Ci(D, Ci, min_sup, support_dict):\n '''\n 由第i轮迭代候选集生成该轮频繁项集\n :param D:数据库\n :param Ci:第i轮迭代候选集\n :param min_sup:最小支持度\n :param support_dict:频繁项计数字典\n :return:\n Li:第i轮迭代生成的频繁项集\n '''\n Li = set()\n item_dict = {} # 候选项计数字典\n min_sup_num = float(len(D)) * min_sup # 最小支持度计数\n # 统计各候选项的支持度计数\n for transaction in D:\n for item in Ci:\n if item.issubset(transaction): # 若事务中含此项,为此项的支持度计数\n if item not in item_dict:\n item_dict[item] = 1\n else:\n item_dict[item] += 1\n # 根据支持度计数生成频繁项集\n for item in item_dict:\n if item_dict[item] >= min_sup_num:\n Li.add(item)\n support_dict[item] = item_dict[item]\n return Li\n\ndef generate_L(D, k, min_sup):\n '''\n 生成所有的频繁项集\n :param D:数据库\n :param k:频繁项最大项数\n :min_sup:最小支持度\n :return:\n Lmax:所有最大长度的频繁项集\n '''\n support_dict = {} # 频繁项全集字典\n C1 = create_C1(D)\n L1 = generate_Li_by_Ci(D, C1, min_sup, support_dict)\n Lisub1 = L1.copy()\n Lmax = Lisub1\n for i in range(2, k+1):\n Ci = create_Ci(Lisub1, i)\n Li = generate_Li_by_Ci(D, Ci, min_sup, support_dict)\n if len(Li) == 0: # 若频繁项集为空集,结束迭代\n break\n Lisub1 = Li.copy()\n Lmax = Lisub1\n return Lmax\n\nif __name__ == \"__main__\":\n filename = \"apriori_data.txt\"\n support_dict = {}\n\n D = load_D(filename)\n\n Lmax = generate_L(D, 100, 0.05) # min_support = 100 / 2000 = 0.05\n print(\"最大频繁项集:\")\n for item_set in Lmax:\n item = sorted(list(map(int, item_set)))\n print(item)","sub_path":"apriori/apriori.py","file_name":"apriori.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"9232158","text":"from pathlib import Path\nimport sys\nfilename = 'model_limit'\npath = str(Path(__file__))\nfinal_path = path[:path.find(filename) + len(filename)]\nsys.path.append(final_path)\nfrom model.creat_model.data_process.data_normalize import *\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom model.creat_model.doc_files.files_path import load_ordata\nfrom model.creat_model.data_process.data_encode import data_transform\n# from sklearn.pipeline import Pipeline\n# from sklearn.preprocessing import StandardScaler\n\n\ndef load_fit_data(smote=True):\n or_data=load_ordata()\n or_data=or_data[or_data['classification'].isin(['good','bad'])]\n or_data['classification']=or_data['classification'].replace({'good':1,'bad':0})\n train,test=train_test_split(or_data,test_size=0.25)\n train,test = data_transform(train,test=test)\n X,Y=split_data(train,label='classification')\n x_test,y_test=split_data(test,label='classification')\n X,x_test=pro_data(X,x_test=x_test)\n if smote:\n X,Y=smote_sample(X,Y)\n return X,Y,x_test,y_test\n\nif __name__ == '__main__':\n load_fit_data()","sub_path":"risk/model_limit/model/creat_model/data_process/get_fit_data.py","file_name":"get_fit_data.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529003810","text":"import random\n\n\ndef selection_elite(fitness, population, **kargs):\n scored_pop = sorted(population, key=fitness, reverse=True)\n selection = int((.1 * len(population)))\n \n res = scored_pop[:selection]\n random.shuffle(res)\n return res\n\ndef selection_best_half(fitness, population, **kargs):\n scored_pop = sorted(population, key=fitness, reverse=True)\n selection = int((.5 * len(population)))\n\n res = scored_pop[:selection]\n random.shuffle(res)\n return res\n\n\ndef selection_random_kth(fitness, population, **kargs):\n scored_pop = sorted(population, key=fitness, reverse=True)\n selection = int((random.random() * len(population))) + 2\n\n res = scored_pop[:selection]\n random.shuffle(res)\n return res\n\n\ndef selection_random_choice(fitness, population, **kargs):\n random_candidates = []\n select_number = int((random.random() * len(population))) + 2\n for _ in range(select_number):\n random_candidates.append(random.choice(population))\n return random_candidates\n\n\nif __name__ == \"__main__\":\n fitness = lambda x : random.randint(0, 50)\n pop = []\n new_pop = []\n for _ in range(100):\n child = [random.randint(0, 50) for _ in range(10)]\n pop.append(child)\n print(\"Testing pop\")\n for i in range(10):\n print(i + 1, pop[i])\n\n print(\"\\nTesting elite selection\")\n new_pop = selection_elite(fitness, pop)\n for i in range(len(new_pop)):\n print(i + 1, new_pop[i])\n\n print(\"\\nTesting half selection\")\n new_pop = selection_best_half(fitness, pop)\n for i in range(len(new_pop)):\n print(i + 1, new_pop[i])\n\n print(\"\\nTesting random kth selection\")\n new_pop = selection_random_kth(fitness, pop)\n for i in range(len(new_pop)):\n print(i + 1, new_pop[i])\n\n print(\"\\nTesting random choice selection\")\n new_pop = selection_random_choice(fitness, pop)\n for i in range(len(new_pop)):\n print(i + 1, new_pop[i])\n","sub_path":"selection.py","file_name":"selection.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"226537575","text":"# -*- coding: utf-8 -*-\n### required - do no delete\nimport json\nimport math \n\ndef user(): return dict(form=auth())\ndef download(): return response.download(request,db)\ndef call(): return service()\n### end requires\ndef index():\t\n\ttabla='cf_persona'\n\trow=db(db[tabla].id > 0).select()\n\texito=request.vars.exito\t\n\tprueba=\"\"\"\n\t\n \n \n \t\n \n \n \n \n \n \n \n \n \t\n \n \n \n \n \n \n \n \n \"\"\"\n #IMG(_src=URL('uploads',row.ruta_foto))\n\tlista=[\"\"\\\n\t\t \"\"\\\n\t\t \"\"\\\n\t\t \"\"\\\n\t\t \"\" % URL('default', 'download',args=row.ruta_foto)\\\n\t\t\tfor row in row] \t\n\t\n\tprueba+=\"\".join(lista)\n\tprueba+=\"
IdCedulaNombresApellidosFoto
IdCedulaNombresApellidosFoto
\"+str(row.id)+\"\"+row.cedula+\"\"+row.nombres+\"\"+row.apellidos+\"
\"\n\n \t\n\tif len(prueba)>0:\n\t\tmytabla=XML(prueba)\n\telse:\t\t\n\t\tmytabla=T(\"No existen registros\")\n\n\treturn dict(mytabla=mytabla,exito=exito)\n\ndef handle():\n\ttabla='cf_persona'\t\n\texito=request.vars.exito\t\n\tif len(request.args) > 0:\n\t\tid = request.args[0]\n\t\trow=db(db[tabla].id == id).select().first()\n\t\tregistro=row.id\n\telse:\n\t\tregistro = 0\n\tform = SQLFORM(db[tabla], registro, deletable=True, submit_button='Enviar' , delete_label='Click para borrar:', next=URL(c='persona', f='handle'), \\\n\t\t\tmessage=T(\"Operacion Exitosa !\"), upload=URL('download'))\t\n\tif form.accepts(request.vars, session):\t\t\t\n\t\t\tredirect(URL('persona','index',vars=dict(exito=1) ) ) \n\telif form.errors:\t\t\t\n\t\t\texito=0\n\t\t\t#redirect(URL('persona','index',vars=dict(exito=0) ) ) \n\n\treturn dict(myform=form,exito=exito)\t\n\ndef eliminar():\n\ttabla='cf_persona'\t\n\tif len(request.args) > 0:\n\t\tid = request.args[0]\n\t\trow=db(db[tabla].id == id).delete()\t\t\n\t\tif row:\t\t\t\t\t\n\t\t\tredirect(URL('persona','index',vars=dict(exito=1) ) ) \n\t\telif row==None:\t\t\t\n\t\t\tredirect(URL('persona','index',vars=dict(exito=2) ) ) \n\treturn\ndef quick_add():\n\trif=request.vars.rif\n\tnom=request.vars.nom\n\tjuri=request.vars.juri\n\tcl=Cliente()\n\trow=cl.quick_insert(rif,nom,juri)\n\treturn row\n\ndef error():\n return dict()\n\ndef imprimir():\n# Let's import the wrapper\n\timport os\n\timport pdf\n\tfrom pdf.theme import colors, DefaultTheme\n\n\t# and define a constant\n\tTABLE_WIDTH = 560 # this you cannot do in rLab which is why I wrote the helper initially\n\n # then let's extend the Default theme. I need more space so I redefine the margins\n # also I don't want tables, etc to break across pages (allowSplitting = False)\n # see http://www.reportlab.com/docs/reportlab-userguide.pdf\n\tclass MyTheme(DefaultTheme):\n\t\tdoc = {\n 'leftMargin': 25,\n 'rightMargin': 25,\n 'topMargin': 20,\n 'bottomMargin': 25,\n 'allowSplitting': False\n }\n \n # let's create the doc and specify title and author\n\tdoc = pdf.Pdf('Personal actual', 'wuelfhis asuaje')\n\n # now we apply our theme\n\tdoc.set_theme(MyTheme)\n\n # time to add the logo at the top right\n\t#logo_path = os.path.join(request.folder,'static/images','facebook.png') \n\t#doc.add_image(logo_path, 67, 67, pdf.LEFT)\n\tlogo=pdf.Image(os.path.join(request.folder,'static/images','facebook.png') )\n\taddress = pdf.Paragraph(\" We are please%s \" % \"Hola\",MyTheme.paragraph)\n\tLIST_STYLE = [(\n\t\t\t'LINEABOVE', (0,0), (-1,0), 2, colors.grey),\n\t\t\t('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),\n\t\t\t('LINEBELOW', (0,0), (-1,-1), 2, colors.grey),\n\t\t\t('ALIGN', (0,0), (0,0),'LEFT'),\t\t\t\n\t\t\t\n\t\t\t]\n\t\t\t\n\t\n\tdoc.add(pdf.Table([[logo,address,\"\",\"\",\"\",\"\"]],style=LIST_STYLE ))\n\n # give me some space\n\tdoc.add_spacer()\n \n # this header defaults to H1\n\tdoc.add_header('Personal actual')\n\n # here's how to add a paragraph\n\t#doc.add_paragraph(\"We are pleased to confirm your reservation with ...\")\n\tdoc.add_spacer()\t\n\n\t# let's move on to the divers table\n\n\tdiver_table = [['Id','Cedula', 'Nombres', 'Apellidos', 'Sexo' ,'Tlf. Hab', 'Tlf. Cel.','Email']] # this is the header row \n\n\tfor row in db(db.cf_persona.id>0).select() : \n\t\tfoto=pdf.Image(os.path.join(request.folder,'uploads',row.ruta_foto) )\n\t\tfoto.drawHeight = 10\n\t\tfoto.drawWidth = 10\n\t\tdiver_table.append([row.id, row.cedula, row.nombres, row.apellidos, row.sexo,row.tlf_hab, row.tlf_cel, row.email ]) # these are the other rows\n\n\tdoc.add_table(diver_table, TABLE_WIDTH)\n\t\n\tresponse.headers['Content-Type']='application/pdf'\n\t\n\treturn doc.render()","sub_path":"controllers/cliente.py","file_name":"cliente.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"46216838","text":"# Copyright (c) 2015-2016 Cisco Systems, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\nimport os\n\nimport click\n\nfrom molecule import util\nfrom molecule.command import base\n\n\nclass Init(base.Base):\n def main(self):\n \"\"\"\n Overriden to prevent the initialization of a molecule object, since\n :class:`.Config` cannot parse a non-existent `molecule.yml`.\n\n :returns: None\n \"\"\"\n pass\n\n def execute(self, exit=True):\n \"\"\"\n Execute the actions necessary to perform a `molecule init` and exit.\n\n :param exit: (Unused) Provided to complete method signature.\n :return: None\n \"\"\"\n role = self.command_args.get('role')\n role_path = os.getcwd()\n driver = self._get_driver()\n verifier = self._get_verifier()\n if not role:\n role = os.getcwd().split(os.sep)[-1]\n role_path = os.path.abspath(os.path.join(os.getcwd(), os.pardir))\n self._init_existing_role(role, role_path, driver, verifier)\n else:\n if os.path.isdir(role):\n msg = ('The directory {} exists. '\n 'Cannot create new role.').format(role)\n util.print_error(msg)\n util.sysexit()\n self._init_new_role(role, role_path, driver, verifier)\n\n path = os.path.join(role_path, role)\n msg = 'Successfully initialized new role in {}.'.format(path)\n util.print_success(msg)\n util.sysexit(0)\n\n def _init_existing_role(self, role, role_path, driver, verifier):\n extra_context = self._get_cookiecutter_context(role, driver, verifier)\n\n util.print_info('Initializing molecule in current directory...')\n for template in [\n 'playbook', 'driver/{}'.format(driver),\n 'verifier/{}'.format(verifier)\n ]:\n util.process_templates(template, extra_context, role_path)\n\n def _init_new_role(self, role, role_path, driver, verifier):\n extra_context = self._get_cookiecutter_context(role, driver, verifier)\n\n util.print_info('Initializing role {}...'.format(role))\n for template in [\n 'galaxy_init', 'playbook', 'driver/{}'.format(driver),\n 'verifier/{}'.format(verifier)\n ]:\n util.process_templates(template, extra_context, role_path)\n\n def _get_cookiecutter_context(self, role, driver, verifier):\n md = self.molecule.config.config['molecule']['init']\n platform = md.get('platform')\n provider = md.get('provider')\n\n d = {\n 'repo_name': role,\n 'role_name': role,\n 'driver_name': driver,\n 'dependency_name': 'galaxy', # static for now\n 'verifier_name': verifier,\n }\n if driver == 'vagrant':\n d.update({\n 'platform_name': platform.get('name'),\n 'platform_box': platform.get('box'),\n 'platform_box_url': platform.get('box_url'),\n 'provider_name': provider.get('name'),\n 'provider_type': provider.get('type')\n })\n\n return d\n\n def _get_driver(self):\n return self.command_args.get('driver')\n\n def _get_verifier(self):\n return self.command_args.get('verifier')\n\n\n@click.command()\n@click.option(\n '--role',\n help=('Name of role to create, otherwise initalize molecule inside '\n 'existing directory.'))\n@click.option(\n '--driver',\n type=click.Choice(['vagrant', 'docker', 'openstack']),\n default='vagrant',\n help='Name of driver to initialize.')\n@click.option(\n '--verifier',\n type=click.Choice(['testinfra', 'serverspec', 'goss']),\n default='testinfra',\n help='Name of verifier to initialize.')\n@click.pass_context\ndef init(ctx, role, driver, verifier): # pragma: no cover\n \"\"\"\n Creates the scaffolding for a new role intended for use with molecule.\n \"\"\"\n command_args = {'role': role, 'driver': driver, 'verifier': verifier}\n\n i = Init(ctx.obj.get('args'), command_args)\n i.execute\n util.sysexit(i.execute()[0])\n","sub_path":"molecule/command/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350291286","text":"'''\nAdvent of Code 2019 - Day 1 [Gold]\n\nFor each line in the input, recursively divide the number by 3 and take the floor, then subtract 2. This should continue until the value is negative (in which case break).\nSum the total of all the values generated above.\n'''\n\nif __name__ == '__main__':\n with open('input.txt', 'r') as f:\n input_text = f.read()\n\n parsed_input = [int(line) for line in input_text.split('\\n') if line]\n\n sum = 0\n\n for i in parsed_input:\n local_sum = 0\n\n while True:\n result = (i // 3) - 2\n\n if result < 0:\n break\n\n local_sum += result\n i = result\n\n sum += local_sum\n\n print(f'Solution: {sum}')\n","sub_path":"2019/1/gold.py","file_name":"gold.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"238671666","text":"from sys import exit\n\nbaka = False\ncheck = ''\nfinal = []\nn = input('Задача №1\\nВведите размер массива: ')\nn_t = n.split('e')\nif len(n_t) == 2:\n if n_t[0] == '' or n_t[1] == '':\n print('Wrong value was entered!')\n exit()\n if n_t[1][0] == '+':\n start = list(n_t[1])\n del start[0]\n n_t[1] = ''.join(start)\nn_t = ''.join(n_t)\nif n.isdigit() or n_t.isdigit():\n print('Введите значения массива (по одному):')\n n = int(float(n))\n orig_m = [0]*n\n for i in range(n):\n temp = input()\n orig_m[i] = temp\n pre_check = temp.split('e')\n if len(pre_check) > 2:\n baka = True\n elif len(pre_check) == 2:\n if pre_check[0] == '' or pre_check[1] == '':\n print('Wrong value was entered!')\n exit()\n temp1 = list(pre_check[0])\n if temp1[0] == '.' or temp1[0] == '-' or temp1[0] == \"+\":\n del temp1[0]\n temp1 = ''.join(temp1)\n\n temp1 = temp1.split(' ')\n if len(temp1) > 1:\n baka = True\n temp1 = ''.join(temp1)\n temp1 = temp1.split('-')\n if len(temp1) > 1:\n baka = True\n temp1 = ''.join(temp1)\n temp1 = temp1.split('.')\n if len(temp1) > 2:\n baka = True\n temp1 = ''.join(temp1)\n\n temp2 = list(pre_check[1])\n if temp2[0] == '-' or temp2[0] == \"+\":\n del temp2[0]\n temp2 = ''.join(temp2)\n temp2 = temp2.split(' ')\n if len(temp2) > 1:\n baka = True\n temp2 = ''.join(temp2)\n temp2 = temp2.split('-')\n if len(temp2) > 1:\n baka = True\n temp2 = ''.join(temp2)\n temp2 = temp2.split('.')\n if len(temp2) > 2:\n baka = True\n temp2 = ''.join(temp2)\n\n temp = temp1 + temp2\n else:\n temp = list(pre_check[0])\n if temp[0] == '.' or temp[0] == '-' or temp[0] == \"+\":\n del temp[0]\n temp = ''.join(temp)\n\n temp = temp.split(' ')\n if len(temp) > 1:\n baka = True\n temp = ''.join(temp)\n temp = temp.split('-')\n if len(temp) > 1:\n baka = True\n temp = ''.join(temp)\n temp = temp.split('.')\n if len(temp) > 2:\n baka = True\n temp = ''.join(temp)\n\n if baka or temp.isdigit() is False:\n print('Wrong value was entered!')\n exit('Invalid values')\nelse:\n print('Wrong value was entered!')\n exit()","sub_path":"1st_semester/Lab 6/Bogatyrev/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"581108165","text":"\"\"\"Laser pointer control.\n\nDefines a single class LaserPointer that allows control of a laser pointer via an FTDI device. This\nmodule assumes that an electrical interface between a single pin of the FTDI device and the laser\npointer allow the laser pointer on/off state to be controlled by the voltage level on that pin.\nThe details of that electrical interface are not specified.\n\"\"\"\n\nfrom pyftdi.ftdi import Ftdi\nfrom configargparse import Namespace\nfrom track.config import ArgParser\n\n\n# for purposes of set_bitmode bitmask:\n# bit set => output\n# bit unset => input\nPIN_TXD = (1<<0)\nPIN_RXD = (1<<1)\nPIN_RTS = (1<<2)\nPIN_CTS = (1<<3)\nPIN_DTR = (1<<4)\nPIN_DSR = (1<<5)\nPIN_DCD = (1<<6)\nPIN_RI = (1<<7)\n\n\nclass LaserPointer(object):\n \"\"\"Class for controlling a laser pointer via an FTDI device.\n\n This class allows a laser pointer to be controlled by toggling the state of a pin on an FTDI\n USB Serial device in bitbang mode.\n\n Attributes:\n laser_pin: An integer bitmask with a single bit set corresponding to the pin that the laser\n pointer is controlled by. See the set of constants defined at the top of this source\n file.\n ftdi: An object of type pyftdi.ftdi.Ftdi.\n \"\"\"\n\n def __init__(self, ftdi_pid='232r', serial_num=None, laser_pin=PIN_CTS):\n \"\"\"Inits LaserPointer object.\n\n Initializes a LaserPointer object by constructing an Ftdi object and opening the desired\n FTDI device. Configures the FTDI device to bitbang mode.\n\n Args:\n ftdi_pid: Product ID string for the FTDI device.\n serial_num: String containing the serial number of the FTDI device. If None, any\n serial number will be accepted.\n laser_pin: Integer bit mask with a single bit set corresponding to the pin on the FTDI\n device that controls the laser pointer.\n \"\"\"\n self.laser_pin = laser_pin\n\n self.ftdi = Ftdi()\n\n self.ftdi.open_bitbang(\n vendor=Ftdi.VENDOR_IDS['ftdi'],\n product=Ftdi.PRODUCT_IDS[Ftdi.FTDI_VENDOR][ftdi_pid],\n serial=serial_num, # serial number of FT232RQ in the laser FTDI cable\n latency=Ftdi.LATENCY_MAX, # 255ms; reduce if necessary (at cost of higher CPU usage)\n )\n\n # set laser_pin as output, all others as inputs\n self.ftdi.set_bitmode(self.laser_pin, Ftdi.BITMODE_BITBANG)\n assert self.ftdi.bitbang_enabled\n\n # make sure laser is disabled by default\n self.set(False)\n\n def __del__(self):\n # make sure laser is disabled on shutdown\n try:\n self.set(False)\n self.ftdi.close()\n except:\n pass\n\n def set(self, enable):\n \"\"\"Sets the state of the laser pointer.\n\n Args:\n enable: Laser pointer will be turned on when True and off when False.\n \"\"\"\n if enable:\n self.ftdi.write_data(bytes([0x00]))\n else:\n self.ftdi.write_data(bytes([self.laser_pin]))\n\n def get(self):\n \"\"\"Gets the current state of the laser pointer.\n\n This reads the current state from FTDI device and does not rely on any state information\n in this class.\n\n Returns:\n The current state of the laser pointer as a boolean.\n \"\"\"\n return (self.ftdi.read_pins() & self.laser_pin) == 0x0\n\n\ndef add_program_arguments(parser: ArgParser) -> None:\n \"\"\"Add program arguments relevant to laser pointers.\n\n Args:\n parser: The instance of ArgParser to which this function will add arguments.\n \"\"\"\n laser_group = parser.add_argument_group(\n title='Laser Pointer Options',\n description='Options that apply to laser pointers',\n )\n laser_group.add_argument(\n '--laser-ftdi-serial',\n help='serial number of laser pointer FTDI device',\n )\n\n\ndef make_laser_from_args(args: Namespace) -> LaserPointer:\n \"\"\"Construct a LaserPointer based on the program arguments provided.\n\n Args:\n args: Set of program arguments.\n \"\"\"\n return LaserPointer(serial_num=args.laser_ftdi_serial)\n","sub_path":"track/laser.py","file_name":"laser.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14778820","text":"\"\"\"\nA horizontal display of all the cards that\na player has piled up over the course of a ronda.\n\"\"\"\n\nimport tkinter as tk\nfrom PIL import Image, ImageTk\n\n\nclass CardScroll(tk.Frame):\n \"\"\"Horizontal lineup of cards\"\"\"\n def __init__(self, parent, player_image, cards):\n tk.Frame.__init__(self, parent)\n\n player_image.thumbnail((65, 65), Image.ANTIALIAS)\n img = ImageTk.PhotoImage(player_image)\n\n img_label = tk.Label(self, image=img, relief='solid')\n img_label.image = img\n img_label.grid(row=0, column=0, padx=10, sticky=\"we\", rowspan=2)\n\n self.cards = cards\n self._draw_cards(1)\n\n def _draw_cards(self, starting_col):\n \"\"\"Renders images and places them on the canvas.\"\"\"\n row = 0\n col = starting_col\n\n count = len(self.cards)\n # this should restrict things to two lines in most cases\n line_break_col = 8 if count < 17 else 12\n\n for card in self.cards:\n resized = card.image()\n resized.thumbnail((65, 65), Image.ANTIALIAS)\n\n image = ImageTk.PhotoImage(resized)\n lbl = tk.Label(self, image=image)\n lbl.image = image\n lbl.grid(row=row, column=col, sticky=\"we\")\n\n # split over two lines if holding more than 14 cards\n if count > 14 and col >= line_break_col:\n col = starting_col\n row += 1\n else:\n col += 1\n","sub_path":"quince/ui/components/score_report/card_scroll.py","file_name":"card_scroll.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"499438763","text":"\n\nfrom xai.brain.wordbase.nouns._transvestite import _TRANSVESTITE\n\n#calss header\nclass _TRANSVESTITES(_TRANSVESTITE, ):\n\tdef __init__(self,): \n\t\t_TRANSVESTITE.__init__(self)\n\t\tself.name = \"TRANSVESTITES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"transvestite\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_transvestites.py","file_name":"_transvestites.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"219195038","text":"import cards\nimport player\nfrom game_logic import game_logic as gl\n\n\n# anything not in a function is for debug/testing\n\n\ndef main():\n decks = cards.Deck()\n player.create_players()\n\n \"\"\"\n print(player.Player.List)\n for player_number in player.Player.List:\n print(player_number.player_number)\n \"\"\"\n player.create_teams()\n cards.create_hands()\n gl.calling_round()\n gl.play_round()\n \"\"\"\n print(player.Team.List)\n for team in player.Team.List:\n for person in team.players:\n print()\n print(person.player_number)\n for card in person.hand.cards:\n print(card.name)\n\n print()\n\n for card in decks.Cards:\n print(card.name)\n print()\n print(len(decks.Cards))\n \"\"\"\n quit()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"470092253","text":"# This script performs the following operations:\n# 1. Downloads the Flowers dataset\n# 2. Fine-tunes an InceptionV3 model on the Flowers training set.\n# 3. Evaluates the model on the Flowers validation set.\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\nfrom COMP7015_Mini_Project_1.Data.Flower import Flower_Data_Manager\nfrom COMP7015_Mini_Project_1.preprocessing import preprocessing_factory\nfrom COMP7015_Mini_Project_1.train import nets_factory\n\n# Where the pre-trained InceptionV3 checkpoint is saved to.\npretrained_checkpoint_dir = '/tmp/checkpoints'\n\n# Where the training (fine-tuned) checkpoint and logs will be saved to.\ntrain_dir = '/tmp/flowers-models/inception_v3'\n\nnum_preprocessing_threads = 4\nsplit_name = 'train'\nlabels_offset = 0\nweight_decay = 0.00004\nuse_grayscale = False\n\nnum_readers = 4\nbatch_size = 32\n\nlearning_rate = 0.01\nnum_epochs_per_decay = 2.0\nlearning_rate_decay_type = 'exponential'\nlearning_rate_decay_factor = 0.94\nend_learning_rate = 0.0001\n\ntrainable_scopes = None\n\ndef _get_variables_to_train():\n if trainable_scopes is None:\n return tf.trainable_variables()\n else:\n scopes = [scope.strip() for scope in trainable_scopes.split(',')]\n\n variables_to_train = []\n for scope in scopes:\n variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)\n variables_to_train.extend(variables)\n return variables_to_train\n\ndef _configure_learning_rate(num_samples_per_epoch, global_step):\n decay_steps = int(num_samples_per_epoch * num_epochs_per_decay / batch_size)\n\n if learning_rate_decay_type == 'exponential':\n return tf.train.exponential_decay(learning_rate,\n global_step,\n decay_steps,\n learning_rate_decay_factor,\n staircase=True,\n name='exponential_decay_learning_rate')\n\n elif learning_rate_decay_type == 'fixed':\n return tf.constant(learning_rate, name='fixed_learning_rate')\n\n elif learning_rate_decay_type == 'polynomial':\n return tf.train.polynomial_decay(learning_rate,\n global_step,\n decay_steps,\n end_learning_rate,\n power=1.0,\n cycle=False,\n name='polynomial_decay_learning_rate')\n else:\n raise ValueError('learning_rate_decay_type [%s] was not recognized' % learning_rate_decay_type)\n\ndef _configure_optimizer(learning_rate, optimizer='adam'):\n if optimizer == 'adam':\n optimizer = tf.train.AdamOptimizer(\n learning_rate,\n beta1=0.9,\n beta2=0.99,\n epsilon=1.0)\n elif optimizer == 'rmsprop':\n optimizer = tf.train.RMSPropOptimizer(\n learning_rate,\n decay=0.9,\n momentum=0.9,\n epsilon=1.0)\n elif optimizer == 'sgd':\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n else:\n raise ValueError('Optimizer [%s] was not recognized' % optimizer)\n return optimizer\n\ndef get_init_fn(checkpoints_dir, model_name):\n \"\"\"Returns a function run by the chief worker to warm-start the training.\"\"\"\n checkpoint_exclude_scopes = []\n\n exclusions = [scope.strip() for scope in checkpoint_exclude_scopes]\n\n variables_to_restore = []\n for var in slim.get_model_variables():\n for exclusion in exclusions:\n if var.op.name.startswith(exclusion):\n break\n else:\n variables_to_restore.append(var)\n\n # init_op= slim.assign_from_checkpoint_fn(os.path.join(checkpoints_dir, '%s.ckpt'%model_name), variables_to_restore)\n restorer = tf.train.Saver(variables_to_restore)\n return restorer\n\ndef main(model_name, checkpoints_dir, dataset_dir='D:/DataSet/flower_dataset/'):\n if not dataset_dir:\n raise ValueError('You must supply the dataset directory with --dataset_dir')\n\n # Create global_step\n global_step = tf.train.create_global_step()\n\n # Select the dataset #\n dataset = Flower_Data_Manager.get_split(split_name, dataset_dir, file_pattern=None, reader=None)\n\n # Select the network #\n network_fn = nets_factory.get_network_fn(model_name,\n num_classes=(dataset.num_classes - labels_offset),\n weight_decay=weight_decay, is_training=True)\n\n # Select the preprocessing function #\n preprocessing_name = model_name\n image_preprocessing_fn = preprocessing_factory.get_preprocessing(\n preprocessing_name,\n is_training=True,\n use_grayscale=use_grayscale)\n\n # Create a dataset provider that loads data from the dataset #\n provider = slim.dataset_data_provider.DatasetDataProvider(\n dataset,\n num_readers=num_readers,\n common_queue_capacity=20 * batch_size,\n common_queue_min=10 * batch_size)\n\n [image, label] = provider.get(['image', 'label'])\n label -= labels_offset\n\n train_image_size = network_fn.default_image_size\n\n image = image_preprocessing_fn(image, train_image_size, train_image_size)\n\n images, labels = tf.train.batch(\n [image, label],\n batch_size=batch_size,\n num_threads=num_preprocessing_threads,\n capacity=5 * batch_size)\n\n labels = slim.one_hot_encoding(labels, dataset.num_classes - labels_offset)\n logits, end_points = network_fn(images)\n\n entropy_loss = tf.nn.softmax_cross_entropy_with_logits(logits, labels)\n regularization_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n regularization_loss = tf.add_n(regularization_losses, name='regularization_loss')\n total_loss = entropy_loss + regularization_loss\n\n learning_rate = _configure_learning_rate(dataset.num_samples, global_step)\n optimizer = _configure_optimizer(learning_rate)\n\n # ------------------------------------------------------------------------------------------------\n variables_to_train = _get_variables_to_train()\n\n # update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n # with tf.control_dependencies(update_ops):\n # gradients = optimizer.compute_gradients(loss=total_loss, var_list=variables_to_train)\n # grad_updates = optimizer.apply_gradients(gradients, global_step=global_step)\n\n # -----------------------------------------------------------------------------------------------\n tf.logging.set_verbosity(tf.logging.INFO)\n # Specify the optimizer and create the train op:\n train_op = slim.learning.create_train_op(total_loss, optimizer, variables_to_train=variables_to_train)\n\n final_loss = slim.learning.train(\n train_op,\n logdir=train_dir,\n init_fn=get_init_fn(checkpoints_dir, model_name),\n number_of_steps=2)\n\nif __name__ == '__main__':\n\n pass\n","sub_path":"train/Fine_Tune_Example.py","file_name":"Fine_Tune_Example.py","file_ext":"py","file_size_in_byte":7050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"599067215","text":"from django.contrib.auth.models import User\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import EmailMessage\nfrom django.http import HttpResponseRedirect, HttpResponse, JsonResponse\nfrom django.shortcuts import render\nfrom django.template.loader import render_to_string\n\nfrom lectures.models import Lecture\nfrom main.forms import SignupForm, UserForm, QuestionForm\nfrom main.models import Question\nfrom main.tokens import account_activation_token\nfrom tag.models import Tag\n\n\ndef main_page(request):\n lectures_by_rating = Lecture.objects.filter(ratings__isnull=False).order_by('-ratings__average')[:3]\n lectures_by_date = Lecture.objects.order_by(\"-date\")[:3]\n return render(request, 'main/mainPage.html',\n {'lectures': lectures_by_date, 'tags': Tag.objects.all(), 'lectures_by_rating': lectures_by_rating})\n\n\ndef signup(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.is_active = False\n user.save()\n current_site = get_current_site(request)\n mail_subject = 'Activate your blog account.'\n message = render_to_string('main/acc_activate_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': user.pk,\n 'token': account_activation_token.make_token(user),\n })\n to_email = form.cleaned_data['email']\n email = EmailMessage(\n mail_subject, message, to=[to_email]\n )\n email.send()\n return HttpResponseRedirect('/confirmEmailPage')\n else:\n form = SignupForm()\n return render(request, 'main/signup.html', {'form': form})\n\n\ndef activate(request, uidb64, token):\n try:\n uid = uidb64\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n return HttpResponseRedirect('/login')\n else:\n return HttpResponse('Activation link is invalid!')\n\n\ndef confirm_email_page(request):\n return render(request, 'main/confirmEmailPage.html')\n\n\ndef profile(request, user_id):\n user = User.objects.get(pk=user_id)\n lectures_user = Lecture.objects.filter(author=user)\n lectures_all = Lecture.objects.all()\n user_form = UserForm()\n questions = Question.objects.filter(author=user)\n return render(request, 'main/profile.html',\n {'user': user, 'lectures_user': lectures_user,\n 'lectures_all': lectures_all, 'user_form': user_form, 'questions': questions})\n\n\ndef change_data(request):\n request_username = request.POST['username']\n if request_username.__len__() in range(3, 15) and User.objects.check(username=request_username) is not None:\n return_dict = change_username(request, request_username)\n return JsonResponse(return_dict)\n return JsonResponse({'status': 'false'}, status=500)\n\n\ndef change_theme(request):\n return_dict = dict()\n if request.POST['theme'] == \"math\":\n request.session['new_theme'] = request.POST['theme']\n return_dict[\"new_theme\"] = \"математическую\"\n elif request.POST['theme'] == \"humanity\":\n del request.session['new_theme']\n return_dict[\"new_theme\"] = \"гуманитарную\"\n return JsonResponse(return_dict)\n\n\ndef ask_question(request):\n return_dict = dict()\n question = Question()\n question.author = request.user\n question.lecture_author = Lecture.objects.get(pk=request.POST[\"lecture_id\"]).author\n question.text = request.POST[\"question\"]\n question.lecture_author = request.POST['lecture_id']\n question.save()\n return JsonResponse(return_dict)\n\n\ndef change_username(request, request_username):\n return_dict = dict()\n user = User.objects.get(pk=request.POST['user_id'])\n user.username = request_username\n user.save()\n return_dict['new_username'] = user.username\n return return_dict\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"150725039","text":"#!/usr/bin/python\n# -*- coding = utf-8 -*-\n\nclass Emap(object):\n def __init__(self, radio):\n super(Emap, self).__init__()\n self.radio = radio\n self.edges = []\n self.dic = {}\n\n def insert(self, lst, num):\n size = len(lst)\n if size == 0:\n return -1\n\n if size == 1:\n lst.append(num)\n return 1\n\n low = 1\n high = size - 1\n\n while low <= high:\n mid = (low + high) // 2\n value = lst[mid]\n\n if value > num:\n flag = True\n high = mid - 1\n elif value < num:\n low = mid + 1\n flag = False\n else:\n return -1\n\n if flag:\n lst.insert(mid, num)\n elif mid < size-1:\n lst.insert(mid+1, num)\n else:\n lst.append(num)\n\n return mid\n\n\n def search(self, lst, num):\n size = len(lst)\n if size <= 1:\n return -1\n\n low = 1\n high = size - 1\n\n while low <= high:\n mid = (low + high) // 2\n value = lst[mid]\n\n if value > num:\n flag = True\n high = mid - 1\n elif value < num:\n low = mid + 1\n flag = False\n else:\n return mid\n\n if flag:\n return mid\n else:\n return min(mid + 1, size - 1)\n\n\n def inserts(self, num):\n size = len(self.edges)\n if size == 0:\n self.edges.append([num])\n return 0\n\n low = 0\n high = size - 1\n\n while low <= high:\n mid = (low + high) // 2\n value = self.edges[mid][0]\n\n if value > num:\n flag = True\n high = mid - 1\n elif value < num:\n low = mid + 1\n flag = False\n else:\n return mid\n\n if flag:\n self.edges.insert(mid, [num])\n elif mid < size-1:\n self.edges.insert(mid+1, [num])\n mid = mid + 1\n else:\n self.edges.append([num])\n mid = size\n\n return mid\n\n\n def searchs(self, num):\n size = len(self.edges)\n if size == 0:\n return -1\n\n low = 0\n high = size - 1\n\n while low <= high:\n mid = (low + high) // 2\n value = self.edges[mid][0]\n\n if value > num:\n flag = True\n high = mid - 1\n elif value < num:\n low = mid + 1\n flag = False\n else:\n return mid\n\n if flag:\n return mid\n else:\n return min(mid + 1, size - 1)\n\n\n def load(self, edges):\n for edge in edges:\n e = edge.split(\"\\x00\")\n px = int(111200 * float(e[0]))\n py = int(111200 * float(e[1]))\n idx = self.inserts(px)\n self.insert(self.edges[idx], py)\n self.dic[\"\\x00\".join([str(px) , str(py)])] = edge\n\n def check(self, lst, py):\n idx = self.search(lst, py)\n i = idx - 1\n while i > 0:\n if abs(py - lst[i]) <= self.radio:\n return True\n i = i - 1\n\n i = idx\n while i < len(lst):\n if abs(lst[i] - py) <= self.radio:\n return True\n i = i + 1\n\n return False\n\n\n def checks(self, px, py):\n px = int(111200 * float(px))\n py = int(111200 * float(py))\n idx = self.searchs(px)\n i = idx - 1\n while i >= 0:\n if abs(px - self.edges[i][0]) >= self.radio:\n break\n if self.check(self.edges[i], py):\n yield self.dic.get(\"\\x00\".join([str(_) for _ in self.edges[i]]))\n i = i - 1\n\n i = idx\n while i < len(self.edges):\n if abs(self.edges[i][0] - px) >= self.radio:\n break\n if self.check(self.edges[i], py):\n yield self.dic.get(\"\\x00\".join([str(_) for _ in self.edges[i]]))\n i = i + 1\n\n\n","sub_path":"webapps/jubaopen/actions/map/emap.py","file_name":"emap.py","file_ext":"py","file_size_in_byte":4166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"569014066","text":"import sys, pygame, random, math\npygame.init()\n\ndef rot_center(image, angle):\n \"\"\"rotate an image while keeping its center and size\"\"\"\n orig_rect = image.get_rect().copy()\n rot_image = pygame.transform.rotate(image, angle)\n orig_rect.center = rot_image.get_rect().center\n rot_image = rot_image.subsurface(orig_rect).copy()\n return rot_image\n\nsize = (width, height) = (640, 480)\nspeed = [2, 2]\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\n\nscreen = pygame.display.set_mode(size)\nball = pygame.image.load('ball_black.gif')\nball_w = ball_h = 40\nball_sdir = 1\nball_sang = 6\nball_ang = 0\nball = pygame.transform.scale(ball, (ball_w, ball_h))\norig_ball = ball.copy()\nballrect = pygame.Rect(0, 0, ball_w, ball_h)\nball_held = False\nprev_mouse_lst = [(0, 0)]\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n ball_held = True\n prev_mouse_lst = [pygame.mouse.get_pos()]\n elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:\n ball_held = False\n elif event.type == pygame.KEYUP:\n if event.key == 273:\n ball_sang += 1\n if event.key == 274 and ball_sang > 0:\n ball_sang -= 1\n\n if ball_held:\n cur_mouse = pygame.mouse.get_pos()\n ballrect.center = cur_mouse\n prev_mouse_lst.append(cur_mouse)\n if len(prev_mouse_lst) > 5:\n del prev_mouse_lst[0]\n speed = [(cur_mouse[0] - prev_mouse_lst[0][0]) / 10.,\n (cur_mouse[1] - prev_mouse_lst[0][1]) / 10.]\n else:\n ballrect = ballrect.move(speed)\n ball_ang = (ball_ang + ball_sdir * ball_sang) % 360\n ball = rot_center(orig_ball, ball_ang)\n if ballrect.left < 0 or ballrect.right > width:\n speed[0] = -speed[0]\n ball_sdir = math.copysign(1, speed[1] * ballrect.left)\n if ballrect.top < 0 or ballrect.bottom > height:\n speed[1] = -speed[1]\n ball_sdir = math.copysign(1, -speed[0] * ballrect.top)\n\n screen.fill(black)\n screen.blit(ball, ballrect)\n pygame.display.update()\n pygame.time.delay(10)\n","sub_path":"python/pygame_ball/pygame_ball.py","file_name":"pygame_ball.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"519043058","text":"\"\"\"\nper-directory pytest configuration\nThis makes the fixtures available to tests within this directory\n\"\"\"\nfrom glob import glob\n\n\ndef refactor(string: str) -> str:\n \"\"\"python file path to module name converter\"\"\"\n return string.replace(\"/\", \".\").replace(\"\\\\\", \".\").replace(\".py\", \"\")\n\n\npytest_plugins = [\n refactor(fixture) for fixture in glob(\"tests/fixtures/*.py\") if \"__\" not in fixture\n]\n","sub_path":"tests/unit/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"387252364","text":"# ライブラリ読み込み\nfrom gensim import models\nfrom lib import utils\n\n\nclass Doc2Vec:\n def __init__(self, *, alpha=0.025, min_alpha=0.00025, min_count=5, sample=1e-5, vector_size=100, epochs=20, workers=4):\n self.alpha = alpha\n self.min_alpha = min_alpha\n self.min_count = min_count\n self.sample = sample\n self.vector_size = vector_size\n self.epochs = epochs\n self.workers = workers\n self.label = None\n self.model = None\n\n def load_model(self, path):\n # モデルをロード\n self.model = models.Doc2Vec.load(path)\n\n def update(self, docs, label):\n sentences = utils.LabeledListSentence(docs, label)\n self.model.build_vocab(sentences, update=True)\n self.model.train(sentences, total_examples=self.model.corpus_count, epochs=self.model.iter)\n self.model.save('./model/doc2vec/updated_doc2vec_' + str(self.vector_size) + '.model')\n\n def train(self, docs, label):\n sentences = utils.LabeledListSentence(docs, label)\n\n # doc2vec の学習条件設定\n # alpha: 学習率 / min_count: X回未満しか出てこない単語は無視\n # size: ベクトルの次元数 / iter: 反復回数 / workers: 並列実行数\n self.model = models.Doc2Vec(alpha=self.alpha, min_alpha=self.min_count, min_count=self.min_count, sample=self.sample, vector_size=self.vector_size, epochs=self.epochs, workers=self.workers)\n\n # doc2vec の学習前準備(単語リスト構築)\n self.model.build_vocab(sentences)\n\n # Wikipedia から学習させた単語ベクトルを無理やり適用して利用することも出来ます\n # self.model.intersect_word2vec_format('./model/word2vec/entity_vector.model.bin', binary=True)\n\n # 学習実行\n self.model.train(sentences, total_examples=self.model.corpus_count, epochs=self.model.iter)\n # training = 10\n # for epoch in range(training):\n # print('epoch ' + str(epoch + 1))\n\n # セーブ\n self.model.save('./model/doc2vec/doc2vec_' + str(self.vector_size) + '.model')\n\n # 順番が変わってしまうことがあるので会社リストは学習後に再呼び出し\n self.label = self.model.docvecs.offset2doctag\n\n def to_vector(self, docs):\n sent_vecs = []\n for doc in docs:\n sent_vecs.append(self.model.infer_vector(doc))\n\n return sent_vecs\n","sub_path":"lib/doc2vec.py","file_name":"doc2vec.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"161006362","text":"\nclass NoteSequencer(object):\n def __init__(self, sched, synth, channel, patch=(0, 40), callback=None, velocity=100, pitches=None):\n super(NoteSequencer, self).__init__()\n\n self.sched = sched\n self.synth = synth\n self.channel = channel\n self.patch = patch\n self.callback = callback\n self.velocity = velocity\n self.pitches = pitches\n\n self.notes = None\n\n # Runtime Variables\n self.cur_idx = 0\n self.loop = False\n self.on_cmd = None\n self.off_cmd = None\n self.playing = False\n\n def set_notes(self, notes, loop):\n self.notes = notes\n self.loop = loop\n self.cur_idx = 0\n\n def start(self):\n if not self.playing:\n self.playing = True\n self.synth.program(self.channel, self.patch[0], self.patch[1])\n self.on_cmd = self.sched.post_at_tick(self.sched.get_tick(), self._noteon, None)\n\n def stop(self):\n if self.playing:\n self.playing = False\n\n self.sched.remove(self.on_cmd)\n self.sched.remove(self.off_cmd)\n if self.off_cmd:\n self.off_cmd.execute()\n\n # reset these so we don't have a reference to old commands.\n self.on_cmd = None\n self.off_cmd = None\n\n def _get_next_note(self):\n duration, pitch = self.notes[self.cur_idx]\n notes_len = len(self.notes)\n\n # advance index\n self.cur_idx += 1\n\n # reset index, if looping\n if self.loop:\n self.cur_idx = self.cur_idx % notes_len\n # otherwise, stop if we have reached end of the notes\n else:\n if self.cur_idx == notes_len:\n self.stop()\n self.cur_idx = notes_len - 1\n\n return duration, pitch\n\n def _noteon(self, tick, ignore):\n if self.playing:\n duration, pitch = self._get_next_note()\n\n # Avoid doing anything for rests\n if pitch != 0:\n # play note on:\n self.synth.noteon(self.channel, pitch, self.velocity)\n\n # post the note-off at the appropraiate tick:\n off_tick = tick + duration\n self.off_cmd = self.sched.post_at_tick(off_tick, self._noteoff, pitch)\n\n # callback:\n if self.callback is not None:\n self.callback(self.pitches.index(pitch))\n\n # post next note\n self.on_cmd = self.sched.post_at_tick(tick + duration, self._noteon, None)\n\n def _noteoff(self, tick, pitch):\n self.synth.noteoff(self.channel, pitch)","sub_path":"code/common/backup_notesequencer.py","file_name":"backup_notesequencer.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"479259532","text":"\"\"\"urlconf for the base application\"\"\"\n\nfrom django.conf.urls import url, patterns, include\nfrom forms import AdvancedSearchForm, AdvFacetedSearchForm, AdvModelSearchForm\nfrom haystack.views import SearchView, search_view_factory, FacetedSearchView\nfrom haystack.query import SearchQuerySet\n\nsqs = SearchQuerySet().facet('prop_19_exact')\n\nurlpatterns = patterns('base.views',\n url(r'^admin/base/file/add/', 'addfile', name='addfile'),\n url(r'^$', 'home', name='home'),\n url(r'^map/(?P\\d+)/$', 'mapdetail', name='mapdetail'),\n url(r'^about/ur-online-project', 'about', name='about'),\n url(r'^about/ancient-ur/', 'ancientur', name='ancientur'),\n url(r'^about/excavations/', 'excavations', name='excavations'),\n url(r'^about/woolleys-excavations/', 'woolley', name='woolley'),\n url(r'^about/cast-of-characters/', 'characters', name='characters'),\n url(r'^developers/', 'developers', name='developers'),\n url(r'^sample/', 'sample', name='sample'),\n url(r'^search/', FacetedSearchView(\n form_class = AdvModelSearchForm,\n searchqueryset = sqs\n ), name='haystack_search'),\n # ex: /ur.iaas.upenn.edu/subject/5/\n url(r'^subject/(?P\\d+)/$', 'subjectdetail', name='subjectdetail'),\n # ex: /ur.iaas.upenn.edu/personorg/5/\n url(r'^personorg/(?P\\d+)/$', 'personorgdetail', name='personorgdetail'),\n # ex: /ur.iaas.upenn.edu/media/5/\n url(r'^media_item/(?P\\d+)/$', 'mediadetail', name='mediadetail'),\n url(r'^property/(?P\\d+)/$', 'propertydetail', name='propertydetail'),\n url(r'^terminology/', 'terminology', name='terminology'),\n url(r'^browse/', 'browse', name='browse'),\n url(r'^collections/', 'collections', name='collections'), \n url(r'^term/(?P\\d+)/$', 'termdetail', name='termdetail'), \n url(r'^collection/(?P\\d+)/$', 'collectiondetail', name='collectiondetail'), \n url(r'^term_export/(?P\\d+)/$', 'termdetailexport', name='termdetailexport'),\n url(r'^collection_export/(?P\\d+)/$', 'collectiondetailexport', name='collectiondetailexport'), \n url(r'^location/(?P\\d+)/$', 'locationdetail', name='locationdetail'),\n url(r'^location_export/(?P\\d+)/$', 'locationdetailexport', name='locationdetailexport'), \n url(r'^search_help/', 'search_help', name='search_help'),\n url(r'^help/', 'help', name='help'),\n url(r'^update_index/', 'update_index', name='update_index'),\n url(r'^news/(?P[\\w\\-]+)/$', 'post'),\n url(r'^news/', 'news', name='news'),\n url(r'^contact/', 'contact', name='contact'),\n url(r'^property_export/(?P\\d+)/$', 'export_property_details', name='export_property_details'),\n url(r'^control_property_export/(?P\\d+)/$', 'export_control_property_details', name='export_control_property_details'), \n url(r'^result_export/', 'export_search_results', name='export_search_results'),\n url(r'^single_loc_in_ah/', 'kyra_special_ah', name='kyra_special_ah'),\n url(r'^search_export/(?P\\S+)/$', 'search_export', name='search_export'),\n url(r'^kyra_special_2/', 'kyra_special_2', name='kyra_special_2'),\n url(r'^select2/', include('django_select2.urls')),\n url(r'^bulk_update_subject/$', 'bulk_update_subject', name='bulk_update_subject'),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n url(r'^bulk_upload_file/', 'bulk_upload_file', name='bulk_upload_file'),\n)\n","sub_path":"base/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"578996143","text":"#!/usr/bin/env python\n# ASN.1 Data model\nasn1Files = []\nasn1Modules = []\nexportedTypes = {}\nexportedVariables = {}\nimportedModules = {}\ntypes = {}\nvariables = {}\nasn1Files.append(\"./dataview-uniq.asn\")\nasn1Modules.append(\"TASTE-Dataview\")\nexportedTypes[\"TASTE-Dataview\"] = [\"MyInteger\", \"MyReal\", \"MyBool\", \"MyEnum\", \"MySeq\", \"MyChoice\", \"MySeqOf\", \"MyOctStr\", \"MySeq-validity\", \"T-Int32\", \"T-UInt32\", \"T-Int8\", \"T-UInt8\", \"T-Boolean\"]\nexportedVariables[\"TASTE-Dataview\"] = [\"myVar\"]\nimportedModules[\"TASTE-Dataview\"] = [{\"TASTE-BasicTypes\":{\"ImportedTypes\": [\"T-Int32\",\"T-UInt32\",\"T-Int8\",\"T-UInt8\",\"T-Boolean\"], \"ImportedVariables\": []}}]\n\ntypes[\"MyInteger\"] = type(\"MyInteger\", (object,), {\n \"Line\": 6, \"CharPositionInLine\": 0, \"type\": type(\"MyInteger_type\", (object,), {\n \"Line\": 6, \"CharPositionInLine\": 16, \"kind\": \"ReferenceType\", \"ReferencedTypeName\": \"T-UInt8\", \"Min\": \"0\", \"Max\": \"255\", \"ReferencedModName\": \"TASTE-BasicTypes\"\n })\n})\n\ntypes[\"MyReal\"] = type(\"MyReal\", (object,), {\n \"Line\": 8, \"CharPositionInLine\": 0, \"type\": type(\"MyReal_type\", (object,), {\n \"Line\": 8, \"CharPositionInLine\": 16, \"kind\": \"RealType\", \"Min\": \"-1.00000000000000000000E+003\", \"Max\": \"1.00000000000000000000E+003\"\n })\n})\n\ntypes[\"MyBool\"] = type(\"MyBool\", (object,), {\n \"Line\": 10, \"CharPositionInLine\": 0, \"type\": type(\"MyBool_type\", (object,), {\n \"Line\": 10, \"CharPositionInLine\": 16, \"kind\": \"BooleanType\"\n })\n})\n\ntypes[\"MyEnum\"] = type(\"MyEnum\", (object,), {\n \"Line\": 12, \"CharPositionInLine\": 0, \"type\": type(\"MyEnum_type\", (object,), {\n \"Line\": 12, \"CharPositionInLine\": 16, \"kind\": \"EnumeratedType\", \"Extensible\": \"False\", \"ValuesAutoCalculated\": \"False\", \"EnumValues\": {\n \"hello\": type(\"hello\", (object,), {\n \"IntValue\": 0, \"Line\": 12, \"CharPositionInLine\": 29, \"EnumID\": \"hello\"\n }),\n \"world\": type(\"world\", (object,), {\n \"IntValue\": 1, \"Line\": 12, \"CharPositionInLine\": 36, \"EnumID\": \"world\"\n }),\n \"howareyou\": type(\"howareyou\", (object,), {\n \"IntValue\": 2, \"Line\": 12, \"CharPositionInLine\": 43, \"EnumID\": \"howareyou\"\n })\n }\n })\n})\n\ntypes[\"MySeq\"] = type(\"MySeq\", (object,), {\n \"Line\": 14, \"CharPositionInLine\": 0, \"type\": type(\"MySeq_type\", (object,), {\n \"Line\": 14, \"CharPositionInLine\": 16, \"kind\": \"SequenceType\", \"Children\": {\n \"input-data\": type(\"input-data\", (object,), {\n \"Optional\": \"False\", \"Line\": 15, \"CharPositionInLine\": 4, \"type\": type(\"input-data_type\", (object,), {\n \"Line\": 15, \"CharPositionInLine\": 16, \"kind\": \"ReferenceType\", \"ReferencedTypeName\": \"MyInteger\", \"Min\": \"0\", \"Max\": \"255\"\n })\n }),\n \"output-data\": type(\"output-data\", (object,), {\n \"Optional\": \"False\", \"Line\": 16, \"CharPositionInLine\": 4, \"type\": type(\"output-data_type\", (object,), {\n \"Line\": 16, \"CharPositionInLine\": 16, \"kind\": \"ReferenceType\", \"ReferencedTypeName\": \"MyInteger\", \"Min\": \"0\", \"Max\": \"255\"\n })\n }),\n \"validity\": type(\"validity\", (object,), {\n \"Optional\": \"False\", \"Line\": 17, \"CharPositionInLine\": 4, \"type\": type(\"validity_type\", (object,), {\n \"Line\": 0, \"CharPositionInLine\": 0, \"kind\": \"ReferenceType\", \"ReferencedTypeName\": \"MySeq-validity\"\n })\n })\n }\n })\n})\n\ntypes[\"MyChoice\"] = type(\"MyChoice\", (object,), {\n \"Line\": 20, \"CharPositionInLine\": 0, \"type\": type(\"MyChoice_type\", (object,), {\n \"Line\": 20, \"CharPositionInLine\": 16, \"kind\": \"ChoiceType\", \"Children\": {\n \"a\": type(\"a_PRESENT\", (object,), {\n \"Line\": 21, \"CharPositionInLine\": 4, \"EnumID\": \"a_PRESENT\", \"type\": type(\"a_PRESENT_type\", (object,), {\n \"Line\": 21, \"CharPositionInLine\": 6, \"kind\": \"BooleanType\"\n })\n }),\n \"b\": type(\"b_PRESENT\", (object,), {\n \"Line\": 22, \"CharPositionInLine\": 4, \"EnumID\": \"b_PRESENT\", \"type\": type(\"b_PRESENT_type\", (object,), {\n \"Line\": 22, \"CharPositionInLine\": 6, \"kind\": \"ReferenceType\", \"ReferencedTypeName\": \"MySeq\"\n })\n })\n }\n })\n})\n\ntypes[\"MySeqOf\"] = type(\"MySeqOf\", (object,), {\n \"Line\": 25, \"CharPositionInLine\": 0, \"type\": type(\"MySeqOf_type\", (object,), {\n \"Line\": 25, \"CharPositionInLine\": 16, \"kind\": \"SequenceOfType\", \"Min\": \"2\", \"Max\": \"2\", \"type\": type(\"SeqOf_type\", (object,), {\n \"Line\": 25, \"CharPositionInLine\": 39, \"kind\": \"ReferenceType\", \"ReferencedTypeName\": \"MyEnum\"\n })\n })\n})\n\ntypes[\"MyOctStr\"] = type(\"MyOctStr\", (object,), {\n \"Line\": 27, \"CharPositionInLine\": 0, \"type\": type(\"MyOctStr_type\", (object,), {\n \"Line\": 27, \"CharPositionInLine\": 16, \"kind\": \"OctetStringType\", \"Min\": \"3\", \"Max\": \"3\"\n })\n})\n\ntypes[\"MySeq-validity\"] = type(\"MySeq-validity\", (object,), {\n \"Line\": 0, \"CharPositionInLine\": 0, \"type\": type(\"MySeq-validity_type\", (object,), {\n \"Line\": 17, \"CharPositionInLine\": 16, \"kind\": \"EnumeratedType\", \"Extensible\": \"False\", \"ValuesAutoCalculated\": \"False\", \"EnumValues\": {\n \"valid\": type(\"valid\", (object,), {\n \"IntValue\": 0, \"Line\": 17, \"CharPositionInLine\": 29, \"EnumID\": \"valid\"\n }),\n \"invalid\": type(\"invalid\", (object,), {\n \"IntValue\": 1, \"Line\": 17, \"CharPositionInLine\": 36, \"EnumID\": \"invalid\"\n })\n }\n })\n})\n\n\nvariables[\"myVar\"] = type(\"myVar\", (object,), {\n \"Line\": 30,\n \"CharPositionInLine\": 0,\n \"varName\": \"myVar\",\n \"type\": type(\"myVar_type\", (object,), {\n \"Line\": 30, \"CharPositionInLine\": 12, \"kind\": \"ReferenceType\", \"ReferencedTypeName\": \"MySeqOf\", \"Min\": \"2\", \"Max\": \"2\"\n }),\n \"value\": {\"hello\", \"world\"}\n})\n\nasn1Modules.append(\"TASTE-BasicTypes\")\nexportedTypes[\"TASTE-BasicTypes\"] = [\"T-Int32\", \"T-UInt32\", \"T-Int8\", \"T-UInt8\", \"T-Boolean\"]\nexportedVariables[\"TASTE-BasicTypes\"] = []\nimportedModules[\"TASTE-BasicTypes\"] = []\n\ntypes[\"T-Int32\"] = type(\"T-Int32\", (object,), {\n \"Line\": 39, \"CharPositionInLine\": 0, \"type\": type(\"T-Int32_type\", (object,), {\n \"Line\": 39, \"CharPositionInLine\": 13, \"kind\": \"IntegerType\", \"Min\": \"-2147483648\", \"Max\": \"2147483647\"\n })\n})\n\ntypes[\"T-UInt32\"] = type(\"T-UInt32\", (object,), {\n \"Line\": 41, \"CharPositionInLine\": 0, \"type\": type(\"T-UInt32_type\", (object,), {\n \"Line\": 41, \"CharPositionInLine\": 13, \"kind\": \"IntegerType\", \"Min\": \"0\", \"Max\": \"4294967295\"\n })\n})\n\ntypes[\"T-Int8\"] = type(\"T-Int8\", (object,), {\n \"Line\": 43, \"CharPositionInLine\": 0, \"type\": type(\"T-Int8_type\", (object,), {\n \"Line\": 43, \"CharPositionInLine\": 11, \"kind\": \"IntegerType\", \"Min\": \"-128\", \"Max\": \"127\"\n })\n})\n\ntypes[\"T-UInt8\"] = type(\"T-UInt8\", (object,), {\n \"Line\": 45, \"CharPositionInLine\": 0, \"type\": type(\"T-UInt8_type\", (object,), {\n \"Line\": 45, \"CharPositionInLine\": 12, \"kind\": \"IntegerType\", \"Min\": \"0\", \"Max\": \"255\"\n })\n})\n\ntypes[\"T-Boolean\"] = type(\"T-Boolean\", (object,), {\n \"Line\": 47, \"CharPositionInLine\": 0, \"type\": type(\"T-Boolean_type\", (object,), {\n \"Line\": 47, \"CharPositionInLine\": 14, \"kind\": \"BooleanType\"\n })\n})\n\n\n","sub_path":"UseCase1/obsw/DataView.py","file_name":"DataView.py","file_ext":"py","file_size_in_byte":7300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"386221748","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jun 8 16:19:45 2020\r\n这是建立发动蛋白的粗粒度模型,在运行程序前\r\n请大声喊出:平头傻逼,否则程序会启动自毁程序\r\n@author: Wang\r\n\"\"\"\r\n# import numpy as np\r\nimport math\r\nd = 40 #圆片直径\r\nm = 1 #螺旋圈数\r\nr = 100 #孔半径\r\nh = 50 #螺旋高度(必须大于等于round(m)*d)\r\nn = 133 #原片数\r\nc = 4 #圆片珠子层数\r\ns = 28 #第一层珠子数\r\nfw = open('luoxvan.xyz','w')\r\nfor i in range(n):\r\n z = i * h / n\r\n x = r * math.cos(math.pi*2*m*i/n)\r\n y = r * math.sin(math.pi*2*m*i/n)\r\n R = math.sqrt(x**2 + y**2 + z**2) #原点极径\r\n theta = math.asin(z/R) #z轴角度\r\n fi = math.acos(x/math.sqrt(x**2+y**2)) #x轴角度\r\n print(x,y,z,end = ' ', file = fw)\r\n print(file = fw)\r\n for j in range(c,0,-1):\r\n x_1 = x * (R-d/2*j/c)/R #近原点x\r\n y_1 = y * (R-d/2*j/c)/R #近原点y\r\n z_1 = z * (R-d/2*j/c)/R #近原点z\r\n x_2 = x * (R+d/2*j/c)/R #近原点x\r\n y_2 = y * (R+d/2*j/c)/R #近原点y\r\n z_2 = z * (R+d/2*j/c)/R #近原点z\r\n print(x_1,y_1,z_1,end = ' ', file = fw)\r\n print(file = fw)\r\n print(x_2,y_2,z_2,end = ' ', file = fw)\r\n print(file = fw)\r\n p = int(round((s-2)/2/math.pow(1.472,(c-j)))+1)\r\n for k in range(1,p):\r\n R1 = math.sqrt(R**2+(d/2*j/c)**2-R*d*j/c*math.cos(k*math.pi/p)) #圆盘极径\r\n beta = math.acos((R**2+R1**2-(d/2*j/c)**2)/2/R/R1) #两极径夹角\r\n x1 = R1*math.cos(theta-beta)*math.cos(math.pi*2*m*i/n)\r\n y1 = R1*math.cos(theta-beta)*math.sin(math.pi*2*m*i/n)\r\n z1 = R1*math.sin(theta-beta) \r\n x2 = R1*math.cos(theta+beta)*math.cos(math.pi*2*m*i/n)\r\n y2 = R1*math.cos(theta+beta)*math.sin(math.pi*2*m*i/n)\r\n z2 = R1*math.sin(theta+beta)\r\n print(x1,y1,z1,end = ' ', file = fw)\r\n print(file = fw)\r\n print(x2,y2,z2,end = ' ', file = fw)\r\n print(file = fw)\r\nfw.close()\r\n# 制作ipt文件 谈谈吧,啥感受\r\nposition = []\r\nf_in = open('luoxvan.xyz','r')\r\nf_out = open('SBZ.itp','w')\r\nfout = open('SBZ.pdb','w')\r\ncount=0\r\nfor line in f_in.readlines():\r\n count=count+1\r\nf_in.close()\r\nf_in = open('luoxvan.xyz','r')\r\np = int(count/n)\r\nprint('[moleculetype]',file=f_out)\r\nprint('; molname nrexcl',file=f_out)\r\nprint(' MOL 1',file=f_out)\r\nprint(file=f_out)\r\nprint('[atoms]',file=f_out)\r\nprint('; id \ttype \tresnr \tresidu \tatom \tcgnr \tcharge', file=f_out)\r\nfor i in range(1,int(count+1)):\r\n print(' ', i, ' P4 ', 1, ' MOL ', 'SBZ ', i, ' 0', end=' ', file=f_out)\r\n print(file=f_out)\r\nprint('[bonds]',file=f_out)\r\nprint('; i j \tfunct \tlength \tforce.c.',file=f_out)\r\nfor i in range(count):\r\n line = f_in.readline()\r\n atom = line.split()\r\n ATOM = [float(x) for x in atom]\r\n position.append(ATOM)\r\nfor i in range(n-1):\r\n start = int(i*p)\r\n end = int((i+1)*p)\r\n for j in range(start,end):\r\n X = position[int(j+p)][0] - position[j][0]\r\n Y = position[int(j+p)][1] - position[j][1]\r\n Z = position[int(j+p)][2] - position[j][2]\r\n R = math.sqrt(X**2+Y**2+Z**2)\r\n print(' ', j+1,'', j+1+p, ' 1 ', round(R/10,4), ' 1000', end=' ', file=f_out)\r\n print(file=f_out)\r\n for k in range(int(j+1),end):\r\n x = position[k][0] - position[j][0]\r\n y = position[k][1] - position[j][1]\r\n z = position[k][2] - position[j][2]\r\n r = math.sqrt(x**2+y**2+z**2)\r\n if r < 8:\r\n print(' ', j+1,'', k+1, ' 1 ', round(r/10,4), ' 125000', end=' ', file=f_out)\r\n print(file=f_out)\r\nfor i in range(count):\r\n print(\"ATOM{0:>7d}{1:>3s}{2:>6s}{3:>6d}{4:>12.3f}{5:>8.3f}{6:>8.3f}{7:>6.2f}{8:>6.2f}\".format(i+1,'P4','MOL',1,position[i][0],position[i][1],position[i][2],1.00,0.00), file=fout)\r\nprint(\"TER{0:>8d}\".format(count+1), file=fout)\r\nf_in.close()\r\nf_out.close()\r\nfout.close()","sub_path":"pingtoujianmo/fadongdanbai.py","file_name":"fadongdanbai.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"254462644","text":"from django.shortcuts import render\nimport requests\nimport json\n# Create your views here.\n\n\n\ndef home(request):\n\n\tresponse = json.loads(requests.get(\"https://dog.ceo/api/breeds/list/all\").content)\n\tdog_breed_list = []\n\tfor key,val in response['message'].items():\n\t\tif response['message'][key]:\n\t\t\tfor nested_breed_types in response['message'][key]:\n\t\t\t\tdog_breed_list.append(key+\"-\"+nested_breed_types)\n\t\telse:\n\t\t\tdog_breed_list.append(key)\n\n\tcontext = {\n\t\t\"dog_breed_list\" : dog_breed_list,\n\t}\n\n\ttemplate = \"home.html\"\n\n\treturn render(request,template,context)\n\n\n\ndef breed_image(request,slug):\n\n\tresponse = json.loads(requests.get(\"https://dog.ceo/api/breed/\"+slug+\"/images/random\").content)\t\n\tcontext = {\n\t\t\"breed_image\": response['message']\n\n\t}\n\n\ttemplate = \"breed_image.html\"\n\n\treturn render(request,template ,context)\n","sub_path":"holivirtualenv/holidog/dogbreeds/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"628523305","text":"#!/usr/bin/env python3.4\n#coding: utf8\n\n\nimport socket,sys,os\n#from gestionErr.py import *\nfrom getpass import getpass\nimport hashlib\n\n\nTCP_IP ='127.0.0.1'\n\nTCP_PORT = 6264\n\nBUFFER_SIZE = 1024\nhistorique = \" \"\n\n\ns= socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\ns.connect((TCP_IP,TCP_PORT))\ndecision=\"\"\n\ndef PlsrLignes ():\n\ta = \" \"\n\tb = \"\"\n\twhile str(b) != \"§\":\n\t\tb = input(\"> \")\n\t\tif str(b) != \"§\" :\n\t\t\ta = a + \"\\n\"+str(b)\n\treturn a\n\nDROIT = ''\n\nwhile decision!= \"exit\":\n\tprint(\"=====================================================================================\")\n\tprint(\"<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>\")\n\tprint(\"Voulez vous:\\n\\t¤ Vous connectez en tant qu'Administrateur (admin) ?\\n\\t¤ Vous connecter(login)?\\n\\t¤ Quitter(exit)?\")\n\n\n\tservice=True\n\tsession=True\n\ttout=True\n\tverrouille=True\n\n\tdecision=input(\">> \")\n\ts.send(decision.encode())\n\n\n\n\tif decision == \"login\":\n\n\t\twhile tout:\n\t\t\tuser=''\n\t\t\twhile service:\n\t\t\t\tsaisie=input(\"Quel service ? (Medecin, Infirmier, Interne) \\n >> \")\n\t\t\t\tsaisie=saisie.encode()\n\t\t\t\ts.send(saisie)\n\n\t\t\t\tdata=s.recv(10)\n\t\t\t\tdata=data.decode()\n\t\t\t\tprint (data)\n\t\t\t\tif data == \"1\":\n\t\t\t\t\tprint(\"Vous etes un Médecin \\n\")\n\t\t\t\t\tDROIT='M'\n\t\t\t\t\tservice=False\n\t\t\t\telif data == \"2\":\n\t\t\t\t\tprint(\"Vous etes un Infirmier \\n\")\n\t\t\t\t\tDROIT=''\n\t\t\t\t\tservice=False\n\t\t\t\telif data == \"3\":\n\t\t\t\t\tprint(\"Vous etes un Interne \\n\")\n\t\t\t\t\tDROIT=''\n\t\t\t\t\tservice=False\n\t\t\t\telse:\n\n\t\t\t\t\tprint(\"Service inconnu\")\n\n\t\t\twhile session and user != 'retour':\n\n\t\t\t\tuser=input(\"Utilisateur : \")\n\t\t\t\tuser=user.encode()\n\t\t\t\ts.send(user)\n\n\t\t\t\tdata2=s.recv(30)\n\t\t\t\tdata2=data2.decode()\n\n\t\t\t\tif data2 == \"1\":\n\t\t\t\t\tsession=False\n\t\t\t\t\ttout = False\n\t\t\t\t\tprint(\"Utilisateur reconnu\")\n\t\t\t\telif data2 == \"return\":\n\t\t\t\t\tservice=True\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tprint (\"Utilisateur inconnu\")\n\n\t\t\twhile verrouille and tout == False :\n\t\t\t\ts.send(b\"OKmdp\")\n\t\t\t\tTimeline=s.recv(30)\n\t\t\t\tTimeline=Timeline.decode()\n\t\t\t\tprint(Timeline)\n\n\t\t\t\tif Timeline == \"Reste 0 essai\":\n\t\t\t\t\tprint(\"Plus d'essai disponible\")\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tsaisie=getpass(\"Mot de passe: \")\n\t\t\t\t\tsaisie=saisie.encode()\n\t\t\t\t\ts.send(saisie)\n\n\t\t\t\tverif=s.recv(10)\n\t\t\t\tverif=verif.decode()\n\t\t\t\tprint (verif)\n\t\t\t\tif verif == \"1\":\n\t\t\t\t\tprint(\"Session ouverte \\n\")\n\t\t\t\t\tverrouille = False\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Mot de passe incorrect\")\n\n\n\t\twhile 1 :\n\t\t\tcmd=input(\"Saisir la commande \")\n\t\t\tl = cmd.split(\" \")\n\t\t\ti = 0\n\t\t\tmaCom = \" \"\n\t\t\twhile i \"7\" :\n\t\t\t\t\t\t\t\tnum = input(\"\\n\\nATTENTION : Quand vous editez un champs vous réecrivez par dessus !\\n\\nQuelle champs voulez vous editer ? (mettre le n°) : \")\n\t\t\t\t\t\t\ts.send(num.encode())\n\t\t\t\t\t\t\tif int(num) >= 3 and int(num) <= 6 :\n\t\t\t\t\t\t\t\tprint(\"Ecrivez ce que vous voulez ecrire dans ce champs : \")\n\t\t\t\t\t\t\t\tedit = PlsrLignes()\n\t\t\t\t\t\t\telse :\n\t\t\t\t\t\t\t\tedit=input(\"Ecrivez ce que vous voulez ecrire dans ce champs : \")\n\t\t\t\t\t\t\ts.send(edit.encode())\n\t\t\t\t\t\t\tprint (\"Voici l'affichage du fichier après edition :\\n\")\n\t\t\t\t\t\t\trep=s.recv(BUFFER_SIZE)\n\t\t\t\t\t\t\tprint (rep.decode())\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tprint (rep)\n\t\t\t\t\t\t\tprint (\"Erreur le fichier \", l[1], \" n'existe pas\\n\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint (rep)\n\n\t\t\telif l[0]==\"creer\" :\n\t\t\t\tif len(l) < 2 :\n\t\t\t\t\tprint (\"Erreur : argument manquant\\nuse : creer nomfichier\")\n\t\t\t\telse :\n\t\t\t\t\ts.send(cmd.encode())\n\t\t\t\t\trep = s.recv(BUFFER_SIZE)\n\t\t\t\t\trep=rep.decode()\n\t\t\t\t\tif DROIT == 'M':\n\t\t\t\t\t\tif rep == \"0\":\n\t\t\t\t\t\t\tecrase = input(\"Un fichier du même nom existe déjà voulez vous l'écraser ? (non:0/oui:1)\\n\")\n\t\t\t\t\t\tif (rep != \"0\") or ecrase==1 :\n\t\t\t\t\t\t\tprint (\"\\nEntrez les informations concernant le patient\\n\")\n\t\t\t\t\t\t\tnom=input(\"Saisir le nom : \")\n\t\t\t\t\t\t\tnom=str(nom)+\" \"\n\t\t\t\t\t\t\ts.send(nom.encode())\n\t\t\t\t\t\t\tprenom=input(\"Saisir le prenom : \")\n\t\t\t\t\t\t\tprenom=str(prenom)+\" \"\n\t\t\t\t\t\t\ts.send(prenom.encode())\n\t\t\t\t\t\t\tage=input(\"Saisir l'age: \")\n\t\t\t\t\t\t\tage=str(age)+\" \"\n\t\t\t\t\t\t\ts.send(age.encode())\n\t\t\t\t\t\t\tprint(\"Saisir ses allergies (§ pour terminer): \")\n\t\t\t\t\t\t\taller=PlsrLignes()\n\t\t\t\t\t\t\ts.send(aller.encode())\n\t\t\t\t\t\t\tprint(\"Saisir ses symptomes (§ pour terminer): \")\n\t\t\t\t\t\t\tsymp= PlsrLignes()\n\t\t\t\t\t\t\ts.send(symp.encode())\n\t\t\t\t\t\t\tprint(\"Saisie du diagnostique (§ pour terminer): \")\n\t\t\t\t\t\t\tdiag=PlsrLignes()\n\t\t\t\t\t\t\ts.send(diag.encode())\n\n\t\t\t\t\t\t\tprint(\"Saisie des commentaires (§ pour terminer): \")\n\t\t\t\t\t\t\tcom = PlsrLignes()\n\t\t\t\t\t\t\ts.send(com.encode())\n\n\t\t\t\t\t\t\thop=input(\"Saisie de la date d'entrée à l'hôpital: \")\n\t\t\t\t\t\t\thop=str(hop)+\" \"\n\t\t\t\t\t\t\ts.send(hop.encode())\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\terr = \"ERREUR\"\n\t\t\t\t\t\t\ts.send(err.encode())\n\t\t\t\t\t\tprint(\"Fin de la saisie\")\n\t\t\t\t\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(rep)\n\t\t\telif l[0]==\"signer\":\n\t\t\t\ts.send(cmd.encode())\n\t\t\t\terreur=\"ERR\"\n\t\t\t\trepDoc=s.recv(BUFFER_SIZE)\n\t\t\t\trepDoc=repDoc.decode()\n\t\t\t\tprint(user)\n\t\t\t\ts.send(user)\n\t\t\t\tprint(\"Vous pouvez signer les documents suivants:\\n\")\n\t\t\t\tprint (repDoc)\n\t\t\t\tdoc=input(\"Quel document voulez vous signer?\\n>>\")\n\t\t\t\tif doc not in repDoc:\n\t\t\t\t\tprint(\"Le document n'existe pas\")\n\t\t\t\t\ts.send(erreur.encode())\n\t\t\t\telse:\n\t\t\t\t\ts.send(doc.encode())\n\n\t\t\telif l[0]==\"help\":\n\t\t\t\tprint(\"Voici les commandes :\\n\")\n\t\t\t\tprint(\"ls :\t\taffiche tous les fichiers du repertoire où vous vous trouvez)\")\n\t\t\t\tprint(\"cat :\t\taffiche le fichier passé en paramètre (use : cat nomFichier)\")\n\t\t\t\tprint(\"rm :\t\tefface le fichier passé en paramètre (use : rm nomFichier)\")\n\t\t\t\tprint(\"mkdir :\t\tcréé un dossier (use : mkdir nomdossier)\")\n\t\t\t\tprint(\"cd :\t\tdéplacement dans le dossier, mettre .. pour revenir au dossier parent (use : cd nomdossier ou cd ..)\")\n\t\t\t\tprint(\"cp:\t\tcopie un fichier dans un dossier (use : cp nomfichier nomdossier)\")\n\t\t\t\tprint(\"creer :\t\tcréé un fichier (use : creer nomfichier)\")\n\t\t\t\tprint(\"edit :\t\tédite un fichier (use : edit nomfichier)\")\n\t\t\t\tprint(\"signer :\tsigne un fichier \")\n\t\t\t\tprint(\"clear :\t\tefface votre page \")\n\t\t\t\tprint(\"historique :\t\taffiche l'historique de vos commandes \")\n\t\t\t\tprint(\"whereis :\t\ttrouve un fichier (use : whereis nomfichier) \")\n\t\t\t\tprint(\"fin:\t\tquitte et revient aux login\")\n\t\t\telif l[0]==\"clear\":\n\t\t\t\tprint (\"\\033[H\\033[2J\")\n\n\t\t\telif l[0]==\"historique\":\n\t\t\t\tprint (historique)\n\n\n\t\t\telif l[0] == \"fin\" :\n\t\t\t\thistorique = \" \"\n\t\t\t\tfin='1'\n\t\t\t\ts.send(fin.encode())\n\t\t\t\tbreak\n\t\t\telse :\n\t\t\t\ts.send(cmd.encode())\n\t\t\t\trep=s.recv(BUFFER_SIZE)\n\t\t\t\tprint (rep.decode())\n\n\n\telif decision==\"admin\":\n\t\tsaisie=\"\"\n\t\tuser=input(\"Utilisateur : \")\n\t\ts.send(user.encode())\n\t\tuser1=s.recv(32).decode()\n\n\t\tif user1 == \"admin\" :\n\t\t\tmdp_admin1=''\n\t\t\twhile mdp_admin1 != 'correct' :\n\t\t\t\tmdp_admin=getpass(\"Entrez votre mot de passe administrateur : \")\n\t\t\t\tmdp_admin = hashlib.sha256(mdp_admin.encode()).hexdigest()\n\t\t\t\ts.send(mdp_admin.encode())\n\t\t\t\tmdp_admin1=s.recv(16).decode()\n\n\t\t\t\tif mdp_admin1=='Faux' :\n\t\t\t\t\tprint(mdp_admin1+\", mauvais mot de passe. Veuillez réessayez.\")\t\t\t\t\n\n\t\t\t\telif mdp_admin1=='correct' :\n\t\t\t\t\tprint(\"Code bon\")\n\t\t\t\t\tprint(\"Vous êtes connecté en tant qu'administrateur.\")\n\t\t\t\t\ttout=True\n\n\t\t\t\telse :\n\t\t\t\t\tprint(\"Veuillez réessayez\")\n\n\t\t\twhile tout :\n\n\t\t\t\tprint(\"Voulez vous :\\n\\t¤ Enregistrer un nouvel utilisateur (signup) ?\\n\\t¤ Modifier la blacklist (blacklist) ?\\n\\t¤ Quitter (fin)?\")\n\t\t\t\tprint(\" \")\n\t\t\t\tchoix = input(\">> \") #signup ou blacklist\n\t\t\t\ts.send(choix.encode())\n\n\t\t\t\tif choix==\"fin\" :\n\t\t\t\t\tchoix1 = s.recv(32).decode()\n\t\t\t\t\tfin = '1' \n\t\t\t\t\ts.send(fin.encode())\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\n\t\t\t\telse :\n\t\t\t\t\tchoix1 = s.recv(32).decode()\n\t\t\t\t\tif choix1 == \"signup1\" : #le serveur montre qu'il suit vers signup\n\t\t\t\t\t\tservice = input(\"Sous quel service voulez vous enregistrer le nouvel utilisateur ? (Medecin, Infirmier, Interne)? \\n >> \")\n\t\t\t\t\t\ts.send(service.encode())\n\n\t\t\t\t\t\tif service == 'Medecin' :\n\t\t\t\t\t\t\tservice1=s.recv(32).decode() \n\n\t\t\t\t\t\t\tif service1 == \"okMed\":\n\t\t\t\t\t\t\t\tsaisie=input(\"Cle Medecin : \")\n\t\t\t\t\t\t\t\ts.send(saisie.encode())\n\n\t\t\t\t\t\t\t\tclé=s.recv(64).decode()\t#vérification que la clé correspond a la clé medecin\n\t\t\t\t\t\t\t\tif clé == \"okCle\":\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinvalide=True\n\t\t\t\t\t\t\t\t\twhile invalide :\n\t\t\t\t\t\t\t\t\t\tnom=input(\"Nom de l'utilisiteur : \")\n\t\t\t\t\t\t\t\t\t\ts.send(nom.encode())\n\t\t\t\t\t\t\t\t\t\toknom=s.recv(16).decode()\n\t\t\t\t\t\t\t\t\t\tif oknom == 'okNom' :\n\t\t\t\t\t\t\t\t\t\t\tinvalide = False\n\t\t\t\t\t\t\t\t\t\telse :\n\t\t\t\t\t\t\t\t\t\t\tprint(\"Ce nom d'utilisateur existe déjà...\")\n\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tmdp = getpass(\"Mot de passe :\")\n\t\t\t\t\t\t\t\t\thash_mdp = hashlib.sha256(mdp.encode()).hexdigest()\n\t\t\t\t\t\t\t\t\ts.send(hash_mdp.encode())\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tprint(clé)\n\t\t\t\t\t\t\t\t\tprint (\"Clé erronée, inscription impossible \\n\")\n\t\t\t\t\t\t\t\n\n\t\t\t\t\t\telif service == 'Infirmier' :\n\t\t\t\t\t\t\tservice1=s.recv(32).decode() \n\n\t\t\t\t\t\t\tif service1 == \"okInf\":\n\t\t\t\t\t\t\t\tsaisie=input(\"Cle Infirmier : \")\n\t\t\t\t\t\t\t\ts.send(saisie.encode())\n\n\t\t\t\t\t\t\t\tclé=s.recv(64).decode()\n\t\t\t\t\t\t\t\tif clé == \"okCle\" :\n\t\t\t\t\t\t\t\t\tprint(clé)\n\n\t\t\t\t\t\t\t\t\tinvalide=True\n\t\t\t\t\t\t\t\t\twhile invalide :\n\t\t\t\t\t\t\t\t\t\tnom=input(\"Nom de l'utilisiteur : \")\n\t\t\t\t\t\t\t\t\t\ts.send(nom.encode())\n\t\t\t\t\t\t\t\t\t\toknom=s.recv(16).decode()\n\t\t\t\t\t\t\t\t\t\tif oknom == 'okNom' :\n\t\t\t\t\t\t\t\t\t\t\tinvalide = False\n\t\t\t\t\t\t\t\t\t\telse :\n\t\t\t\t\t\t\t\t\t\t\tprint(\"Ce nom d'utilisateur existe déjà...\")\n\n\t\t\t\t\t\t\t\t\tmdp = getpass(\"Mot de passe :\")\n\t\t\t\t\t\t\t\t\thash_mdp = hashlib.sha256(mdp.encode()).hexdigest()\n\t\t\t\t\t\t\t\t\ts.send(hash_mdp.encode())\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tprint(clé)\n\t\t\t\t\t\t\t\t\tprint (\"Clé erronée, inscription impossible \\n\")\n\n\t\t\t\t\t\telif service == 'Interne' :\n\t\t\t\t\t\t\tservice1=s.recv(32).decode()\n\n\n\t\t\t\t\t\t\tif service1 == \"okInt\" :\n\t\t\t\t\t\t\t\tsaisie=input(\"Cle Interne : \")\n\t\t\t\t\t\t\t\ts.send(saisie.encode())\n\n\t\t\t\t\t\t\t\tclé=s.recv(64).decode()\n\t\t\t\t\t\t\t\tif clé == \"okCle\" :\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinvalide=True\n\t\t\t\t\t\t\t\t\twhile invalide :\n\t\t\t\t\t\t\t\t\t\tnom=input(\"Nom de l'utilisiteur : \")\n\t\t\t\t\t\t\t\t\t\ts.send(nom.encode())\n\t\t\t\t\t\t\t\t\t\toknom=s.recv(32).decode()\n\t\t\t\t\t\t\t\t\t\tif oknom == 'okNom' :\n\t\t\t\t\t\t\t\t\t\t\tinvalide = False\n\t\t\t\t\t\t\t\t\t\telse :\n\t\t\t\t\t\t\t\t\t\t\tprint(\"Ce nom d'utilisateur existe déjà...\")\n\n\t\t\t\t\t\t\t\t\tmdp = getpass(\"Mot de passe :\")\n\t\t\t\t\t\t\t\t\thash_mdp = hashlib.sha256(mdp.encode()).hexdigest()\n\t\t\t\t\t\t\t\t\ts.send(hash_mdp.encode())\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tprint(clé)\n\t\t\t\t\t\t\t\t\tprint (\"Clé erronée, inscription impossible \\n\")\n\n\t\t\t\t\t\telse :\n\t\t\t\t\t\t\tservice_erreur=s.recv(64).decode()\n\t\t\t\t\t\t\tprint(service_erreur)\n\n\n\t\t\t\t\telif choix1=='blacklist' :\n\t\t\t\t\t\tblack='go'\n\t\t\t\t\t\twhile black=='go' :\n\t\t\t\t\t\t\tnom_blackliste=input(\"Utilisateur blacklisté : \")\n\t\t\t\t\t\t\ts.send(nom_blackliste.encode())\n\t\t\t\t\t\t\ta=s.recv(16).decode()\n\n\t\t\t\t\t\t\tif a=='stop':\n\t\t\t\t\t\t\t\t\tprint(\"Vous avez fini les modifications sur la blacklist\")\n\t\t\t\t\t\t\t\t\tblack='stop'\n\n\t\t\t\t\t\t\telif a == 'oui' :\n\t\t\t\t\t\t\t\tprint(\"Cet utilisateur est dans la blacklist\")\n\t\t\t\t\t\t\t\tprint(\"Pour retirer cet utilisateur de la blacklist taper la commande \\n \\t\\t\")\n\t\t\t\t\t\t\t\tdelet=input(\">> \")\n\t\t\t\t\t\t\t\ts.send(delet.encode())\n\n\t\t\t\t\t\t\t\tok=s.recv(64).decode()\n\t\t\t\t\t\t\t\tif ok=='okDelet':\n\t\t\t\t\t\t\t\t\tprint(\"Vous allez effacer l'utilisateur \"+delet[1]+\" de la blacklist\")\n\t\t\t\t\t\t\t\t\tb='dansDelet'\n\t\t\t\t\t\t\t\t\ts.send(a.encode())\n\t\t\t\t\t\t\t\t\ta=s.recv(64).decode()\n\t\t\t\t\t\t\t\t\tprint(\"L'utilisateur peut de nouveau se connecter, il n'est plus dans la blacklist\")\n\n\t\t\t\t\t\t\t\telif ok=='stop':\n\t\t\t\t\t\t\t\t\tprint(\"Vous avez fini les modifications su la blacklist\")\n\t\t\t\t\t\t\t\t\tblack='stop'\n\n\t\t\t\t\t\t\t\telse :\n\t\t\t\t\t\t\t\t\tprint(ok)\n\n\t\t\t\t\t\t\telif a == 'non' :\n\t\t\t\t\t\t\t\tprint(\"Cet utilisateur n'est pas dans la Blacklist\")\n\n\t\t\t\t\t\t\telse : \n\t\t\t\t\t\t\t\tprint(\"Erreur....\")\n\n\n\n\n\t\t\t\t\telse :\n\t\t\t\t\t\tprint(choix1)\n\n","sub_path":"TraitementTxtFork/clientTxt.py","file_name":"clientTxt.py","file_ext":"py","file_size_in_byte":11795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"157764366","text":"#!/usr/bin/env python3\nfrom typing import Awaitable, Callable\nimport asyncio\nimport binding\nfrom pygments.formatters import HtmlFormatter\nfrom .ui import Ui # NOTE: before justpy\nimport justpy as jp\nfrom .elements.element import Element\nfrom .timer import Timer\n\nwp = jp.QuasarPage(delete_flag=False, title=Ui.config.title, favicon=Ui.config.favicon)\nwp.tailwind = True # use Tailwind classes instead of Quasars\nwp.css = HtmlFormatter().get_style_defs('.codehilite')\nwp.head_html += '\\n' # avoid confirmation dialog for reload\n\nmain = jp.Div(a=wp, classes='q-ma-md column items-start', style='row-gap: 1em')\nmain.add_page(wp)\n\njp.justpy(lambda: wp, start_server=False)\n\nasync def binding_loop():\n while True:\n binding.update()\n await asyncio.sleep(0.1)\n\ndef create_task(coro):\n loop = asyncio.get_event_loop()\n return loop.create_task(coro)\n\ntasks = []\n\n@jp.app.on_event('startup')\ndef startup():\n tasks.extend(create_task(t) for t in Timer.tasks)\n tasks.extend(create_task(t) for t in Ui.startup_tasks if isinstance(t, Awaitable))\n [t() for t in Ui.startup_tasks if isinstance(t, Callable)]\n jp.run_task(binding_loop())\n\n@jp.app.on_event('shutdown')\ndef shutdown():\n [create_task(t) for t in Ui.shutdown_tasks if isinstance(t, Awaitable)]\n [t() for t in Ui.shutdown_tasks if isinstance(t, Callable)]\n [t.cancel() for t in tasks]\n\nElement.wp = wp\nElement.view_stack = [main]\n\napp = jp.app\nui = Ui()\n","sub_path":"nicegui/nicegui.py","file_name":"nicegui.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618308629","text":"import os\nimport json\nfrom SlamUtils.Loader.TartanAir import rootDIR, getDataSequences, getDataLists, tartan_camExtr\n\ndef genFullSequences(path_scr = rootDIR):\n TartanAir_scenarios = os.listdir(path_scr)\n dict_full = {}\n for scene in TartanAir_scenarios:\n if os.path.isdir(os.path.join(path_scr,scene)) == False:\n TartanAir_scenarios.remove(scene)\n\n dict_full.update({'keys': TartanAir_scenarios})\n dict_full.update({'levels': ['Easy', 'Hard']})\n for scene in TartanAir_scenarios:\n _dict_scene = {}\n _path_sce = os.path.join(path_scr,scene)\n levels = os.listdir(_path_sce); levels.sort()\n for lvl in levels:\n _trajs = os.listdir(os.path.join(_path_sce,lvl))\n _trajs.sort()\n _traj_paths = []\n for _traj in _trajs:\n # _path = os.path.join(_path_sce,lvl,_traj,'')\n _traj_paths.append(_traj)\n print(scene, '-', lvl)\n _dict_scene.update({lvl:_traj_paths})\n dict_full.update({scene:_dict_scene})\n # print(dict_full)\n return dict_full\n\nmyDict = genFullSequences()\nwith open(rootDIR + 'tartanair_data.json', 'w') as fp:\n json.dump(myDict, fp)\n\n# with open(rootDIR + 'tartanair_data.json', 'r') as fp:\n# checkDict = json.load(fp)","sub_path":"Benchmark/script_gendata_json.py","file_name":"script_gendata_json.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298728404","text":"from pathlib import Path\nimport homeworks.les01.parse_5ka as p5ka\n\n\"\"\"\nhttps://5ka.ru/special_offers/\n\nЗадача организовать сбор данных, \nнеобходимо иметь метод сохранения данных в .json файлы\nрезультат: Данные скачиваются с источника, при вызове метода/функции сохранения в файл скачанные данные \nсохраняются в Json вайлы, для каждой категории товаров должен быть создан отдельный файл и содержать товары \nисключительно соответсвующие данной категории.\n\nпример структуры данных для файла: \nнейминг ключей можно делать отличным от примера\n\n{\n\"name\": \"имя категории\",\n\"code\": \"Код соответсвующий категории (используется в запросах)\",\n\"products\": [{PRODUCT}, {PRODUCT}........] # список словарей товаров соответсвующих данной категории\n}\n\"\"\"\n\n\n# этот класс сначала считывает все категоии, а потом все продукты в категории\nclass ParseCat5ka(p5ka.Parse5ka):\n # @url_cat - ссылка получения списка категорий\n def __init__(self, url_cat, url_prod, save_path: Path):\n self.url_cat = url_cat\n super().__init__(url_prod, save_path)\n\n def run(self):\n # список каталогов\n response = self._get_response(self.url_cat, headers=self.headers)\n parent_cats = response.json()\n # перебор категорий\n for parent_cat in parent_cats:\n code_group = parent_cat['parent_group_code']\n name_group = parent_cat['parent_group_name']\n file_path = self.save_path.joinpath(f\"{code_group}-{self._clear_name(name_group)}.json\")\n print(parent_cat['parent_group_code'], name_group)\n # инициализация структуры\n cat_content = {\"name\": name_group, \"code\": code_group, \"products\": []}\n # параметр запроса @categories\n self.params['categories'] = code_group\n for product in self._parse(self.star_url):\n cat_content['products'].append(product)\n self._save(cat_content, file_path)\n\n # готовит содержимое строки для именования файла\n def _clear_name(self, name_file):\n clean_str = ''.join(e for e in name_file if e.isalnum())\n return clean_str[:10]\n\n\nif __name__ == \"__main__\":\n save_path = p5ka.get_save_path(\"products\")\n url_cat = \"https://5ka.ru/api/v2/categories/\"\n url_prod = \"https://5ka.ru/api/v2/special_offers/\"\n parser = ParseCat5ka(url_cat, url_prod, save_path)\n parser.run()\n","sub_path":"homeworks/les01/parse_cat_5ka.py","file_name":"parse_cat_5ka.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"423996280","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# From: https://oj.leetcode.com/problems/plus-one/\n# Status: AC\n# Date: Sep. 25, 2014\n\nclass Solution:\n # @param digits, a list of integer digits\n # @return a list of integer digits\n def plusOne(self, digits):\n n = len(digits) - 1\n tmp = 1\n while n > -1:\n val = digits[n] + tmp\n tmp = val // 10\n digits[n] = val % 10\n n -= 1\n res = digits\n if tmp == 1:\n res = [1] + digits\n return res\n","sub_path":"week26/Yao/plus_one.py","file_name":"plus_one.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293066680","text":"from flask import request, jsonify\n\nfrom exceptions.resource_not_found import ResourceNotFound\nfrom models.department import Department\nfrom services.department_service import DepartmentService\n\n\ndef route(app):\n @app.route(\"/departments\", methods=[\"POST\"])\n def post_department():\n try:\n department = Department.json_parse(request.json)\n department = DepartmentService.add_department(department)\n return jsonify(department.json()), 201\n except KeyError:\n return \"A name and department head must be entered to add a department.\", 400\n except ResourceNotFound as r:\n return r.message, 404\n\n @app.route(\"/departments\", methods=[\"GET\"])\n def get_all_departments():\n return jsonify(DepartmentService.get_all_departments())\n\n @app.route(\"/departments/\", methods=[\"GET\"])\n def get_department(department_name):\n try:\n department = DepartmentService.get_department(department_name)\n return jsonify(department.json()), 200\n except ResourceNotFound as r:\n return r.message, 404\n\n @app.route(\"/departments/\", methods=[\"PUT\"])\n def update_department(department_name):\n try:\n department = Department.json_parse(request.json)\n department.department_name = department_name\n DepartmentService.update_department(department)\n return jsonify(department.json()), 200\n except KeyError:\n return \"Please enter a new Department Head for this Department.\", 400\n except ResourceNotFound as r:\n return r.message, 404\n\n @app.route(\"/departments/\", methods=[\"DELETE\"])\n def delete_department(department_name):\n try:\n return DepartmentService.delete_department(department_name)\n except KeyError:\n return f\"No Department with name {department_name} found.\", 400\n","sub_path":"controllers/department_controller.py","file_name":"department_controller.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"584458520","text":"#!/usr/bin/env python3\n# encoding: utf-8\n# @Time : 2017/12/16 下午8:41\n# @Author : yuchangqian\n# @Contact : changqian_yu@163.com\n# @File : BaseDataset.py\n\nimport os\nimport time\nimport json\nimport cv2\nimport torch\nimport pickle as pkl\nimport numpy as np\nfrom PIL import Image\n\nimport torch.utils.data as data\n\nclass DAVIS(data.Dataset):\n def __init__(self, setting, split_name, thre, preprocess=None,\n file_length=None):\n super(DAVIS, self).__init__()\n self._split_name = split_name\n self.data_pairs = self._load_data_file(setting['data_train_source'])\n self._file_length = len(self.data_pairs)\n self.preprocess = preprocess\n\n def __len__(self):\n if self._file_length is not None:\n return self._file_length\n return len(self.data_pairs)\n\n def __getitem__(self, index):\n name = self.data_pairs[index]\n\n ref_img, cur_img, ref_mask, cur_mask = self._fetch_data(name)\n if self.preprocess is not None:\n ref_img, cur_img, cur_mask, extra_dict = self.preprocess(ref_img, cur_img, ref_mask, cur_mask)\n\n if self._split_name == 'train':\n ref_img = torch.from_numpy(np.ascontiguousarray(ref_img)).float()\n cur_img = torch.from_numpy(np.ascontiguousarray(cur_img)).float()\n cur_mask = torch.from_numpy(np.ascontiguousarray(cur_mask)).float()\n\n if self.preprocess is not None and extra_dict is not None:\n for k, v in extra_dict.items():\n extra_dict[k] = torch.from_numpy(np.ascontiguousarray(v))\n if 'label' in k:\n extra_dict[k] = extra_dict[k].float()\n if 'img' in k:\n extra_dict[k] = extra_dict[k].float()\n\n output_dict = dict(ref_img=ref_img, cur_img=cur_img, cur_mask=cur_mask)\n\n if self.preprocess is not None and extra_dict is not None:\n output_dict.update(**extra_dict)\n\n return output_dict\n\n def _fetch_data(self, line):\n ref_img = line.split('\\t')[0]\n cur_img = line.split('\\t')[1]\n\n ref_mask = ref_img.replace('JPEGImages', 'Annotations').replace('jpg', 'png')\n cur_mask = cur_img.replace('JPEGImages', 'Annotations').replace('jpg', 'png')\n\n ref_mask = Image.open(ref_mask)\n ref_mask = np.atleast_3d(ref_mask)[...,0]\n ref_mask = ref_mask.copy()\n ref_mask[ref_mask > 0] = 1\n cur_mask = Image.open(cur_mask)\n cur_mask = np.atleast_3d(cur_mask)[...,0]\n cur_mask = cur_mask.copy()\n cur_mask[cur_mask > 0] = 1\n\n ref_img = cv2.imread(ref_img)[:,:,::-1]\n cur_img = cv2.imread(cur_img)[:,:,::-1]\n\n return ref_img, cur_img, ref_mask, cur_mask\n\n def _load_data_file(self, data_source_path):\n data_file = open(data_source_path, 'r').readlines()\n data_file = [i.strip() for i in data_file]\n return data_file\n\n def get_length(self):\n return self.__len__()\n\n\nif __name__ == \"__main__\":\n data_setting = {'data_train_source': '/home/duy/phd/lucasdu/duy/coco_train2017_refine_training/info.txt'}\n bd = COCO(data_setting, 'train', 0.3)\n","sub_path":"furnace/datasets/davis_rand_sample.py","file_name":"davis_rand_sample.py","file_ext":"py","file_size_in_byte":3189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"280061198","text":"\"\"\"\n@brief test log(time=10s)\n\nYou should indicate a time in seconds. The program ``run_unittests.py``\nwill sort all test files by increasing time and run them.\n\"\"\"\n\n\nimport sys, os, unittest, pandas\n\n\ntry :\n import src\n import pyquickhelper\nexcept ImportError :\n path = os.path.normpath(os.path.abspath( os.path.join( os.path.split(__file__)[0], \"..\", \"..\")))\n if path not in sys.path : sys.path.append (path)\n path = os.path.normpath(os.path.abspath( os.path.join( os.path.split(__file__)[0], \"..\", \"..\", \"..\", \"pyquickhelper\", \"src\")))\n if path not in sys.path : sys.path.append (path)\n import src\n import pyquickhelper\n\nfrom pyquickhelper import fLOG\nfrom src.pyensae.sql.database_main import Database\n\n\nclass TestDatabaseDF (unittest.TestCase):\n \n def test_import_df(self) :\n fLOG (__file__, self._testMethodName, OutputPrint = __name__ == \"__main__\")\n dbf = os.path.join(os.path.abspath(os.path.split(__file__)[0]), \"temp_database_df.db3\")\n if os.path.exists(dbf): os.remove(dbf)\n \n values = [ {\"name\":\"A\", \"age\":10, \"score\":34.5 },\n {\"name\":\"B\", \"age\":20, \"score\":-34.5 }, ]\n df = pandas.DataFrame(values)\n db = Database.fill_sql_table(df, dbf, \"newtable\")\n vie = db.execute_view(\"SELECT * FROM newtable\")\n df2 = db.to_df( \"SELECT * FROM newtable\")\n df3 = df2[[\"age\",\"name\",\"score\"]]\n assert len(df)>0\n assert len(df3)==len(df)\n for a,b in zip(df.values, df3.values):\n assert len(a)>0\n assert len(a) == len(b)\n for c,d in zip(a,b):\n assert c == d\n db.close()\n\nif __name__ == \"__main__\" :\n unittest.main () \n","sub_path":"_unittests/ut_sql/test_database_df.py","file_name":"test_database_df.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"303149514","text":"from requests import Session\nfrom bs4 import BeautifulSoup as bs\nfrom selenium import webdriver\nimport json\nimport re\n\nwith open('omegafilogininfo.json') as file:\n login_data_raw = json.load(file)\n login_data = {}\n for key, value in login_data_raw.items():\n login_data[key.encode(\"utf-8\")] = value.encode(\"utf-8\")\n file.close()\n\nwith Session() as s:\n site = s.get(\"https://login.omegafi.com/users/sign_in\")\n bs_content = bs(site.content, \"html.parser\")\n token = bs_content.find(\"input\", {\"name\":\"authenticity_token\"})[\"value\"]\n lt = bs_content.find(\"input\", {\"name\":\"lt\"})[\"value\"]\n login_data['authenticity_token'] = token.encode(\"utf-8\")\n login_data['lt'] = lt.encode(\"utf-8\")\n s.post(\"https://login.omegafi.com/cas/login\",login_data)\n site = s.get('https://my.omegafi.com/apps/myomegafi/ajax/portlets/memberroster.php?viewstate=tDMposC690cqv3NGJxzyPhpk73RgpPMYV_sGVbVjo0Q!')\n members_content = bs(site.content, \"html.parser\")\n file = open('sitecontent.txt','w+')\n for member in members_content.find_all(\"tr\", {\"class\":\"memberdetail\"}):\n regex_search = re.search('([a-zA-Z\\s]+)<\\/td>([a-zA-Z\\s]+)<\\/td>', str(member))\n if str(regex_search) != 'None':\n file.write(regex_search.group(1) + \" \" + regex_search.group(2) + \"\\n\")\n file.close()\n","sub_path":"omegafilogin.py","file_name":"omegafilogin.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"202961206","text":"import numpy as np\nimport matplotlib.pyplot as plt\nplt.rc('font', family='Times New Roman')\n\nlen_plot = 2000\nnum_trial = 1\nn_feature = 2048\nf_focus = np.load('f_focus_{}.npy'.format(n_feature))\n\nfontsize = 15\n\nhorizons = [50, 100, 200, 500, 2000]\nsteps = []\nws = []\n\nfor h in horizons:\n acc_steps = np.zeros(len_plot)\n acc_w = np.zeros((len_plot, n_feature))\n for trial in range(0, num_trial):\n acc = np.load('layer_5/accurate_random_reward^1_decay_replace^0_trial_'\n '{}_alpha_decay_gamma_1_horizon_{}_epsilonMin_0.01.npz'.format(trial, h))\n acc_steps += acc['step']\n acc_w += acc['w']\n acc_steps = acc_steps / num_trial\n acc_w = acc_w / num_trial\n steps.append(acc_steps)\n ws.append(acc_w)\n\nfig = plt.figure(figsize=(15,5))\nax1 = fig.add_subplot(121)\nfig.suptitle('Mountain Car', fontsize=fontsize)\nplt.xticks(fontsize=fontsize)\nplt.yticks(fontsize=fontsize)\n# plot step\nplt.xlabel('Episode', fontsize=fontsize)\nplt.ylabel('Steps', fontsize=fontsize)\nfor i, step in enumerate(steps):\n # ax1.plot(steps[algorithm], label='accurate')\n # ax1.plot(range(0, len(steps[algorithm]), 10),\n # [np.mean(steps[algorithm][i: i + 10]) for i in range(0, len(steps[algorithm]), 10)])\n ax1.plot([np.mean(step[0: i]) for i in range(1, len(step))], label='{}'.format(horizons[i]))\n# plt.legend(fontsize=fontsize)\nplt.grid()\n# plt.show()\n\n# plot q values for features we focus\nax2 = fig.add_subplot(122)\nplt.xticks(fontsize=fontsize)\nplt.yticks(fontsize=fontsize)\nplt.xlabel('Episode', fontsize=fontsize)\nplt.ylabel('Tnitial maximum Q value', fontsize=fontsize)\nfor i, w in enumerate(ws):\n q = [max(np.dot(f_focus, e)) for e in w]\n # ax2.plot(q, label='{}'.format(horizons[i]))\n ax2.plot([np.mean(q[0: i]) for i in range(1, len(q))], label='{}'.format(horizons[i]))\nax2.legend(fontsize=fontsize)\nplt.grid()\nplt.savefig('results/horizon_M')\nplt.show()\n\n\n\n\n","sub_path":"mountaincar/horizon_plot.py","file_name":"horizon_plot.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"112533941","text":"import argparse\nimport os\nfrom shutil import copy\n\nimport numpy as np\nimport torch\nfrom torch import nn, optim\nfrom torch.utils.data.dataloader import DataLoader\n\nfrom pytorch_gans.config.ConfigParams import ConfigParams\nfrom pytorch_gans.data.Preprocessing import Preprocessing\nfrom pytorch_gans.data.StandardDataset import StandardDataset\nfrom pytorch_gans.model.ModelsFactory import ModelsFactory\nfrom pytorch_gans.utils.draw import save_generated_images\n\n\ndef do_parsing():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"--dataset_dir\", required=True, type=str, help=\"Dataset directory\")\n parser.add_argument(\"--config_file\", required=True, type=str, help=\"Config file path\")\n parser.add_argument(\"--model_output_dir\", required=True, type=str,\n help=\"Directory where to save G and D models\")\n parser.add_argument(\"--single_dir_dataset\", action=\"store_true\", help=\"If dataset not includes classes subdirs\")\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = do_parsing()\n print(args)\n\n # Load config file with model, hyperparameters and preprocessing\n config = ConfigParams(args.config_file)\n\n # Prepare preprocessing transform pipeline\n preprocessing_transforms = Preprocessing(config)\n preprocessing_transforms_train = preprocessing_transforms.get_transforms_train()\n\n # Read Dataset\n assert os.path.exists(args.dataset_dir), f\"Dataset dir {args.dataset_dir} does not exists\"\n classes = sorted(next(os.walk(args.dataset_dir))[1])\n print(f\"Classes: {classes}\")\n dataset = StandardDataset(args.dataset_dir, preprocessing_transforms_train)\n print(\"Dataset - Classes: {0}, Samples: {1}\".format(str(len(dataset.get_classes())), str(len(dataset))))\n\n # Load model and apply .train() and .cuda()\n # TODO: Try different ways to attach class indexes\n G, D = ModelsFactory.create(config, len(dataset.get_classes()))\n device = torch.device(\"cuda:0\")\n print(G)\n print(D)\n G.cuda()\n G.train()\n D.cuda()\n D.train()\n\n results_dir = os.path.join(args.model_output_dir, \"results\")\n os.makedirs(results_dir, exist_ok=True)\n os.makedirs(os.path.join(args.model_output_dir, \"chkpt\"), exist_ok=True)\n copy(args.config_file, os.path.join(args.model_output_dir, os.path.basename(args.config_file)))\n\n # Create a PyTorch DataLoader from CatDogDataset (two of them: train + val)\n train_loader = DataLoader(dataset, batch_size=config.batch_size, shuffle=True, num_workers=8)\n validation_inputs_z = torch.randn(config.batch_size, config.zdim).to(device)\n # Create class input replicating labels if len(classes) < config.batch_size, otherwise truncate them\n full_class_indexes = np.array(range(0, len(classes)))\n full_class_indexes_rep = np.tile(full_class_indexes, (config.batch_size // len(full_class_indexes) + 1))[:config.batch_size]\n validation_inputs_classes = torch.from_numpy(full_class_indexes_rep).to(device)\n\n criterion = nn.BCELoss()\n optimizer_G = optim.Adam(G.parameters(), lr=config.learning_rate, betas=(config.beta1, 0.999))\n optimizer_D = optim.Adam(D.parameters(), lr=config.learning_rate, betas=(config.beta1, 0.999))\n\n for epoch in range(config.epochs):\n\n G.train()\n running_d_loss = 0.0\n running_d_real_loss = 0.0\n running_d_fake_loss = 0.0\n running_g_loss = 0.0\n\n # Iterate on train batches and update weights using loss\n for batch_i, data in enumerate(train_loader):\n\n # Batch of generator images\n latents = torch.randn(len(data[\"image\"]), config.zdim).to(device)\n # Generate random class indices\n class_indexes = torch.randint(low=0, high=len(classes), size=(len(data[\"image\"]),)).to(device)\n g_out = G(latents, class_indexes)\n\n ############ Discriminator update over real images\n\n # Discriminator prediction over real images with the correct class\n d_out_real = D(data[\"image\"].to(device), data[\"gt\"].to(device))\n\n # zero the parameter (weight) gradients for discriminator\n D.zero_grad()\n\n # calculate the loss between predicted and target class\n d_real_loss = criterion(d_out_real, torch.ones(size=(len(data[\"image\"]), 1)).to(device))\n\n # backward pass to calculate the weight gradients\n d_real_loss.backward()\n\n # update D weights\n optimizer_D.step()\n\n ############ Discriminator update over fake images\n\n # Discriminator prediction over fake images (detaching generator to avoid gradients propagation)\n d_out_fake = D(g_out.detach(), class_indexes)\n\n # calculate the loss between predicted and target class\n d_fake_loss = criterion(d_out_fake, torch.zeros(size=(len(data[\"image\"]), 1)).to(device))\n\n # backward pass to calculate the weight gradients\n d_fake_loss.backward()\n\n # update D weights\n optimizer_D.step()\n\n ############ Generator update\n\n # zero the parameter (weight) gradients for generator\n G.zero_grad()\n\n # Discriminator over fake images another time keeping generator for gradients\n d_out_fake_with_G = D(g_out, class_indexes)\n\n # Calculate generator loss and gradients, we want discriminator output 1 for fake images\n g_loss = criterion(d_out_fake_with_G, torch.ones(size=(len(data[\"image\"]), 1)).to(device))\n\n # backward pass to calculate the weight gradients\n g_loss.backward()\n\n # update G weights\n optimizer_G.step()\n\n ############ print loss statistics and output generated images\n\n running_d_loss += running_d_real_loss * 0.5 + running_d_fake_loss * 0.5\n running_d_real_loss += d_real_loss.item()\n running_d_fake_loss += d_fake_loss.item()\n running_g_loss += g_loss.item()\n if batch_i % 10 == 9: # print every 10 batches\n print(f\"Epoch: {epoch + 1}, \"\n f\"Batch: {batch_i + 1}, \"\n f\"D Avg. Loss: {running_d_loss / 10}, \"\n f\"D Avg Real Loss {running_d_real_loss / 10}, \"\n f\"D Avg Fake Loss {running_d_fake_loss / 10}, \"\n f\"G Avg Loss {running_g_loss / 10}\")\n running_d_loss = 0.0\n running_d_real_loss = 0.0\n running_d_fake_loss = 0.0\n running_g_loss = 0.0\n\n # eval() to disable BN train mode\n if (epoch + 1) % 5 == 0:\n G.eval()\n # Save images generated at the end of the epoch, validation like\n gen_images_t = G(validation_inputs_z, validation_inputs_classes)\n gen_images = gen_images_t.cpu().data.numpy()\n save_generated_images(gen_images, epoch, results_dir)\n\n # Save model\n # TODO: Save architecture log\n G.eval()\n torch.save(G.state_dict(), os.path.join(args.model_output_dir, \"chkpt\", f\"G_{epoch + 1}.pth\"))\n torch.save(D.state_dict(), os.path.join(args.model_output_dir, \"chkpt\", f\"D_{epoch + 1}.pth\"))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pytorch_gans/train_cdcgan.py","file_name":"train_cdcgan.py","file_ext":"py","file_size_in_byte":7327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216492567","text":"import speech_recognition as sr\nimport tkinter as tk\nimport time\nimport json\nfrom newsapi import NewsApiClient\nimport threading\n\nr = sr.Recognizer()\nstt_text = None\nnotepad = []\n\ncur_month = time.strftime(\"%B\") + \" \" + time.strftime(\"%Y\")\n\ndays_str = [\"Lundi\", \"Mardi\", \"Mercredi\", \"Jeudi\", \"Vendredi\", \"Samedi\", \"Dimanche\"]\ndays_lbl = []\n\nclass MainApp(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n\n container = tk.Frame(self)\n container.place(anchor = tk.NW, relx = 0, rely = 0, relwidth = 1, relheight = 1)\n \n self.frames = {}\n\n frame = Newspaper(container, self)\n self.frames[Newspaper] = frame\n frame.place(anchor = tk.NW, relx = 0, rely = 0, relwidth = 1, relheight = 1)\n\n self.show_frame(Newspaper)\n\n def show_frame(self, toshow):\n tmp_frame = self.frames[toshow]\n tmp_frame.tkraise()\n\nclass Newspaper(tk.Frame):\n def __init__(self, container, master):\n tk.Frame.__init__(self, container) \n\n # Declare the newsapi obj\n self.newsapi = NewsApiClient(api_key='56146cd9ec894d63975bdfce0bb8faeb')\n \n # Declare all the main categories available\n self.cate = {\"économie\" : \"business\",\n \"divertissement\" : \"entertainment\",\n \"santé\" : \"health\",\n \"science\" : \"science\",\n \"sport\" : \"sports\",\n \"technologie\" : \"technology\"}\n self.country = {\"france\" : \"fr\",\n \"états-unis\" : \"us\",\n \"angleterre\" : \"gb\"}\n \n # Get from the file all the subcategories defined by the user\n sub_cate_f = open(\"sub_cate.json\",\"r\")\n self.sub_cate = json.load(sub_cate_f)\n\n # First button to show\n self.btn0 = tk.Button(self, text = \"RECORD\", fg = \"blue\", command = lambda arg=self.make_req : google_stt(arg))\n self.btn0.place(anchor = tk.S, relx = 0.5, rely = 1, relwidth = 0.5, relheight = 0.1)\n\n def make_req(self, ctry, cat):\n top = self.newsapi.get_top_headlines(country=self.country[ctry], category=self.cate[cat])\n \n print(top)\n\ndef google_stt(make_req_f):\n # Local vars used after\n country = \"\"\n category = \"\"\n\n # obtain audio from the microphone\n with sr.Microphone() as source:\n audio = r.listen(source)\n\n try:\n tmp_result = r.recognize_google(audio, language = \"fr-FR\")\n tmp_result = tmp_result.lower()\n# if \"calendrier ajoute\" in tmp_result:\n# if len(tmp_result[17:]) > 1:\n# notepad.append(tmp_result[18:])\n# stt_text = \"Ajouté !\"\n# else:\n# stt_text = \"Rien a faire...\"\n\n# elif \"calendrier liste\" in tmp_result:\n# tmp_str = \"\"\n# for i in notepad:\n# tmp_str = tmp_str + i + \"\\r\\n\"\n# stt_text = tmp_str\n \n if \"journal affiche\" in tmp_result:\n if \"france\" in tmp_result:\n if \"catégorie\" in tmp_result:\n make_req_f(\"france\", tmp_result[33:])\n \n else:\n stt_text = tmp_result\n\n except Exception as e:\n print(e)\n \n\napp = MainApp()\n\napp.mainloop()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"167292509","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 20 15:12:33 2020.\n\n@author: laura\n\"\"\"\n\n# GOAL 1\n\"\"\"The tiles are arranged into rows that are all the same width;\nyou take note of the safe tiles (.) and traps (^) in the first row\n(your puzzle input). The type of tile (trapped or safe) in each row is based on\nthe types of the tiles in the same position, and to either side of that\nposition, in the previous row. (If either side is off either end of the row,\n it counts as \"safe\" because there isn't a trap embedded in the wall.)\n\n Let's call these three tiles from the previous row the left, center,\n and right tiles, respectively. Then, a new tile is a trap only in one of\n the following situations:\n\n- Its left and center tiles are traps, but its right tile is not.\n- Its center and right tiles are traps, but its left tile is not.\n- Only its left tile is a trap.\n- Only its right tile is a trap.\n\nIn any other situation, the new tile is safe.\n\nStarting with the map in your puzzle input,\nin a total of 40 rows (including the starting row),\nhow many safe tiles are there?\"\"\"\n\n# DATA\ndata = \"\"\".^^^.^.^^^^^..^^^..^..^..^^..^.^.^.^^.^^....^.^...^.^^.^^.^^..^^..^.^..^^^.^^...^...^^....^^.^^^^^^^\"\"\"\n\ndata = list(data)\n\n\n# ANSWER 1\ntotal = []\ntotal.append(data)\n\n\ndef find_new_row(prev_row):\n \"\"\"Determines the values in the next row.\"\"\"\n new_row = []\n for i, j in enumerate(prev_row):\n if i == 0:\n left = \".\"\n else:\n left = prev_row[i - 1]\n\n center = j\n\n if i == 99:\n right = \".\"\n else:\n right = prev_row[i + 1]\n\n if right == \".\" and center == \".\" and left == \"^\":\n val = \"^\"\n elif right == \"^\" and center == \".\" and left == \".\":\n val = \"^\"\n elif right == \"^\" and center == \"^\" and left == \".\":\n val = \"^\"\n elif right == \".\" and center == \"^\" and left == \"^\":\n val = \"^\"\n else:\n val = \".\"\n\n new_row.append(val)\n\n return new_row\n\nfor i in range(39):\n data = find_new_row(data)\n total.append(data)\n\nflat_list = [item for sublist in total for item in sublist]\nprint(f\"The room contains {flat_list.count('.')} safe tiles\")\n\n# GOAL 2\n\"\"\"How many safe tiles are there in a total of 400000 rows?\"\"\"\n\n# ANSWER 2:\ndata = \"\"\".^^^.^.^^^^^..^^^..^..^..^^..^.^.^.^^.^^....^.^...^.^^.^^.^^..^^..^.^..^^^.^^...^...^^....^^.^^^^^^^\"\"\"\ndata = list(data)\ntotal = []\ntotal.append(data)\n\nfor i in range(400000-1):\n data = find_new_row(data)\n total.append(data)\n\nflat_list = [item for sublist in total for item in sublist]\nprint(f\"The larger room contains {flat_list.count('.')} safe tiles\")\n","sub_path":"Day18.py","file_name":"Day18.py","file_ext":"py","file_size_in_byte":2668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"272517302","text":"# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, HttpRequest, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.template import *\nfrom django.db.models import Q\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom plus.utils.path import *\n\nfrom wiki.models import *\nfrom wiki.forms import ArticleForm, CommentForm\n\n@login_required\ndef add_comment(request, template):\n if request.method == 'POST':\n article_id = request.POST['article'];\n try :\n f = CommentForm(POST_DATA=request.POST)\n if f.is_valid():\n f.save();\n except :\n raise Http404(\"save Comment error\")\n\n return redir_next_page(request);\n\n else :\n raise Http404(\"No post Comment data\")\n\n@login_required\ndef change_comment_status(request, comment_id, top = None, hidden = None):\n if request.method == 'GET':\n try :\n comment = Comment.objects.get(id = comment_id)\n if hidden is not None:\n comment.hidden = hidden;\n if top is not None:\n comment.top = top;\n comment.save();\n except :\n raise Http404(\"change Comment error\")\n\n return redir_next_page(request);\n\n else :\n raise Http404(\"No post Comment data\")\n\n@login_required\n@csrf_exempt\ndef edit_comment(request, comment_id, template):\n data={}\n if request.method == 'GET':\n raise Http404(\"No get Comment data\")\n else:\n try :\n comment = Comment.objects.get(id = comment_id)\n comment.content = request.POST['content']\n comment.save()\n except :\n raise Http404(\"change Comment error\")\n\n data.update({'comment': comment})\n data.update(gen_next_page_item(request, request.path))\n return render(request, template,data, RequestContext(request))\n","sub_path":"wiki/views/edit_comment.py","file_name":"edit_comment.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"254263140","text":"# -*- coding: UTF-8 -*-\n\"\"\"\nProcess the category information in ./Config/category.json\n\"\"\"\nimport json\nimport os\n\n\nclass Category:\n \"\"\"\n Manage deal categories: add, delete, show\n \"\"\"\n def __init__(self):\n \"\"\"\n Initialization of class.\n category_list = [\n {\"id\": 1, \"Chinese name\": \"\"},\n ......\n ]\n Note: category id starts from 0.\n \"\"\"\n if os.path.isfile('./Config/category.json'):\n self.category_list = json.load(open('./Config/category.json', 'r'))\n else:\n print(\" Error: Cannot find category.json.\")\n self.category_list = []\n\n def delete_category(self, category_id):\n \"\"\"\n Delete a specified category from category.json\n :param category_id: id of the category to be deleted\n :return:\n \"\"\"\n for idx, category in enumerate(self.category_list):\n if category['id'] == category_id:\n print(\"You are deleting \", category[\"Chinese name\"])\n while True:\n choice = input(\"Are you sure to delete this deal category? (y/n)\")\n if choice == 'y':\n deleted_category = self.category_list.pop(idx)\n json.dump(self.category_list, open('./Config/category.json', 'w'))\n print(\"Category has been deleted: \", deleted_category)\n break\n elif choice == 'n':\n break\n else:\n print(\"Wrong input. Please enter 'y' or 'n'.\")\n break\n\n def add_category(self, category_Chinese_name, category_description):\n \"\"\"\n Add a category in category.json.\n Note: new category id is one bigger than the last existed category.\n :param category_Chinese_name: Chinese_name of the category\n :param category_description: Description of the category\n :return:\n \"\"\"\n if len(self.category_list) == 0:\n new_category = {\n \"id\": 0,\n \"Chinese name\": category_Chinese_name,\n \"Description\": category_description\n }\n else:\n new_category = {\n \"id\": self.category_list[-1]['id'] + 1,\n \"Chinese name\": category_Chinese_name,\n \"Description\": category_description\n }\n print(\"You are adding a new category: \", new_category)\n while True:\n choice = input(\"Are you sure to add this deal category? (y/n)\")\n if choice == 'y':\n self.category_list.append(new_category)\n json.dump(self.category_list, open('./Config/category.json', 'w'))\n print(\"New category has been saved: \", new_category)\n break\n elif choice == 'n':\n break\n else:\n print(\"Wrong input. Please enter your choice with 'y' or 'n'.\")\n\n def show_category(self):\n \"\"\"\n Print category\n :return:\n \"\"\"\n for _, category in enumerate(self.category_list):\n print(\"ID: {}\\nName: {}\\nDescription: {}\".format(category['id'], category['Chinese name'], category['Description']))\n\n def get_categories(self):\n return self.category_list\n\n\n\nif __name__ == \"__main__\":\n category_manager = Category()\n category_manager.add_category(\"工作餐\", \"只包含工作餐\")\n category_manager.add_category(\"购物\", \"网购,买菜,零食,水果\")\n category_manager.add_category(\"娱乐\", \"看电影,KTV,音视频会员充值\")\n category_manager.add_category(\"交通&车辆\", \"打车,停车,加油,保养,维修\")\n category_manager.add_category(\"家庭\", \"外出就餐,办护照,山姆续费\")\n category_manager.add_category(\"育儿\", \"玩具,奶粉,尿不湿,儿童乐园,幼儿园\")\n category_manager.add_category(\"工作\", \"党费,团建,办公用品,出差\")\n category_manager.add_category(\"人情往来\", \"请吃饭,随礼\")\n category_manager.add_category(\"水电煤网\", \"水费,电费,煤气费,手机费,网费\")\n category_manager.add_category(\"房产\", \"物业费,车位费,修理费\")\n category_manager.add_category(\"医疗\", \"医疗费用\")\n # category_manager.show_category()","sub_path":"deal_category.py","file_name":"deal_category.py","file_ext":"py","file_size_in_byte":4405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"632357404","text":"# Given a sorted array arr containing n elements with possibly\n# duplicate elements, the task is to find indexes of first and last\n# occurrences of an element x in the given array.\nvalues = list(map(int, input().split()))\nelement = int(input())\nstart = 0\nend = len(values) - 1\nstart_pos = -1\nend_pos = -1\nwhile(start < end):\n if values[start] == element:\n if start_pos == -1:\n start_pos = start\n else:\n end_pos = start\n start += 1\n elif values[end] == element:\n if end_pos == -1:\n end_pos = end\n else:\n start_pos = end\n end -= 1\n else:\n if start_pos != -1 and end_pos != -1:\n break\n elif start_pos != -1 and end_pos == -1:\n end_pos = start_pos\n elif end_pos != -1 and start_pos == -1:\n start_pos = end_pos\n elif element > values[start]:\n start += 1\n else:\n end -= 1\nprint(\"Starting position : \", start_pos)\nprint(\"Ending position : \", end_pos)\n \n \n","sub_path":"first_last_position_of_element.py","file_name":"first_last_position_of_element.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89421614","text":"import os\r\nimport shelve\r\nfrom tokenizator_generator_krupina import Tokenizer\r\n\r\nclass Position(object):\r\n def __init__(self, beginning, end):\r\n self.beginning = beginning\r\n self.end = end\r\n def __eq__(self, obj):\r\n return (self.beginning == obj.beginning and self.end == obj.end)\r\n def __repr__(self):\r\n return '(' + str(self.beginning) + ',' + ' ' + str(self.end) + ')'\r\n\r\nclass Position_with_lines(object):\r\n def __init__(self, beginning, end, line):\r\n self.beginning = beginning\r\n self.end = end\r\n self.line = line\r\n def __eq__(self,obj):\r\n return (self.beginning == obj.beginning and self.end == obj.end and\r\n self.line == obj.line)\r\n def __repr__(self):\r\n return '(' + str(self.beginning) + ',' + ' ' + str(self.end) + \\\r\n ',' + ' ' + str(self.line) + ')'\r\n\r\nclass Indexer(object):\r\n def __init__(self, database_name):\r\n self.database = shelve.open(database_name, writeback=True)\r\n\r\n def indexing(self, filename):\r\n tokenizer = Tokenizer()\r\n if not isinstance(filename, str):\r\n raise ValueError\r\n try:\r\n file = open(filename)\r\n except IOError:\r\n raise FileNotFoundError\r\n for token in tokenizer.generate_alpha_and_digits(file.read()):\r\n #for token in tokenizer.generator_with_types(file.read()):\r\n i = token.position + len(token.word)\r\n self.database.setdefault(token.word, {}).setdefault(filename, []).append(\r\n Position(token.position, i)\r\n )\r\n file.close()\r\n self.database.sync()\r\n self.database.close()\r\n\r\n def indexing_with_lines(self, filename):\r\n \r\n tokenizer = Tokenizer()\r\n \r\n if not isinstance(filename, str):\r\n raise ValueError\r\n try:\r\n file = open(filename)\r\n except IOError:\r\n raise FileNotFoundError\r\n for linenumber, line in enumerate(file):\r\n for token in tokenizer.generator_with_types(line):\r\n i = token.position + len(token.word)\r\n self.database.setdefault(token.word, {}).setdefault(filename, []).append(\r\n Position_with_lines(token.position, i, linenumber)\r\n )\r\n file.close()\r\n self.database.sync()\r\n self.database.close()\r\n\r\n def __del__(self):\r\n self.database.close()\r\n\r\ndef main():\r\n indexator = Indexer('database')\r\n file = open('text.txt', 'w')\r\n file.write('this is my testing ground')\r\n file.close()\r\n indexator.indexing('text.txt')\r\n del indexator\r\n os.remove('text.txt')\r\n print(dict(shelve.open('database')))\r\n for filename in os.listdir(os.getcwd()): \r\n if filename == 'database' or filename.startswith('database.'):\r\n os.remove(filename) \r\n\r\n\r\nif __name__=='__main__':\r\n main()\r\n","sub_path":"indexer.py","file_name":"indexer.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"156857207","text":"# coding:utf-8\n# @author : csl\n# @date : 2018/05/24 09:47\n# 链接BU接口\n\nfrom common.base import buApiBase\nimport requests\nimport copy\nfrom common.writelog import writelog\nimport time\n\nclass request2buApi(object):\n\n def __init__(self, service, secdata):\n\n self.service = service\n # self.url = \"http://192.168.8.21:6880/tasker\" # 内网开发环境\n self.url = \"http://192.168.8.18:6880\" # 新自测环境\n # self.url = \"http://192.168.8.35:6880\" # 新集成环境\n # self.url = \"http://tubc.jinvovo.com\" # 新集成环境\n # self.url = \"http://192.168.8.41:6880/tasker\" # 新集成环境\n # self.url = \"http://192.168.2.54:9999\" # 远江本机\n\n\n # 公共参数\n self.pubdata = {\n # \"terraceId\":\"*******************************\", # i生活\n # \"terraceId\":\"*******************************\", # 币航\n \"terraceId\": \"*******************************\", # 长青\n # \"secret\":\"*******************************\", # i生活\n # \"secret\":\"*******************************\", # 币航\n \"secret\": \"*******************************\", # 长青\n \"signType\":\"MD5\",\n \"version\":\"v1.0\",\n \"device\":\"ANDROID\"\n }\n # 添加私有参数\n for k,v in secdata.items():\n self.pubdata[k] = v\n\n self.datastr = buApiBase().data2str(self.pubdata)\n # print(self.datastr)\n self.cpdatastr = copy.deepcopy(self.pubdata) #深度拷贝合并后的参数字典\n del self.cpdatastr[\"secret\"] #删除secret\n self.senddata = buApiBase().data2str(self.cpdatastr) + \"&\" + \"sign\" + \"=\" + buApiBase().getSign(self.datastr)\n # print(self.senddata)\n\n def send(self):\n self.geturl = self.url + self.service + \"?\" + self.senddata\n print(self.geturl)\n writelog(\"info\", \"请求地址--%s\" % str(self.geturl))\n beforetime = time.time()\n req = requests.get(self.geturl)\n aftertime = time.time()\n reqtime = str(round((aftertime - beforetime) * 1000, 3))\n writelog(\"info\", \"请求耗用时长--%s ms 返回数据--%s\" % (str(reqtime), str(req.text)))\n return reqtime, req.status_code, req.text, self.service, time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(beforetime))\n\n\n","sub_path":"common/request2buApi.py","file_name":"request2buApi.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"68949940","text":"from rest_framework.permissions import BasePermission\nimport hmac\nfrom hashlib import sha256\nimport hashlib\nfrom backend.settings import GIT_REAL_WEBHOOK_SECRET\n\n\nclass IsWebhookSignatureOk(BasePermission):\n \"\"\"\n see https://docs.github.com/en/developers/webhooks-and-events/securing-your-webhooks\n Code based on https://github.com/bloomberg/python-github-webhook/blob/master/github_webhook/webhook.py\n \"\"\"\n\n def has_permission(self, request, view):\n body = request._request.body\n recieved_digest = request.headers.get(\"X-Hub-Signature\")\n if not recieved_digest:\n return False\n digest = hmac.new(\n str.encode(GIT_REAL_WEBHOOK_SECRET, \"utf-8\"), body, hashlib.sha1\n ).hexdigest()\n correct = recieved_digest == \"sha1=\" + digest\n if not correct:\n breakpoint()\n\n return correct","sub_path":"backend/git_real/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"180584878","text":"import numpy as np\r\nimport h5py\r\nimport os\r\n#最远点采样\r\ndef farthest_point_sample(xyz, npoint):\r\n N, C = xyz.shape\r\n centroids = np.zeros(npoint)\r\n distance = np.ones(N) * 1e10\r\n farthest = np.random.randint(0, N)# random select one as centroid\r\n for i in range(npoint):\r\n centroids[i] = farthest\r\n centroid = xyz[farthest, :].reshape(1, 3)\r\n dist = np.sum((xyz - centroid) ** 2, -1)\r\n mask = dist < distance\r\n distance[mask] = dist[mask]\r\n farthest = np.argmax(distance)# select the farthest one as centroid\r\n #print('index:%d, dis:%.3f'%(farthest,np.max(distance)))\r\n return centroids\r\n#读取off文件\r\ndef read_off(filename):\r\n npoints=2048\r\n f = open(filename)\r\n f.readline() # ignore the 'OFF' at the first line\r\n f.readline() # ignore the second line\r\n All_points = []\r\n selected_points = []\r\n while True:\r\n new_line = f.readline()\r\n x = new_line.split(' ')\r\n if x[0] != '3':\r\n A = np.array(x[0:3], dtype='float32')\r\n All_points.append(A)\r\n else:\r\n break\r\n # if the numbers of points are less than 2000, extent the point set\r\n if len(All_points) < (npoints + 3):\r\n print(\"none\")\r\n return None\r\n All_points = np.array(All_points)\r\n # take and shuffle points\r\n # index = np.random.choice(len(All_points), num_select, replace=False)\r\n xyz = All_points.copy()\r\n points_farthest_index = farthest_point_sample(xyz, npoints).astype(np.int64)\r\n points_farthest = xyz[points_farthest_index, :]\r\n centroid = np.mean(points_farthest, axis=0)\r\n points_unit_sphere = points_farthest - centroid\r\n furthest_distance = np.max(np.sqrt(np.sum(abs(points_farthest) ** 2, axis=-1)))\r\n points_unit_sphere /= furthest_distance\r\n return list(points_unit_sphere) # return N*3 array的list\r\n#保存h5\r\ndef save_h5(h5_filename, data, label, data_dtype='float32', label_dtype='float32'):\r\n h5_fout = h5py.File(h5_filename)\r\n h5_fout.create_dataset(\r\n 'data', data=data,\r\n compression='gzip', compression_opts=4,\r\n dtype=data_dtype)\r\n h5_fout.create_dataset(\r\n 'label', data=label,\r\n compression='gzip', compression_opts=1,\r\n dtype=label_dtype)\r\n h5_fout.close()\r\n\r\ncur_path = os.path.dirname(os.path.realpath(__file__))\r\ndir_path = os.path.join(cur_path, \"ModelNet40\")\r\n# list of all the categories\r\ndirectories = [d for d in os.listdir(dir_path)\r\n if os.path.isdir(os.path.join(dir_path, d))]\r\n\r\nload_dict = [[\"train\", \"ModelNet40/train\"], [\"test\", \"ModelNet40/test\"]]\r\nflag=\"train_labels_name\"\r\nfor d in load_dict:\r\n label_names = {}\r\n for i in range(len(directories)):\r\n label_name = directories[i]\r\n train_path = os.path.join(dir_path, directories[i], d[0])\r\n save_path = os.path.join(cur_path, d[1])\r\n All_points = None\r\n label = []\r\n label_names[i]=label_name\r\n # all the files in \"train\" floder\r\n for filename in os.listdir(train_path):\r\n print('read:',filename)\r\n if '.off' in filename:\r\n s = os.path.join(train_path, filename)\r\n points = read_off(s)\r\n\r\n if All_points is None:\r\n if points:\r\n\r\n All_points = points\r\n label.append(i)\r\n elif points:\r\n All_points = np.vstack((All_points, points))\r\n label.append(i)\r\n if not os.path.exists(save_path):\r\n os.makedirs(save_path)\r\n data_save_path = os.path.join(save_path, directories[i] + '.h5')\r\n save_h5(data_save_path, All_points, label)\r\n try:\r\n print(All_points.shape)\r\n print(len(label))\r\n except:\r\n print(type(All_points))\r\n print(\"eer\")\r\n print(label_names)\r\n import pickle\r\n output = open('%s.pkl'%flag, 'wb')\r\n #保存label的name\r\n pickle.dump(label_names, output)\r\n output.close()\r\n flag=\"test_labels_name\"\r\n\r\n##################将40个类别的h5整合成一个################################\r\n\r\ndata_path = 'ModelNet40/'\r\ndef load_h5(h5_filename):\r\n f = h5py.File(h5_filename)\r\n data = f['data'][:]\r\n label = f['label'][:]\r\n return (data, label)\r\nfor d in [['train', len(os.listdir(data_path + 'train'))], ['test', len(os.listdir(data_path + 'test'))]]:\r\n data = None\r\n labels = None\r\n path = os.path.dirname(os.path.realpath(__file__))\r\n path = os.path.join(path, data_path+d[0])\r\n filenames = [d for d in os.listdir(path)]\r\n for s in filenames:\r\n cur_data,cur_labels=load_h5(os.path.join(path, s))\r\n cur_data = cur_data.reshape(1, -1, 3)\r\n cur_labels = cur_labels.reshape(1, -1)\r\n if labels is None or data is None:\r\n labels=cur_labels\r\n data=cur_data\r\n else:\r\n labels = np.hstack((labels, cur_labels))\r\n data = np.hstack((data, cur_data))\r\n\r\n data = data.reshape(-1, 2048, 3)\r\n labels = labels.reshape(-1, 1)\r\n save_name = data_path + '/ply_data_{0}.h5'.format(d[0])\r\n print(data.shape)\r\n print(labels.shape)\r\n h5_fout = h5py.File(save_name)\r\n h5_fout.create_dataset(\r\n 'data', data=data,\r\n dtype='float32')\r\n h5_fout.create_dataset(\r\n 'label', data=labels,\r\n dtype='float32')\r\n h5_fout.close()\r\n","sub_path":"dataPrep.py","file_name":"dataPrep.py","file_ext":"py","file_size_in_byte":5448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"233801618","text":"#!/usr/bin/env python3\n\nimport sys\nimport os\nimport re\nimport signal\nimport shutil\nimport logging\n\nfrom mozapkpublisher.common.apk.history import get_expected_api_levels_for_version, get_firefox_major_version_number\nfrom mozapkpublisher.common.base import Base, ArgumentParser\nfrom mozapkpublisher.common.exceptions import CheckSumMismatch\nfrom mozapkpublisher.common.utils import load_json_url, download_file, file_sha512sum\n\nlogger = logging.getLogger(__name__)\n\nFTP_BASE_URL = 'https://ftp.mozilla.org/pub/mobile'\n\n\nclass GetAPK(Base):\n arch_values = [\"arm\", \"x86\"]\n\n json_version_url = \"https://product-details.mozilla.org/1.0/firefox_versions.json\"\n\n @classmethod\n def _init_parser(cls):\n cls.parser = ArgumentParser(\n description='Download APKs of Firefox for Android (aka Fennec) from {}'.format(FTP_BASE_URL)\n )\n\n exclusive_group = cls.parser.add_mutually_exclusive_group(required=True)\n exclusive_group.add_argument('--version', default=None, help='Specify version number to download (e.g. 23.0b7)')\n exclusive_group.add_argument('--latest-nightly', action='store_true', default=False,\n help='Download the latest nightly version')\n\n cls.parser.add_argument('--build', type=int, default=1, help='Specify build number (default 1)')\n cls.parser.add_argument(\n '--arch', choices=cls.arch_values, default='all',\n help='Specify which architecture to get the apk for. Will download every architecture if not set.'\n )\n cls.parser.add_argument('--locale', default='multi', help='Specify which locale to get the apk for')\n cls.parser.add_argument(\n '--output-directory', dest='download_directory', default='apk-download',\n help='Directory in which APKs will be downloaded to. Will be created if needed.'\n )\n\n # Cleanup half downloaded files on Ctrl+C\n def signal_handler(self, signal, frame):\n print(\"You pressed Ctrl+C!\")\n self.cleanup()\n sys.exit(1)\n\n def cleanup(self):\n try:\n shutil.rmtree(self.config.download_directory)\n logger.info('Download directory cleaned')\n except FileNotFoundError:\n logger.warn('{} was not found. Skipping...'.format(self.config.download_directory))\n\n def generate_apk_base_url(self, version, build, locale, api_suffix):\n return '{}/nightly/latest-mozilla-central-android-{}'.format(FTP_BASE_URL, api_suffix) \\\n if self.config.latest_nightly else \\\n '{}/android-{}/{}'.format(\n generate_base_directory(version, build),\n api_suffix,\n locale,\n )\n\n def get_api_suffix(self, version, arch):\n if arch != 'arm':\n return [arch]\n else:\n api_levels = get_expected_api_levels_for_version(version)\n # TODO support old schemes when no API level was in the path\n return [\n 'api-{}'.format(api_level) for api_level in api_levels\n ]\n\n def download(self, version, build, architecture, locale):\n try:\n os.makedirs(self.config.download_directory)\n except FileExistsError:\n pass\n\n for api_suffix in self.get_api_suffix(version, architecture):\n apk_base_url = self.generate_apk_base_url(version, build, locale, api_suffix)\n urls_and_locations = craft_apk_and_checksums_url_and_download_locations(\n apk_base_url, self.config.download_directory, version, build, locale, architecture\n )\n apk = urls_and_locations['apk']\n checksums = urls_and_locations['checksums']\n\n download_file(apk['url'], apk['download_location'])\n download_file(checksums['url'], checksums['download_location'])\n\n check_apk_against_checksum_file(apk['download_location'], checksums['download_location'])\n\n def get_version_name(self):\n if self.config.latest_nightly:\n json = load_json_url(self.json_version_url)\n version_code = json['FIREFOX_NIGHTLY']\n return version_code\n return self.config.version\n\n # Download all the archs if none is given\n def download_all(self, version, build, locale):\n for architecture in self.arch_values:\n self.download(version, build, architecture, locale)\n\n def run(self):\n version = self.get_version_name()\n architecture = self.config.arch\n build = str(self.config.build)\n locale = self.config.locale\n\n logger.info('Downloading version \"{}\" build #{} for arch \"{}\" (locale \"{}\")'.format(version, build, architecture, locale))\n if architecture == \"all\":\n self.download_all(version, build, locale)\n else:\n self.download(version, build, architecture, locale)\n\n\ndef craft_apk_and_checksums_url_and_download_locations(base_apk_url, download_directory, version, build, locale, architecture):\n file_names = _craft_apk_and_checksums_file_names(version, locale, architecture)\n\n urls_and_locations = {\n extension: {\n 'download_location': os.path.join(download_directory, file_name),\n 'url': '/'.join([base_apk_url, file_name]),\n } for extension, file_name in file_names.items()\n }\n\n if get_firefox_major_version_number(version) >= 59:\n urls_and_locations['checksums']['url'] = '{}/{}'.format(\n generate_base_directory(version, build), 'SHA512SUMS'\n )\n\n return urls_and_locations\n\n\ndef generate_base_directory(version, build):\n return '{}/candidates/{}-candidates/build{}'.format(FTP_BASE_URL, version, build)\n\n\ndef _craft_apk_and_checksums_file_names(version, locale, architecture):\n file_name_architecture = _get_architecture_in_file_name(architecture)\n extensions = ['apk', 'checksums']\n\n return {\n extension: 'fennec-{}.{}.android-{}.{}'.format(version, locale, file_name_architecture, extension)\n for extension in extensions\n }\n\n\ndef _get_architecture_in_file_name(architecture):\n # the file name contains i386 instead of x86\n return 'i386' if architecture == 'x86' else architecture\n\n\ndef check_apk_against_checksum_file(apk_file, checksum_file):\n logger.debug('Checking checksum for \"{}\"...'.format(apk_file))\n\n checksum = _fetch_checksum_from_file(checksum_file, apk_file)\n apk_checksum = file_sha512sum(apk_file)\n\n if checksum == apk_checksum:\n logger.info('Checksum for \"{}\" succeeded!'.format(apk_file))\n os.remove(checksum_file)\n else:\n raise CheckSumMismatch(apk_file, expected=apk_checksum, actual=checksum)\n\n\ndef _fetch_checksum_from_file(checksum_file, apk_file):\n base_apk_filepath = _take_out_common_path(checksum_file, apk_file)\n\n # pre-Fennec 58 style\n checksum = _match_checksum_regex(\n checksum_file, r\"\"\"^(?P.*) sha512 (?P\\d+) {}\"\"\".format(base_apk_filepath)\n )\n\n if not checksum:\n # post-Fennec 58. More greedy\n checksum = _match_checksum_regex(\n checksum_file, r\"\"\"^(?P.*) {}\"\"\".format(base_apk_filepath)\n )\n\n if not checksum:\n # old style pre-Fennec 53 checksums files. Super greedy\n with open(checksum_file, 'r') as f:\n checksum = f.read()\n checksum = re.sub(\"\\s(.*)\", \"\", checksum.splitlines()[0])\n\n logger.info(\"Found hash {}\".format(checksum))\n return checksum\n\n\ndef _match_checksum_regex(checksum_file, regex):\n with open(checksum_file, 'r') as fh:\n for line in fh:\n m = re.match(regex, line)\n if m:\n gd = m.groupdict()\n return gd['hash']\n return None\n\n\ndef _take_out_common_path(checksum_file, apk_file):\n return os.path.relpath(apk_file, os.path.dirname(checksum_file))\n\n\nif __name__ == '__main__':\n from mozapkpublisher.common import main_logging\n main_logging.init()\n\n myScript = GetAPK()\n signal.signal(signal.SIGINT, myScript.signal_handler)\n myScript.run()\n","sub_path":"mozapkpublisher/get_apk.py","file_name":"get_apk.py","file_ext":"py","file_size_in_byte":8092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168072128","text":"# Using text2 from the nltk book corpa, create your own version of the\n# MadLib program. \n\n# Requirements:\n# 1) Only use the first 150 tokens\n# 2) Pick 5 parts of speech to prompt for, including nouns\n# 3) Replace nouns 15% of the time, everything else 10%\n\n# Deliverables:\n# 1) Print the orginal text (150 tokens)\n# 1) Print the new text\nprint(\"START*******\")\n\nimport random\nimport nltk\nfrom nltk.book import *\nfrom nltk import word_tokenize,sent_tokenize\n\n\ndebug = False\n\nif debug:\n\tprint (\"Getting information from text2...\\n\")\n\noriginal_text = (text2[:151])\nparagraph = \" \".join(original_text)\nprint(\"Original Text:\")\nprint (paragraph)\n\ntokens = nltk.word_tokenize(paragraph)\ntagged_tokens = nltk.pos_tag(tokens) \n\n\ntagmap = {\"NN\":\"a noun\",\"NNS\":\"a plural noun\",\"VB\":\"a verb\",\"JJ\":\"an adjective\", \"PRP\":\"a preposition\"}\nsubstitution_probabilities = {\"NN\":.15,\"NNS\":.10,\"VB\":.10,\"JJ\":.10, \"PRP\":.10}\n\ndef spaced(word):\n \tif word in [\",\", \".\", \"?\", \"!\", \":\"]:\n \t\treturn word\n \telse:\n \t\treturn \" \" + word\n\nfinal_words = []\n\nfor (word, tag) in tagged_tokens:\n \tif tag not in substitution_probabilities or random.random() > substitution_probabilities[tag]:\n \t\tfinal_words.append(spaced(word))\n \telse:\n \t\tnew_word = input(\"Please enter %s:\\n\" % (tagmap[tag]))\n \t\tfinal_words.append(spaced(new_word))\n\t\t\n\nfinal_text = \"\".join(final_words)\t\t\t\t\nprint(\"New Text:\")\nprint (final_text)\n\nprint(\"\\n\\nEND*******\")\n","sub_path":"HW3-StudentCopy/madlibhw3.py","file_name":"madlibhw3.py","file_ext":"py","file_size_in_byte":1404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"402229563","text":"from tkinter import *\nroot = Tk()\nroot.title('Inheritance')\nroot.geometry('600x600')\n\nlabel_name = Label(root,text='Username: ')\nlabel_name.place(relx=0.3,rely=0.2,anchor=CENTER)\nentry_name = Entry(root)\nentry_name.place(relx=0.6,rely=0.2,anchor=CENTER)\nlabel_email = Label(root,text='Email ID: ')\nlabel_email.place(relx=0.3,rely=0.3,anchor=CENTER)\nentry_email = Entry(root)\nentry_email.place(relx=0.6,rely=0.3,anchor=CENTER)\nlabel = Label(root)\n\ndictionary = {}\nclass Users:\n def addUser(key,value):\n dictionary[key] = value \n label = dictionary\n \nclass GetUsers(Users):\n def getUser(self):\n username = entry_name.get()\n email_id = entry_email.get()\n Users.addUser(username,email_id)\n \nuser = GetUsers()\nbtn = Button(root,text='Add user details',command=user.getUser)\nbtn.place(relx=0.5,rely = 0.4,anchor=CENTER)\nlabel.place(relx=0.5,rely=0.5,anchor=CENTER)\n \nroot.mainloop()","sub_path":"P172.py","file_name":"P172.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359783697","text":"import os\nimport sys\nimport string\n\nimport logging\nimport string\nimport uuid\nimport re\n\nimport services.datamodel as datamodel\nimport services.securityservice as securityservice\n\n# Log a message each time this module get loaded.\nlogging.info('Loading %s, app version = %s',\n __name__, os.getenv('CURRENT_VERSION_ID'))\n\n# Declare the Django version we need.\nfrom google.appengine.dist import use_library\nuse_library('django', '1.0')\n\n# Fail early if we can't import Django 1.x. Log identifying information.\nimport django\nlogging.info('django.__file__ = %r, django.VERSION = %r',\n django.__file__, django.VERSION)\nassert django.VERSION[0] >= 1, \"This Django version is too old\"\n\n\n# Custom Django configuration.\nos.environ['DJANGO_SETTINGS_MODULE'] = 'settings'\nfrom django.conf import settings\nsettings._target = None\n\n# Import various parts of Django.\nimport django.core.handlers.wsgi\nimport django.core.signals\nimport django.db\nimport django.dispatch.dispatcher\nimport django.forms\n\n# Work-around to avoid warning about django.newforms in djangoforms.\ndjango.newforms = django.forms\n\nimport datetime\nfrom services import constants, utils\n\n\ndef log_exception(*args, **kwds):\n \"\"\"Django signal handler to log an exception.\"\"\"\n cls, err = sys.exc_info()[:2]\n logging.exception('Exception in request: %s: %s', cls.__name__, err)\n\n\n# Log all exceptions detected by Django.\ndjango.core.signals.got_request_exception.connect(log_exception)\n\n# Unregister Django's default rollback event handler.\ndjango.core.signals.got_request_exception.disconnect(\n django.db._rollback_on_exception)\n\n#import others\nimport wsgiref.handlers\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext import db\nfrom google.appengine.api import images\n\ndef get_request_value(request, name, default=None):\n ret = request.get(name)\n if not ret:\n try:\n ret = request.cookies.get(name)\n except KeyError:\n pass\n if not ret:\n ret = default\n return ret\n\nclass FileUploadHandler(webapp.RequestHandler):\n def get(self): \n file = None\n user = None\n \n token = get_request_value(self.request, 'token')\n fid = get_request_value(self.request, 'id')\n fsize = get_request_value(self.request, 'size', 'original')\n \n if token:\n user = securityservice.SecurityService.authenticate_user_token(token)\n if fid and user:\n file = db.get(fid)\n logging.info(fsize)\n \n if file and fsize=='original' and file.fileBlob:\n self.response.headers['Content-Type'] = str(file.fileType)\n self.response.out.write(file.fileBlob)\n \n elif file and fsize=='thumbnail' and file.thumbnailBlob:\n self.response.headers['Content-Type'] = str(file.fileType)\n self.response.out.write(file.thumbnailBlob) \n \n elif file and fsize and file.fileSize < 2097152 and file.fileBlob:\n sizes = string.split(fsize, 'x')\n if (len(sizes) == 2):\n result = images.resize(file.fileBlob, int(sizes[0]), int(sizes[1]))\n self.response.headers['Content-Type'] = str(file.fileType)\n self.response.out.write(result) \n else:\n self.error(404)\n else:\n self.error(404)\n \n def post(self): \n token = get_request_value(self.request, 'token')\n data = get_request_value(self.request, 'upload')\n key = get_request_value(self.request, 'id')\n user = securityservice.SecurityService.authenticate_user_token(token)\n \n if key is None:\n key = utils.new_key()\n logging.info('No id in request: %s', key)\n \n #logging.info(self.request)\n if user and data: # and len(data)<=2097152:\n file = datamodel.UploadedFile(key_name = key)\n file.ip = self.request.remote_addr\n \n file.fileName = self.request.POST.get('upload').filename;\n if not file.fileName:\n file.fileName = str(uuid.uuid1()) \n logging.info(file.fileName)\n \n file.fileType = None #self.request.headers.get('Content-Type')\n if not file.fileType:\n file.fileType = 'image/png'\n logging.info(file.fileType)\n \n if 'image' in file.fileType:\n img = images.Image(data)\n file.width = img.width\n file.height = img.height\n \n if len(data)<=524288 and 'image' in file.fileType:\n file.thumbnailBlob = db.Blob(images.resize(data, 96, 96))\n\n file.fileBlob = db.Blob(data) \n file.fileSize = len(data)\n file.owner = user.name\n file.is_deleted = False\n file.updated = datetime.datetime.now()\n file.bookmark = utils.bookmark_for_kind(datatype, user.name, file.updated)\n file.put()\n \n file.url = '/assets?id=%s' % (file.key()) \n if file.thumbnailBlob:\n file.thumbnail = '/assets?id=%s&size=thumbnail' % (file.key()) \n file.put()\n \n json_ret = '{\"status\": \"0\", \"id\": \"%s\", \"url\": \"%s\"}' % (key, file.url)\n self.response.out.write(json_ret)\n \n else:\n logging.error('File upload failed, upload key is missing or file size > 2MB')\n self.error(401)\n \ndef main():\n application = webapp.WSGIApplication([\n ('/assets', FileUploadHandler),\n ], debug=True)\n wsgiref.handlers.CGIHandler().run(application)\n\nif __name__ == '__main__':\n main()\n","sub_path":"parabaylite/src/services/uploadservice.py","file_name":"uploadservice.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"642800825","text":"# -*- coding: utf-8 -*-\n\"\"\"The Raspberry onewire bus\n\nInstallation :\n\nLoad modules at boot :\n\n.. code-block:: bash\n\n sudo vim /etc/modules\n\nTo add :\n\n.. code-block:: bash\n\n w1-gpio\n w1-therm\n\nUpdate boot config :\n\n.. code-block:: bash\n\n sudo vim /boot/config.txt\n\nTo add :\n\n.. code-block:: bash\n\n dtoverlay=w1-gpio,gpiopin=4\n\n\"\"\"\n\n__license__ = \"\"\"\n This file is part of Janitoo.\n\n Janitoo is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n Janitoo is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with Janitoo. If not, see .\n\n\"\"\"\n__author__ = 'Sébastien GALLET aka bibi21000'\n__email__ = 'bibi21000@gmail.com'\n__copyright__ = \"Copyright © 2013-2014-2015-2016 Sébastien GALLET aka bibi21000\"\n\n# Set default logging handler to avoid \"No handler found\" warnings.\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom janitoo.thread import JNTBusThread\nfrom janitoo.options import get_option_autostart\n\n##############################################################\n#Check that we are in sync with the official command classes\n#Must be implemented for non-regression\nfrom janitoo.classes import COMMAND_DESC\n\nCOMMAND_CONTROLLER = 0x1050\n\nassert(COMMAND_DESC[COMMAND_CONTROLLER] == 'COMMAND_CONTROLLER')\n##############################################################\n\nfrom janitoo_raspberry_1wire import OID\n\ndef make_thread(options, force=False):\n if get_option_autostart(options, OID) or force:\n return Rpi1wireThread(options)\n else:\n return None\n\nclass Rpi1wireThread(JNTBusThread):\n \"\"\"The I2C thread\n\n \"\"\"\n def init_bus(self):\n \"\"\"Build the bus\n \"\"\"\n from janitoo_raspberry_1wire.bus_1wire import OnewireBus\n self.section = OID\n self.bus = OnewireBus(options=self.options, oid=self.section, product_name=\"Raspberry 1Wire bus\")\n","sub_path":"src/janitoo_raspberry_1wire/thread_1wire.py","file_name":"thread_1wire.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394602821","text":"from kivy.uix.label import Label\n\nfrom controller.popup.getter import get_empty_thought_popup\nfrom database_manager.thought_manager import EmptyThoughtException\nfrom database_manager.util import ChumMeDBManager\nfrom model.thought import Thought\nfrom utils.widget import hide_label, show_label, hide_widget, show_widget\nfrom .friend_carousel import FriendInfo\n\n\nclass FriendThoughts(FriendInfo):\n def update_friend_info(self, friend):\n super().update_friend_info(friend)\n self.thoughts = ChumMeDBManager().\\\n thought_manager.get_thoughts_by_friend_id(\n self.friend.id\n )\n no_thoughts_label = self.no_thoughts_label\n thought_scroll = self.thought_scroll_view\n\n if self.thoughts:\n hide_label(no_thoughts_label)\n show_widget(thought_scroll)\n self.display_thoughts(self.thoughts)\n else:\n show_label(no_thoughts_label,\n 'There are no thoughts about your friend.')\n hide_widget(thought_scroll)\n\n def display_thoughts(self, thoughts):\n container = self.thought_scroll_view.thought_container\n for thought in thoughts:\n label = ThoughtLabel(thought)\n container.add_widget(label)\n\n def add_thought(self, text):\n try:\n ChumMeDBManager().thought_manager.add_thought(\n self.friend.id, text.strip()\n )\n except EmptyThoughtException:\n self.popup = get_empty_thought_popup(self._on_answer)\n self.popup.open()\n else:\n if not self.thoughts:\n hide_label(self.no_thoughts_label)\n show_widget(self.thought_scroll_view)\n\n thought = Thought(text)\n label = ThoughtLabel(thought)\n self.thought_scroll_view.thought_container.add_widget(label)\n self.thought_input.text = ''\n self.thought_input.focus = True\n\n def _on_answer(self, instance):\n self.popup.dismiss()\n self.thought_input.text = ''\n self.thought_input.focus = True\n\n\nclass ThoughtLabel(Label):\n def __init__(self, thought, **kwargs):\n super().__init__(**kwargs)\n self._format_thougth(thought)\n\n def _format_thougth(self, thought):\n template = \"[b][size=22]{}[/size][/b]\\n\"\\\n \"[i]{}[/i]\"\n self.text = template.format(thought.creation_date, thought.text)\n","sub_path":"controller/friend_info/friend_thoughts.py","file_name":"friend_thoughts.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"556794102","text":"# Copyright 2017 Red Hat, Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\nimport os\nimport re\nimport sys\n\nfrom cliff.command import Command\nfrom junit_xml import TestCase\nfrom junit_xml import TestSuite\n\nfrom ara import app\nfrom ara import freezer\nfrom ara import models\n\n\nclass GenerateHtml(Command):\n \"\"\"Generates a static tree of the web application\"\"\"\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(GenerateHtml, self).get_parser(prog_name)\n parser.add_argument(\n 'path',\n metavar='',\n help='Path where the static files will be built in',\n )\n return parser\n\n def take_action(self, args):\n app.config['FREEZER_DESTINATION'] = os.path.abspath(args.path)\n self.log.warn('Generating static files at %s...',\n args.path)\n freezer.freezer.freeze()\n\n print('Done.')\n\n\nclass GenerateJunit(Command):\n \"\"\"Generate junit stream from ara data\"\"\"\n log = logging.getLogger(__name__)\n\n def get_parser(self, prog_name):\n parser = super(GenerateJunit, self).get_parser(prog_name)\n parser.add_argument(\n 'output_file',\n metavar='',\n help='The file to write the junit xml to. Use \"-\" for stdout.',\n )\n return parser\n\n def _sanitize(self, instr):\n \"\"\"Make a string suitable for use in a dotted pseudo python path\"\"\"\n return re.sub('\\W+', '_', instr)\n\n def take_action(self, args):\n test_cases = []\n task_results = models.TaskResult().query.all()\n for result in task_results:\n task_name = result.task.name\n if not task_name:\n task_name = result.task.action\n test_path = \\\n \"{host_name}.{playbook_path}.{play_name}\".format(\n host_name=result.host.name,\n playbook_path=self._sanitize(result.task.playbook.path),\n play_name=self._sanitize(result.task.play.name))\n test_case = TestCase(\n name=task_name,\n classname=test_path,\n elapsed_sec=result.duration.seconds\n )\n if result.status == \"skipped\":\n test_case.add_skipped_info(message=result.result)\n elif (result.status in (\"failed\", \"unreachable\") and\n result.ignore_errors is False):\n test_case.add_failure_info(message=result.result)\n test_cases.append(test_case)\n test_suite = TestSuite(\"Ansible Tasks\", test_cases)\n\n xml_string = test_suite.to_xml_string([test_suite])\n if args.output_file == \"-\":\n sys.stdout.write(xml_string)\n else:\n with open(args.output_file, \"w\") as f:\n f.write(xml_string)\n","sub_path":"ara/cli/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"396289513","text":"import requests\n\nbase_url = \"http://httpbin.org/\"\n\n\ndef get_delay(seconds):\n endpoint = f\"/delay/{seconds}\"\n\n print(f\"Getting with {seconds} delay ... \")\n\n resp = requests.get(base_url + endpoint)\n data = resp.json()\n print(data)\n\n\nget_delay(5)\n\nprint(\"Okay! All finished getting.\")\n","sub_path":"DEVASC-ENAUTO/CBTNuggets/Other/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248578156","text":"list = [2,4,9,10,5,7]\nmaxi= max(list[0],list[1])\nsecondmax = min (list[0],list[1])\n\nfor i in range (2, len(list)):\n if list[i]>maxi:\n secondmax=maxi\n maxi=list[i]\n else:\n if list[i]>secondmax:\n secondmax=list[i]\nprint(\"the second largest number is:\", secondmax)\n","sub_path":"Geeksforgeeks/secondlarget_list.py","file_name":"secondlarget_list.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"98047387","text":"# test mod_md basic configurations\n\nimport re\nimport pytest\n\nfrom configparser import ConfigParser\nfrom TestEnv import TestEnv\nfrom TestHttpdConf import HttpdConf\n\n\ndef setup_module(module):\n print(\"setup_module module:%s\" % module.__name__)\n TestEnv.init()\n TestEnv.clear_store()\n \n\ndef teardown_module(module):\n print(\"teardown_module module:%s\" % module.__name__)\n TestEnv.apache_stop()\n\n\nclass TestConf:\n\n def setup_method(self, method):\n print(\"setup_method: %s\" % method.__name__)\n TestEnv.httpd_error_log_clear()\n\n def teardown_method(self, method):\n print(\"teardown_method: %s\" % method.__name__)\n\n # test case: just one MDomain definition\n def test_300_001(self):\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org\n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n\n # test case: two MDomain definitions, non-overlapping\n def test_300_002(self):\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org\n MDomain example2.org www.example2.org mail.example2.org\n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n\n # test case: two MDomain definitions, exactly the same\n def test_300_003(self):\n assert TestEnv.apache_stop() == 0\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n \"\"\").install()\n assert TestEnv.apache_fail() == 0\n \n # test case: two MDomain definitions, overlapping\n def test_300_004(self):\n assert TestEnv.apache_stop() == 0\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n MDomain example2.org test3.not-forbidden.org www.example2.org mail.example2.org\n \"\"\").install()\n assert TestEnv.apache_fail() == 0\n\n # test case: two MDomains, one inside a virtual host\n def test_300_005(self):\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n \n MDomain example2.org www.example2.org www.example3.org\n \n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n\n # test case: two MDomains, one correct vhost name\n def test_300_006(self):\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n \n ServerName example2.org\n MDomain example2.org www.example2.org www.example3.org\n \n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n\n # test case: two MDomains, two correct vhost names\n def test_300_007(self):\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n \n ServerName example2.org\n MDomain example2.org www.example2.org www.example3.org\n \n \n ServerName www.example2.org\n \n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n\n # test case: two MDomains, overlapping vhosts\n def test_300_008(self):\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n \n ServerName example2.org\n ServerAlias www.example3.org\n MDomain example2.org www.example2.org www.example3.org\n \n\n \n ServerName www.example2.org\n ServerAlias example2.org\n \n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n\n # test case: vhosts with overlapping MDs\n def test_300_009(self):\n assert TestEnv.apache_stop() == 0\n conf = HttpdConf(text=\"\"\"\n ServerAdmin admin@not-forbidden.org\n MDMembers manual\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n MDomain example2.org www.example2.org www.example3.org\n \"\"\")\n conf.add_ssl_vhost(port=12346, domains=[\"example2.org\", \"www.example3.org\"])\n conf.add_ssl_vhost(port=12346, domains=[\"www.example2.org\", \"example2.org\"])\n conf.add_ssl_vhost(port=12346, domains=[\"not-forbidden.org\", \"example2.org\"])\n conf.install()\n assert TestEnv.apache_fail() == 0\n\n # test case: MDomain, vhost with matching ServerAlias\n def test_300_010(self):\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n\n \n ServerName not-forbidden.org\n ServerAlias test3.not-forbidden.org\n \n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n assert (0, 0) == TestEnv.httpd_error_log_count()\n\n # test case: MDomain, misses one ServerAlias\n def test_300_011a(self):\n conf = HttpdConf(text=\"\"\"\n MDomain not-forbidden.org manual www.not-forbidden.org mail.not-forbidden.org test3.not-forbidden.org\n \"\"\")\n conf.add_ssl_vhost(port=TestEnv.HTTPS_PORT, domains=[\n \"not-forbidden.org\", \"test3.not-forbidden.org\", \"test4.not-forbidden.org\"\n ])\n conf.install()\n assert TestEnv.apache_fail() == 0\n assert (1, 0) == TestEnv.httpd_error_log_count()\n\n # test case: MDomain, misses one ServerAlias, but auto add enabled\n def test_300_011b(self):\n assert TestEnv.apache_stop() == 0\n HttpdConf(text=\"\"\"\n MDomain not-forbidden.org auto mail.not-forbidden.org\n\n \n ServerName not-forbidden.org\n ServerAlias test3.not-forbidden.org\n ServerAlias test4.not-forbidden.org\n \n \"\"\" % TestEnv.HTTPS_PORT).install()\n assert TestEnv.apache_restart() == 0\n assert (0, 0) == TestEnv.httpd_error_log_count()\n\n # test case: MDomain does not match any vhost\n def test_300_012(self):\n HttpdConf(text=\"\"\"\n MDomain example012.org www.example012.org\n \n ServerName not-forbidden.org\n ServerAlias test3.not-forbidden.org\n \n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n assert (0, 1) == TestEnv.httpd_error_log_count()\n\n # test case: one md covers two vhosts\n def test_300_013(self):\n HttpdConf(text=\"\"\"\n MDomain example2.org test-a.example2.org test-b.example2.org\n \n ServerName test-a.example2.org\n \n \n ServerName test-b.example2.org\n \n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n assert (0, 0) == TestEnv.httpd_error_log_count()\n\n # test case: global server name as managed domain name\n def test_300_014(self):\n HttpdConf(text=\"\"\"\n MDomain %s www.example2.org\n\n \n ServerName www.example2.org\n \n \"\"\" % TestEnv.HOSTNAME).install()\n assert TestEnv.apache_restart() == 0\n assert (0, 0) == TestEnv.httpd_error_log_count()\n\n # test case: valid pkey specification\n def test_300_015(self):\n HttpdConf(text=\"\"\"\n MDPrivateKeys Default\n MDPrivateKeys RSA\n MDPrivateKeys RSA 2048\n MDPrivateKeys RSA 3072\n MDPrivateKeys RSA 4096\n \"\"\").install()\n assert TestEnv.apache_restart() == 0\n assert (0, 0) == TestEnv.httpd_error_log_count()\n\n # test case: invalid pkey specification\n @pytest.mark.parametrize(\"line,exp_err_msg\", [\n (\"MDPrivateKeys\", \"needs to specify the private key type\"), \n (\"MDPrivateKeys Default RSA 1024\", \"'Default' allows no other parameter\"),\n (\"MDPrivateKeys RSA 1024\", \"must be 2048 or higher\"),\n (\"MDPrivateKeys RSA 1024\", \"must be 2048 or higher\"),\n (\"MDPrivateKeys rsa 2048 rsa 4096\", \"two keys of type 'RSA' are not possible\"),\n (\"MDPrivateKeys p-256 secp384r1 P-256\", \"two keys of type 'P-256' are not possible\"),\n ])\n def test_300_016(self, line, exp_err_msg):\n HttpdConf(text=line).install()\n assert TestEnv.apache_restart() == 1\n assert exp_err_msg in TestEnv.apachectl_stderr\n\n # test case: invalid renew window directive\n @pytest.mark.parametrize(\"line,exp_err_msg\", [\n (\"MDRenewWindow dec-31\", \"has unrecognized format\"), \n (\"MDRenewWindow 1y\", \"has unrecognized format\"), \n (\"MDRenewWindow 10 d\", \"takes one argument\"), \n (\"MDRenewWindow 102%\", \"a length of 100% or more is not allowed.\")])\n def test_300_017(self, line, exp_err_msg):\n HttpdConf(text=line).install()\n assert TestEnv.apache_restart() == 1\n assert exp_err_msg in TestEnv.apachectl_stderr\n\n # test case: invalid uri for MDProxyPass\n @pytest.mark.parametrize(\"line,exp_err_msg\", [\n (\"MDHttpProxy\", \"takes one argument\"), \n (\"MDHttpProxy localhost:8080\", \"scheme must be http or https\"),\n (\"MDHttpProxy https://127.0.0.1:-443\", \"invalid port\"),\n (\"MDHttpProxy HTTP localhost 8080\", \"takes one argument\")])\n def test_300_018(self, line, exp_err_msg):\n HttpdConf(text=line).install()\n assert TestEnv.apache_restart() == 1, \"Server accepted test config {}\".format(line)\n assert exp_err_msg in TestEnv.apachectl_stderr\n\n # test case: invalid parameter for MDRequireHttps\n @pytest.mark.parametrize(\"line,exp_err_msg\", [\n (\"MDRequireHTTPS yes\", \"supported parameter values are 'temporary' and 'permanent'\"),\n (\"MDRequireHTTPS\", \"takes one argument\")])\n def test_300_019(self, line, exp_err_msg):\n HttpdConf(text=line).install()\n assert TestEnv.apache_restart() == 1, \"Server accepted test config {}\".format(line)\n assert exp_err_msg in TestEnv.apachectl_stderr\n\n # test case: invalid parameter for MDMustStaple\n @pytest.mark.parametrize(\"line,exp_err_msg\", [\n (\"MDMustStaple\", \"takes one argument\"), \n (\"MDMustStaple yes\", \"supported parameter values are 'on' and 'off'\"),\n (\"MDMustStaple true\", \"supported parameter values are 'on' and 'off'\")])\n def test_300_020(self, line, exp_err_msg):\n HttpdConf(text=line).install()\n assert TestEnv.apache_restart() == 1, \"Server accepted test config {}\".format(line)\n assert exp_err_msg in TestEnv.apachectl_stderr\n\n # test case: alt-names incomplete detection, github isse #68\n def test_300_021(self):\n conf = HttpdConf(text=\"\"\"\n MDMembers manual\n MDomain secret.com\n \"\"\")\n conf.add_ssl_vhost(port=12344, domains=[\n \"not.secret.com\", \"secret.com\"\n ])\n conf.install()\n assert TestEnv.apache_fail() == 0\n assert (1, 0) == TestEnv.httpd_error_log_count()\n assert TestEnv.httpd_error_log_scan(\n re.compile(\".*Virtual Host not.secret.com:0 matches Managed Domain 'secret.com', \"\n \"but the name/alias not.secret.com itself is not managed. A requested \"\n \"MD certificate will not match ServerName.*\"))\n\n # test case: use MDRequireHttps in an construct, but not in \n MDRequireHttps temporary\n \n \n ServerName secret.com\n \n \"\"\").install()\n assert TestEnv.apache_start() == 0\n conf = HttpdConf(text=\"\"\"\n MDomain secret.com\n \n MDRequireHttps temporary\n \n \"\"\")\n conf.add_ssl_vhost(port=12344, domains=[\"secret.com\"])\n conf.install()\n assert TestEnv.apache_restart() == 1\n","sub_path":"test/test_0300_conf_validate.py","file_name":"test_0300_conf_validate.py","file_ext":"py","file_size_in_byte":12707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"114583557","text":"queen_in = open('queen.in', 'r')\nqueen_out = open('queen.out', 'w')\n\n# Читаем\nn, m = map(int, queen_in.readline().split())\nx, y = map(int, queen_in.readline().split())\nqueen_in.close()\n\nans = n + m - 2\nans += min(n - x, m - y)\nans += min(x - 1, m - y)\nans += min(n - x, y - 1)\nans += min(x - 1, y - 1)\n\nprint(ans, file=queen_out)\nqueen_out.close()\n","sub_path":"LKSH2/0706/queen.py","file_name":"queen.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250175145","text":"try:\n from flask import app,Flask, request, render_template, jsonify\n from flask_restful import Resource, Api, reqparse\n import datetime\n import json\n import os\n import sys\n import ssl\n import os\n import tensorflow_hub as hub\n import tensorflow as tf\n import warnings\n import compute_inference\n from tabulate import tabulate\n import flat_table\n from pandas import json_normalize\nexcept Exception as e:\n print(\"Error : {} \".format(e))\n\n\napp = Flask(__name__)\napi = Api(app)\n\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\n\n\n\ndef label2str(x):\n if x == 0:\n return [\"negative\"]\n else:\n return [\"positive\"]\n\n\ndef predict_online(data):\n\n print(\"Predicting sentiment..\")\n\n path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'models', 'sentiment_tf.keras'))\n print(\"Found model at: \"+path)\n\n model = tf.keras.models.load_model(path,custom_objects={'KerasLayer': hub.KerasLayer})\n pred = [label2str(model.predict_classes([input])) for input in data]\n\n return {\"input\": data, \"pred\": pred}\n\n\n@app.route('/')\ndef my_form():\n return render_template('home.html')\n\n@app.route('/', methods=['POST'])\ndef my_form_post():\n text = request.form['text']\n file_name=text+'.txt'\n path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'call_transcripts', file_name))\n sentences = compute_inference.annotate(path)\n json_data = predict_online(sentences[\"data\"])\n return json_data\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"Assignment 2/Microservices Pipeline3/api/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"445877283","text":"import datetime\nfrom vigilant import config\nfrom threading import Thread\nfrom flask import Flask\nimport json\nimport numpy as np\n\nclass Monitor():\n def __init__(self):\n self.categories = {'default': {}}\n Thread(target=self.serve).start()\n\n def serve(self):\n ip = config['monitor']['address']\n port = config['monitor']['port']\n app = Flask(__name__)\n self.last = {}\n\n @app.route('/')\n def sample():\n result = {}\n for category in self.categories:\n for name, item in self.categories[category].items():\n result[name] = item['experiment']()\n result[name+'/min'] = item['min']\n result[name+'/max'] = item['max']\n self.last = result\n return json.dumps(result)\n\n @app.route('/last')\n def last_sample():\n return json.dumps(self.last)\n\n app.run(host=ip, port=port)\n\n def watch(self, experiment, name=None, category='default', bounds=[-np.inf, np.inf]):\n ''' Add a variable to be monitored actively (querying a method for new\n results with each measurement cycle).\n Args:\n experiment (callable): a function or other callable. Should take\n no arguments and return a numerical value.\n name (str): optional variable name. If None is passed, the default\n experiment.__name__ string is used.\n '''\n if name is None:\n name = experiment.__name__\n if category not in self.categories:\n self.categories[category] = {}\n field = category + '/' + name\n self.categories[category][field] = {'experiment': experiment, 'min': bounds[0], 'max': bounds[1]}\n","sub_path":"vigilant/http_monitor.py","file_name":"http_monitor.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"481273739","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 17 14:12:49 2015\n\n@author: prabu\n\"\"\"\n\nfrom __future__ import print_function\nimport os, os.path\nimport matplotlib.pyplot as plt\nfrom SdalReader import SdalReader\nfrom OverlapHandler import OverlapHandler\n\nif __name__ == \"__main__\":\n print(\"Testing the OverlapHandler class\")\n \n testdir = \"/home/prabu/mycode/sdal/tests_data/test_OverlapHandler\"\n \n \n signames = [\"gr082014_000.sig\", \"gr082014_001.sig\"]\n sigfiles = [os.path.join(testdir, \"input\", f) for f in signames]\n sigspec = [SdalReader().read_spectrum(f) for f in sigfiles]\n \n oh = OverlapHandler()\n ohdspec = [oh.process_overlap(s) for s in sigspec]\n \n #plot it to see if it looks correct\n fig1, axes1 = plt.subplots(nrows = 2, ncols = 1)\n for i in range(len(ohdspec)):\n axes1[i].set_xlim([300.0, 2600.0])\n axes1[i].set_ylim([0.0, 1.0])\n axes1[i].plot(ohdspec[i].wavelengths, \n ohdspec[i].reflectances + 0.1, \n color = 'g',\n alpha = 0.6,\n label = \"After overlap handling\")\n axes1[i].plot(sigspec[i].wavelengths, \n sigspec[i].reflectances, \n color = 'r',\n alpha = 0.6,\n label = \"Before overlap handling\")\n legend = axes1[i].legend(loc = 'upper center', shadow = True)\n fig1.suptitle(\"Spectra with and without overlap handling\")\n fig1.show()\n ","sub_path":"test_OverlapHandler.py","file_name":"test_OverlapHandler.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251344595","text":"from planner.models import Recipe\n\nfrom RecipeObject import RecipeObject\n\n# System Imports\nfrom datetime import datetime\nfrom random import randint\n\ndef todays_meals(assignments):\n\n # Find index of day of the week\n weekday = datetime.today().weekday()\n idx = weekday * 3\n recipe_attributes = []\n\n # Extract breakfast, lunch and dinner objects for today\n if assignments[idx] != '-1':\n break_object = RecipeObject(Recipe.objects.get(id=assignments[idx]))\n recipe_attributes.append({\"Breakfast\":break_object.get_attributes()})\n\n if assignments[idx+1] != '-1':\n lunch_object = RecipeObject(Recipe.objects.get(id=assignments[idx+1]))\n recipe_attributes.append({\"Lunch\":lunch_object.get_attributes()})\n\n if assignments[idx+2] != '-1':\n dinner_object = RecipeObject(Recipe.objects.get(id=assignments[idx+2]))\n recipe_attributes.append({\"Dinner\":dinner_object.get_attributes()})\n\n return recipe_attributes\n\ndef load_weeks(assignments):\n\n recipe_wks = []\n idx = 0\n\n for day in 2*[\"Mon\", \"Tues\", \"Wednes\", \"Thurs\", \"Fri\", \"Satur\", \"Sun\"]:\n curr_day = []\n for time in [\"Breakfast\", \"Lunch\", \"Dinner\"]:\n if assignments[idx] != '-1':\n rec = Recipe.objects.get(id=assignments[idx])\n curr_day.append((time, {\"name\":rec.name, \"id\":rec.id}))\n idx += 1\n recipe_wks.append((day + \"day\", curr_day))\n\n return recipe_wks\n\ndef get_recipes(times, recipes, pref):\n\n # Calculate total number of calories for week\n available_calories = sum([int(i) for i in times]) * 700\n\n if pref.diet == \"lose\":\n available_calories *= 1.1\n if pref.diet == \"gain\":\n available_calories *= 0.9\n\n # Remove recipes that don't meet users preferences\n recipes = [x for x in recipes if RecipeObject(x).meets_criteria(pref)]\n\n # Separate the recipes into breakfast and non-breakfast\n breakfasts = [x for x in recipes if \"breakfast\" in x.categories.lower()]\n regulars = [x for x in recipes if \"breakfast\" not in x.categories.lower()]\n\n if len(breakfasts) == 0 or len(regulars) == 0: return False\n\n for i in range(10000):\n\n assignments = []\n total_calories = 0.0\n\n for idx, time in enumerate(times):\n\n # If the person is having a meal\n if time == \"1\":\n\n # If the meal is breakfast\n if idx % 3 == 0:\n rand_idx = randint(0, len(breakfasts)-1)\n assignments.append(breakfasts[rand_idx].id)\n total_calories += breakfasts[rand_idx].kilocalories\n\n # If the meal is lunch or dinner\n else:\n rand_idx = randint(0, len(regulars)-1)\n assignments.append(regulars[rand_idx].id)\n total_calories += regulars[rand_idx].kilocalories\n\n else:\n assignments.append(-1)\n\n if available_calories*0.95 <= total_calories <= available_calories*1.05:\n return [str(i) for i in assignments]\n\n return False\n\ndef get_recipes_individual(recipes, pref, break_num, reg_num, calories):\n\n if pref.diet == \"lose\":\n calories *= 1.1\n if pref.diet == \"gain\":\n calories *= 0.9\n\n # Remove recipes that don't meet users preferences\n recipes = [x for x in recipes if RecipeObject(x).meets_criteria(pref)]\n\n # Separate the recipes into breakfast and non-breakfast\n breakfasts = [x for x in recipes if \"breakfast\" in x.categories.lower()]\n regulars = [x for x in recipes if \"breakfast\" not in x.categories.lower()]\n\n if len(breakfasts) == 0 or len(regulars) == 0: return False, False\n\n for _ in range(10000):\n\n break_ret, reg_ret = [], []\n total_calories = 0\n\n for _ in range(break_num):\n rand_idx = randint(0, len(breakfasts)-1)\n break_ret.append(breakfasts[rand_idx].id)\n total_calories += breakfasts[rand_idx].kilocalories\n\n for _ in range(reg_num):\n rand_idx = randint(0, len(regulars)-1)\n reg_ret.append(regulars[rand_idx].id)\n total_calories += regulars[rand_idx].kilocalories\n\n if calories*0.95 <= total_calories <= calories*1.05:\n return break_ret, reg_ret\n\n return False, False\n","sub_path":"Local/Meals.py","file_name":"Meals.py","file_ext":"py","file_size_in_byte":4307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"554948261","text":"# LC173 Binary Search Tree Iterator\n# Medium\n\n# Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.\n# Calling next() will return the next smallest number in the BST.\n\n\n# Note:\n# next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.\n# You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.\n\nfrom A02_TreeNode import *\n\n\n# Your BSTIterator object will be instantiated and called as such:\n# obj = BSTIterator(root)\n# param_1 = obj.next()\n# param_2 = obj.hasNext()\n\nclass BSTIterator(object):\n\n # Version A\n # Use traverse list\n # This will take O(n) space, n = number of nodes instead of O(h), h = height\n def __init__(self, root):\n \"\"\"\n :type root: TreeNode\n \"\"\"\n self.root = root\n self.flat = self.inOrderTraverse(root)\n\n def inOrderTraverse(self, root):\n if not root:\n return []\n return self.inOrderTraverse(root.left) + [root.val] + self.inOrderTraverse(root.right)\n\n def next(self):\n \"\"\"\n @return the next smallest number\n :rtype: int\n \"\"\"\n return self.flat.pop(0)\n\n def hasNext(self):\n \"\"\"\n @return whether we have a next smallest number\n :rtype: bool\n \"\"\"\n return bool(self.flat)\n\n\nclass BSTIterator(object):\n\n # Version B, O(h) memory.\n # Use stack, track one node in each depth\n # update the queue with all left branch to the bottom\n def __init__(self, root):\n \"\"\"\n :type root: TreeNode\n \"\"\"\n self.root = root\n self.que = []\n if root:\n self.que.append(root)\n self.updateQue()\n\n # Add from Leetcode LC230\n def kthSmallest(self, k):\n s = []\n rank = 0\n cur = self.root\n while s or cur:\n if cur:\n s.append(cur)\n cur = cur.left\n else:\n cur = s.pop()\n rank += 1\n if rank == k:\n return cur.val\n cur = cur.right\n return None\n\n def updateQue(self):\n if self.que:\n last = self.que[-1]\n while last:\n if last.left:\n self.que.append(last.left)\n last = last.left\n\n def next(self) -> int:\n \"\"\"\n @return the next smallest number\n \"\"\"\n\n if self.que:\n last = self.que[-1]\n next_val = last.val # first get return vanl as a temp\n\n # if there is a right branch, then replace the last node with right branch\n if last.right:\n self.que[-1] = last.right\n self.updateQue()\n # if there is no right branch, move one level above to parent node\n else:\n self.que.pop()\n\n return next_val\n\n def hasNext(self) -> bool:\n \"\"\"\n @return whether we have a next smallest number\n \"\"\"\n if self.que:\n return True\n else:\n return False\n\n\nif __name__ == \"__main__\":\n b0 = None\n iterator = BSTIterator(b0)\n assert not iterator.next(), \"Edge step 1\"\n assert not iterator.hasNext(), \"Edge step 2\"\n\n b1 = genTree([\n 7,\n 3, 15,\n None, None, 9, 20\n ])\n iterator = BSTIterator(b1)\n\n print(iterator.kthSmallest(3))\n\n assert iterator.next() == 3, \"Step 1\"\n assert iterator.next() == 7, \"Step 2\"\n assert iterator.hasNext(), \"Step 3\"\n\n assert iterator.next() == 9, \"Step 4\"\n assert iterator.hasNext(), \"Step 5\"\n\n assert iterator.next() == 15, \"Step 6\"\n assert iterator.hasNext(), \"Step 7\"\n\n assert iterator.next() == 20, \"Step 8\"\n assert not iterator.hasNext(), \"Step 9\"\n\n print(\"All passed\")\n","sub_path":"LeetCode/LC173_binary_search_tree_iterator.py","file_name":"LC173_binary_search_tree_iterator.py","file_ext":"py","file_size_in_byte":3921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75094401","text":"import os\nimport pandas as pd\nimport numpy as np\nimport heapq\nfrom rtree import index\nfrom sklearn.decomposition import PCA\nimport time\n\nclass KNN():\n dimension = 32;\n\n def __init__(self):\n self.encodings = pd.read_csv(\"encodings/all.txt\", header=None);\n # iloc para traer filas y columnas, like an matrix for data\n self.data = self.encodings.iloc[ : ,1:129];\n self.rtreeBuild();\n\n def rtreeBuild(self):\n p = index.Property();\n p.dimension = KNN.dimension;\n p.buffering_capacity = 5;\n p.dat_extension = 'data';\n p.idx_extension = 'index';\n self.idx = index.Index(properties=p);\n self.pca = PCA(n_components=KNN.dimension);\n self.pca_data = self.pca.fit_transform(self.data);\n for i in range(len(self.pca_data)):\n x = self.pca_data[i];\n self.idx.insert(i, (*x, *x));\n\n def knnSeqTest(self):\n # definir querys\n N = [5000,180,3258];\n Qx = [];\n for i in N:\n Qx.append(self.data.iloc[i]);\n dataT = self.data.drop(N, axis=0);\n\n #evaluar knnSearch\n for n_query in range(len(N)):\n for k in [2, 4, 8, 16, 32]:\n p1 = self.knnSearch(dataT, Qx[n_query], k)\n target = self.encodings.iloc[ N[n_query], 129 ]\n count = 0\n for i, d in p1:\n if target == self.encodings.iloc[i,129]:\n count +=1\n print(\"Elementos recuperados\", len(p1))\n print(\"Presicion: \", count/len(p1))\n print(self.encodings.iloc[[x for x, y in p1], 129])\n print(target)\n\n # evaluar knnSearchHeap\n for n_query in range(len(N)):\n for k in [2, 4, 8, 16, 32]:\n result = knnSearchHeap(dataT, Qx[n_query], k)\n target = self.encodings.iloc[N[n_query], 129]\n cont = 0\n for d,i in result:\n if target == self.encodings.iloc[i, 129]:\n cont += 1\n print(\"Precision:\", cont/len(result)) \n print(self.encodings.iloc[[x for y, x in result], 129])\n\n # definir la medida de distancia euclidiana\n @staticmethod\n def DE_l2(x, y):\n return sum((x - y)**2)**0.5;\n\n @staticmethod\n def DM_l1(x, y):\n return sum(abs(x - y));\n\n \"\"\"Algoritmo de busqueda KNN\"\"\"\n\n @staticmethod\n def knnSearch(data, Q, k):\n result = []\n for index, row in data.iterrows():\n d = KNN.DE_l2(Q, row)\n result.append((index, d))\n result.sort(key = lambda tup: tup[1])\n return result[:k]\n\n @staticmethod\n def knnSearchHeap(data, Q, k):\n result = [];\n for index, row in data.iterrows():\n d = KNN.DE_l2(Q, row);\n heapq.heappush(result, (-d, index));\n while len(result) > k:\n heapq.heappop(result);\n result = [ heapq.heappop(result) for _ in range(len(result)) ];\n result = list(reversed(result));\n return result;\n\n def knn(self, q, k):\n k = int(k);\n q_pca = self.pca.transform(np.array([q]))[0];\n start = time.time()\n res = list(self.idx.nearest(coordinates=(*q_pca, *q_pca), num_results=k));\n print(\"rtree time\", time.time() - start);\n start = time.time();\n self.knnSearchHeap(self.data, q, k);\n print(\"knn seq time\", time.time() - start);\n return [ path[1:-1] for path in self.encodings.iloc[res, 0] ];\n","sub_path":"backend/pc4.py","file_name":"pc4.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"35601539","text":"import csv\n\ninputList = []\nwith open('input/advent_input_02.txt') as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n for row in readCSV:\n inputList=row\n\ninputList = [int(i) for i in inputList]\nprint(inputList)\n\n#pre process the list\ninputList[1]=12\ninputList[2]=2\n\n#inputList = [1,9,10,3,2,3,11,0,99,30,40,50]\n#inputList = [1,1,1,4,99,5,6,0,99]\noperationDict={1:'Add', 2:'Multiply', 99:'Exit'}\n\nindex=0\noperation=operationDict.get(inputList[index])\nprint('First operation is: {0}'.format(operation))\n\nwhile not operation.capitalize() == 'Exit':\n parameterIndex1=inputList[index+1]\n parameterIndex2=inputList[index+2]\n resultIndex=inputList[index+3]\n \n if operation.upper() == 'ADD':\n inputList[resultIndex] = inputList[parameterIndex1]+inputList[parameterIndex2]\n elif operation.upper() == 'MULTIPLY':\n inputList[resultIndex] = inputList[parameterIndex1]*inputList[parameterIndex2]\n else:\n print('Unknown operation')\n\n print('{0} {1} {2} = {3}'.format(inputList[parameterIndex1],operation,inputList[parameterIndex2], inputList[resultIndex]))\n\n #Next operation\n index=index+4\n operation=operationDict.get(inputList[index])\n\nprint(inputList)\nprint('First value: {0}'.format(inputList[0]))","sub_path":"advent_02_2019.py","file_name":"advent_02_2019.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"550852976","text":"import hszinc\nfrom hszinc.datatypes import BasicQuantity\nimport json\nfrom pyhaystack.client.niagara import Niagara4HaystackSession\nfrom typing import Any, Dict, List\n\nfrom config import logger\nfrom config import current_config as config\n\nfrom common.constants import N4_TIMEOUT, REDIS_EXPIRE\nfrom data.cache.redis_cache import RedisCache # type: ignore\nfrom models.point import Point\n\n\nsession = Niagara4HaystackSession(\n uri=config.NIAGARA4_SERVER,\n username=config.NIAGARA4_USERNAME,\n password=config.NIAGARA4_PASSWORD,\n http_args=dict(tls_verify=False, debug=True),\n pint=False,\n)\nsession._grid_format = hszinc.MODE_ZINC\n\n\nrcache = RedisCache.get_instance()\n\n\ndef get_site(site_name: str) -> Any:\n \"\"\"\n return a site by name\n site_name example: S.~31430Broadway.elecMeter\n \"\"\"\n op = session.get_entity(site_name, refresh=True)\n op.wait()\n site = op.result\n return site\n\n\ndef get_site_data(entity_name: str, refresh: bool = False) -> Dict[Any, Any]:\n \"\"\"\n Return current value and type of entity.\n Throws error if correct site name is not passed.\n \"\"\"\n if refresh:\n cached = None\n else:\n cached = rcache.get(entity_name)\n\n if cached:\n # got value from cache\n ret = json.loads(cached) # type: Dict[str, Any]\n return ret\n else:\n # no value in cache or skipped cache, get value from N4\n entity = get_site(entity_name)\n data = dict(value=entity.tags.get(\"curVal\"), type=entity.tags.get(\"kind\"),)\n if isinstance(data[\"value\"], BasicQuantity):\n data[\"value\"] = data[\"value\"].value\n stored_val = json.dumps(data)\n rcache.set(entity_name, stored_val)\n rcache.expire(entity_name, REDIS_EXPIRE)\n\n return data\n\n\ndef invoke_action(entity: str, val: Any) -> Any:\n \"\"\"\n Perform session invoke action operation on entity and return Grid\n Throws error if correct entity or value is not passed.\n \"\"\"\n\n resp = session.invoke_action(entity, \"set\", val=val)\n result = hszinc.dump(resp.result, hszinc.MODE_JSON)\n # update_point_val_and_kind(entity)\n return result\n\n\ndef change_mode(entity: str, val: Any) -> Any:\n \"\"\"\n sets the value for a given entity and returns the result.\n Throws error if correct entity or value is not passed.\n \"\"\"\n updated_data = invoke_action(entity, val)\n return updated_data\n\n\ndef get_all_sites() -> Any:\n \"\"\"\n returns all the sites we have\n \"\"\"\n return session.sites\n\n\ndef get_history_for_device(\n device_name: str, rng: str = \"today\"\n) -> List[Dict[Any, Any]]:\n \"\"\"\n example device: 'S.~3575Madison.elecMeter.currentBuilding_Demand'\n \"\"\"\n op = session.his_read(device_name, rng=rng)\n op.wait()\n site = op.result\n formatted_data = _format_data(site)\n return formatted_data\n\n\ndef get_history_for_point(point_path: str, rng: str = \"today\") -> List[Dict[Any, Any]]:\n \"\"\"\n example device: 'S.~3575Madison.elecMeter.currentBuilding_Demand'\n \"\"\"\n logger.info(f\"update_niagara4_device_history - calling N4 for {point_path}\")\n op = session.his_read(point_path, rng=rng)\n proper_return = op.wait(timeout=N4_TIMEOUT)\n logger.info(f\"update_niagara4_device_history - done calling N4 for {point_path}\")\n site = op.result\n formatted_data = _format_data(site)\n return formatted_data\n\n\ndef _format_data(site: Any) -> List[Dict[Any, Any]]:\n formatted_data = []\n point_name = site.metadata[\"id\"].name\n point = Point.get_point_by_path(point_name)\n for row in site._row:\n if point:\n formatted_data.append(\n dict(point_id=point.id, ts=row[\"ts\"], quantity=row[\"val\"].value,)\n )\n else:\n logger.error(f\"couldn't find point by name {point_name}\")\n return formatted_data\n\n\ndef fetch_points_from_n4() -> List[Point]:\n \"\"\"\n Return all the points fetched from niagara4 API\n \"\"\"\n try:\n points = session.find_entity(\"point\")\n point_results = points.result\n point_values = list(point_results.values())\n return point_values\n except Exception as error:\n logger.error(\"Unable to fetch points form Niagara.\", error)\n return list()\n","sub_path":"services/niagara4_service.py","file_name":"niagara4_service.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"596474170","text":"import sys\r\n\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtCore import *\r\n\r\nfrom parvis_gui import *\r\nfrom ParvisLib import *\r\n\r\nclass XWindow(Ui_MainWindow):\r\n def __init__(self,window):\r\n Ui_MainWindow.__init__(self)\r\n self.setupUi(window)\r\n self.edit_PW.returnPressed.connect(self.login)\r\n self.edit_ID.returnPressed.connect(self.login)\r\n\r\n self.edit_search.returnPressed.connect(lambda : self.search(self.edit_search.text()))\r\n\r\n self.edit_rsearch.returnPressed.connect(lambda : self.search(self.edit_rsearch.text()))\r\n self.btn_IPC.clicked.connect(self.equation)\r\n\r\n self.window = window\r\n self.buttons=[]\r\n self.mids=[]\r\n self.checkBox = [[]]\r\n self.dialogs=[]\r\n self.uis=[]\r\n self.w_ids = []\r\n #15 텔레비전, 16 주변, 17 장치, 18 리모콘, 19 스피커\r\n self.ipc = {15 : ['A63F 13/338'],16:['H04R 7/18'],17:['G06F 9/00'],18:['F21V 21/15'],19:['G11B','H04']}\r\n self.explain = {15:['텔레비전 네트워크를 이용하는 것'],\r\n 16:['주변부에 있어서의 것'],\r\n 17:['프로그램제어를 위한 장치, 예. 제어장치(주변장치를 위한 프로그램제어 13/10)'],\r\n 18:['전원동작을 위해 특별히 채용된 것, 예. 리모트콘트롤'], \r\n 19:['기계적 공진 발생기, 예. 현 또는 타격장치를 사용 하여 그들 음을 전기기계변환기에 의하여 픽업하고 그 전기신호를 다시 처리 또는 증폭하고 그 후 스피커 또는 동등의 장치에 의하여 음으로 변환하는 것',\r\n '원격제어 또는 원격 측정시스템에서 주국에서 제어 신호를 적용하거나 측정값을 획득하는것으로 선택되는 소망 장치인 종국을 선택적으로 호출하기 위한 배치']}\r\n \r\n\r\n def login(self):\r\n userid = self.edit_ID.text()\r\n userpw = self.edit_PW.text()\r\n if userid and userpw :\r\n self.stackedWidget.setCurrentIndex(1)\r\n \r\n #search\r\n def search(self,inp):\r\n #초기화\r\n self.buttons=[]\r\n self.mids = []\r\n self.checkBox =[[]]\r\n self.dialogs = []\r\n self.uis = []\r\n self.w_ids = []\r\n #inp은 edit에 있는 텍스트\r\n word_list = inp.split(' ')\r\n mwords = MainWord(word_list)\r\n word_ids = mwords.main_id\r\n self.stackedWidget.setCurrentIndex(2)\r\n self.edit_rsearch.setText(inp)\r\n i=0\r\n j=0\r\n k=0\r\n self.w_ids = self.choose(word_ids)\r\n #버튼들 추가\r\n for w_id in self.w_ids:\r\n self.mids.append(MainID(w_id))\r\n k = i % 10\r\n if not k:\r\n j += 1\r\n self.buttons += [QPushButton(self.mids[i].main_word)]\r\n sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\r\n sizePolicy.setHorizontalStretch(1)\r\n sizePolicy.setVerticalStretch(1)\r\n sizePolicy.setHeightForWidth(self.buttons[i].sizePolicy().hasHeightForWidth())\r\n self.buttons[i].setSizePolicy(sizePolicy)\r\n font = QFont()\r\n font.setFamily(\"Agency FB\")\r\n font.setPointSize(14)\r\n self.buttons[i].setFont(font)\r\n self.buttons[i].setAutoRepeatDelay(300)\r\n self.layout_mword.addWidget(self.buttons[i],j,i%10)\r\n i += 1\r\n frame = QFrame()\r\n self.layout_mword.addWidget(frame,j,10)\r\n #검색식 업데이트\r\n self.equation_IPC()\r\n self.explain_IPC()\r\n self.create_check()\r\n\r\n def equation(self): \r\n subs=[]\r\n i=0\r\n for w_id in self.w_ids:\r\n subs.append('(')\r\n subs.append('+'.join(self.mids[i].sub_words))\r\n subs.append(')')\r\n if i 1:\r\n w_ids.append(word_id[0])\r\n else :\r\n w_ids.append('')\r\n return w_ids\r\n\r\n def open_check(self):\r\n sender = self.window.sender()\r\n for i in range(len(self.w_ids)):\r\n if sender == self.buttons[i]:\r\n button = self.buttons[i]\r\n dialog = self.dialogs[i]\r\n break\r\n x_pos = button.x()\r\n y_pos = button.y()\r\n dx = button.width()\r\n dy = button.height() \r\n dialog.move(button.rect().bottomLeft())\r\n dialog.show()\r\n subs = self.mids[i].sub_words\r\n for j in range(len(subs)):\r\n self.checkBox[i][j].stateChanged.connect(lambda : self.change_check(i))\r\n \r\n def change_check(self, i):\r\n sender = self.window.sender()\r\n subs = self.mids[i].sub_words\r\n for j in range(len(subs)):\r\n if sender == self.checkBox[i][j]:\r\n checkBox = self.checkBox[i][j]\r\n break\r\n print(sender)\r\n if checkBox.isChecked():\r\n self.mids[i].sub_words.append(sender.text())\r\n else:\r\n self.mids[i].sub_words.remove(sender.text())\r\n self.equation()\r\n\r\n def create_check(self):\r\n for i in range(len(self.w_ids)):\r\n mid = self.mids[i]\r\n subs = mid.sub_words\r\n _translate = QtCore.QCoreApplication.translate\r\n\r\n self.dialogs.append(QDialog())\r\n dialog = self.dialogs[i]\r\n self.uis.append(Ui_check_mword())\r\n ui = self.uis[i]\r\n ui.setupUi(dialog)\r\n self.checkBox.append([])\r\n for j in range(len(subs)):\r\n self.checkBox[i].append(QCheckBox(ui.scrollAreaWidgetContents))\r\n self.checkBox[i][j].setChecked(True)\r\n self.checkBox[i][j].setObjectName(subs[j])\r\n self.checkBox[i][j].setText(_translate(\"check_mword\", subs[j]))\r\n ui.verticalLayout.addWidget(self.checkBox[i][j])\r\n self.buttons[i].clicked.connect(self.open_check)\r\n \r\nif __name__ == \"__main__\" :\r\n app = QApplication(sys.argv)\r\n window = QMainWindow()\r\n main_dialog = XWindow(window)\r\n window.show()\r\n app.exec_()\r\n","sub_path":"parvis.py","file_name":"parvis.py","file_ext":"py","file_size_in_byte":7838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"444996276","text":"import importlib\nimport logging\n\nfrom django.conf import settings\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import GenericViewSet\n\nfrom .models import Statement\nfrom .serializers import StatementCreateSerializer, StatementSerializer\n\nlogger = logging.getLogger(__name__)\n\n\nclass ChatbotViewSet(GenericViewSet):\n\n def get_serializer_class(self):\n if self.action == 'create':\n return StatementCreateSerializer\n else:\n return StatementSerializer\n\n def get_logic_adapter_class(self):\n module_name, class_name = settings.LOGIC_ADAPTER.rsplit('.', 1)\n return getattr(importlib.import_module(module_name), class_name)\n\n def list(self, request, *args, **kwargs):\n statement = {\n 'id': None,\n 'message': None,\n 'reply': settings.REPLIES.get('initial'),\n }\n\n serializer = StatementSerializer(statement)\n return Response(serializer.data)\n\n def create(self, request, *args, **kwargs):\n serializer = StatementCreateSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n\n message = serializer.data.get('message')\n in_response_to = serializer.data.get('in_response_to')\n if in_response_to is not None:\n parent = Statement.objects.get(pk=in_response_to)\n parent_reply = parent.reply\n else:\n parent = None\n parent_reply = None\n\n logger.debug('message=\"%s\"', message)\n logger.debug('parent=\"%s\" (pk=%s)', parent_reply, in_response_to)\n\n logic_adapter_class = self.get_logic_adapter_class()\n logic_adapter = logic_adapter_class()\n\n logger.debug('logic_adapter_class=\"%s\"', logic_adapter_class.__name__)\n\n # filter a statement that respond to the last statement\n statements = Statement.objects.filter(parent=parent)\n response, similarity = logic_adapter.process(message, statements)\n response_message = response.message if response else None\n\n if similarity < settings.LOGIC_THRESHOLD:\n logger.warning('no response found for message=\"%s\" in response to parent=\"%s\", best guess was message=\"%s\" (similarity=%0.3f)',\n message, parent_reply, response_message, similarity)\n\n response = {\n 'id': in_response_to,\n 'message': None,\n 'reply': settings.REPLIES.get('unknown'),\n }\n\n else:\n logger.info('message=\"%s\" matched \"%s\" (similarity=%0.3f)', message, response_message, similarity)\n logger.debug('reply=\"%s\"', response.reply)\n\n if not response.children.exists() and not response.conclusion and not response.forward:\n response.conclusion = settings.REPLIES.get('conclusion')\n\n if response.forward:\n try:\n response.forward = Statement.objects.get(reference=response.forward)\n\n if not response.forward.children.exists() and not response.forward.conclusion and not response.forward.forward:\n response.forward.conclusion = settings.REPLIES.get('conclusion')\n\n except Statement.DoesNotExist:\n pass\n\n # return the first statement\n serializer = StatementSerializer(response)\n return Response(serializer.data)\n","sub_path":"chat/viewsets.py","file_name":"viewsets.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76209953","text":"import pymongo\r\ncon=pymongo.MongoClient('127.0.0.1',27017)\r\ncoll=con['parseconfig']['parsers']\r\n\r\nparsers=coll.find()[45]['WindowsParsers']\r\nfor p in parsers:\r\n parsers.pop(0)\r\n for c in p['Conditions']:\r\n for p1 in parsers:\r\n if p1['Name']!=p['Name'] and c in p1['Conditions'] and (p1['Name'].startswith('raw') or p['Name'].startswith(\"raw\")):\r\n print(c,p['Name'],p1['Name'])\r\n","sub_path":"scripts/test7.py","file_name":"test7.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"329321482","text":"# coding: utf-8\nfrom __future__ import print_function\n\nimport numpy as np\nfrom numpy.linalg import pinv\nfrom matplotlib import pyplot as plot\n\nfrom gradient_descent_single import gradient_descent\n\n# --- 正規方程式(多特徴) ---\n# 家を売った際の値段を予測する為\n# 広さ(x1)と部屋数(x2)から売値(y)を予測する\n#\n# - 特徴数がだいたい10000以下なら早い\n# - 学習率が必要ない\n\ndef normal_equation(X, y):\n return pinv(X.T.dot(X)).dot(X.T).dot(y)\n\n\nif __name__ == '__main__':\n # データのロード、変数の初期化\n data = np.loadtxt('../../machine-learning-ex1/ex1/ex1data2.txt', delimiter=',')\n X = data[:, 0:2]\n y = data[:, 2]\n m = X.shape[0]\n X = np.concatenate((np.ones((m, 1)), X), axis=1)\n\n # 正規方程式(Normal equation) だいたい10000特徴以下なら早い\n theta = normal_equation(X, y)\n size = 1650\n rooms = 3\n x = np.array([[1.0, size, rooms]])\n price = x.dot(theta)[0]\n\n print(\"広さ{size}で{rooms}部屋の家売値予測値は{price}です。\".format(\n size=size,\n rooms=rooms,\n price=price\n ))\n","sub_path":"workspace/coursera/python/ex1_regression/normal_equation.py","file_name":"normal_equation.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"338141712","text":"import os\nfrom typing import Generator\n\nimport pytest\n\nfrom kolga.libs.helm import Helm\nfrom kolga.libs.kubernetes import Kubernetes\n\n\n@pytest.fixture() # type: ignore\ndef kubernetes() -> Kubernetes:\n return Kubernetes()\n\n\n@pytest.fixture() # type: ignore\ndef helm() -> Generator[Helm, None, None]:\n helm = Helm()\n yield helm\n try:\n helm.remove_repo(\"stable\")\n except Exception:\n pass\n\n\n@pytest.fixture() # type: ignore\ndef test_namespace(kubernetes: Kubernetes) -> Generator[str, None, None]:\n namespace = kubernetes.create_namespace()\n yield namespace\n kubernetes.delete_namespace()\n\n\ndef pytest_sessionstart(session: pytest.Session) -> None:\n \"\"\"\n Called after the Session object has been created and\n before performing collection and entering the run test loop.\n \"\"\"\n if os.environ.get(\"TEST_CLUSTER_ACTIVE\", 0) not in [1, \"1\", True, \"True\"]:\n raise Exception(\n \"Kubernetes test cluster sanity check failed. Please make sure \"\n \"you are using a testing cluster and not production\"\n )\n","sub_path":"conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"406831189","text":"#!/usr/bin/python\nfrom bs4 import BeautifulSoup\nimport urllib.request\nimport sys\nimport subprocess\nimport os.path\n\nparser = 'html.parser'\n\nif len(sys.argv) == 1:\n print('Provide url of show as first program argument.')\nelse:\n url = sys.argv[1]\n html_doc = urllib.request.urlopen(url).read()\n \n soup = BeautifulSoup(html_doc, parser)\n\n urls = []\n episode_n = []\n episode_title = []\n\n # extract all urls from page\n for link in soup.findAll('a', { 'class' : 'episode' }):\n urls.append(link.get('href'))\n\n episodes = soup.find('ul', { 'class' : 'list-of-seasons' })\n for p in episodes.findAll('span', { 'class' : 'series-title block ellipsis' }):\n episode_n.append(p.get_text().strip())\n\n for p in episodes.findAll('p', { 'class' : 'short-desc' }):\n episode_title.append(p.get_text().strip())\n\n urls = list(reversed(urls))\n episode_n = list(reversed(episode_n))\n episode_title = list(reversed(episode_title))\n\n for i in range(1, len(urls) + 1):\n spacing = ': ' if episode_title[i - 1] != '' else ' '\n print(str(i) + '. ' + episode_n[i - 1] + spacing + episode_title[i - 1])\n\n while True:\n n = input('Choose an episode [1-' + str(len(urls)) + '] or q to end: ')\n\n if n == 'q':\n break\n elif n.isdigit() and int(n) in range(1, len(urls) + 1):\n episode_url = 'http://www.crunchyroll.com' + urls[int(n) - 1]\n null = open(os.devnull, 'w')\n subprocess.check_call(['livestreamer', '-p', 'mpv --cache 8192', '--player-continuous-http', episode_url, 'ultra'])\n else:\n print('Enter valid option (1-' + str(len(urls)) + ', q).')\n\n","sub_path":"crunchyviewer.py","file_name":"crunchyviewer.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"411858235","text":"def dfs(tickets, here, is_visit, cnt):\n n = len(tickets)\n route = [here]\n\n if n == cnt:\n return (route, True)\n\n for idx in range(n):\n (a, b) = tickets[idx]\n if (a == here) and (is_visit[idx] == False):\n is_visit[idx] = True\n (path, res) = dfs(tickets, b, is_visit, cnt+1)\n\n if res == True:\n return (route + path, True)\n \n is_visit[idx] = False\n \n return (route, False)\n \ndef solution(tickets):\n start = \"ICN\"\n is_visit = [ False for _ in tickets ]\n tickets = sorted(tickets)\n (answer, res) = dfs(tickets, start, is_visit, 0)\n return answer if res else None\n\nif __name__ == '__main__':\n \n tickets = [[\"ICN\", \"SFO\"], [\"ICN\", \"ATL\"], [\"SFO\", \"ATL\"], [\"ATL\", \"ICN\"], [\"ATL\", \"SFO\"]] \n #[[\"ICN\", \"JFK\"], [\"JFK\", \"ABC\"], [\"JFK\", \"DEF\"], [\"ABC\", \"JFK\"] ]\n print(solution(tickets))","sub_path":"programmers/ch08_dfs_and_bfs/python/sol04_trip_route.py","file_name":"sol04_trip_route.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389110251","text":"import wikipedia\nimport sys\nimport argparse\nimport urllib.request\nimport json\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"search\", help=\"The article you search\")\nparser.add_argument(\"random\", action=\"store_true\", help=\"type random to get a random article\")\nparser.add_argument(\"--lang\", \"-l\", type=str, help=\"choose language\")\nparser.add_argument(\"--full\", \"-f\", action=\"store_true\", help=\"if sets, display the full page\")\nparser.add_argument(\"--link\", action=\"store_true\", help=\"if sets, display the link of the article at the end\")\nargs = parser.parse_args()\n\nlang = \"en\"\n\nif args.lang:\n\twikipedia.set_lang(args.lang)\n\tlang = args.lang\n\nif args.search == \"random\":\n\turl = \"https://\"+lang+\".wikipedia.org/api/rest_v1/page/random/title\"\n\treq = urllib.request.Request(url)\n\tr = urllib.request.urlopen(req).read()\n\tcont = json.loads(r.decode(\"utf-8\"))\n\tsubject=cont[\"items\"][0]['title']\nelse:\n\tsubjectList = wikipedia.search(args.search)\n\tsubject = subjectList[0]\n\ntry:\n\tp = wikipedia.page(subject, auto_suggest=False)\n\tprint(\"====== \"+p.title+\" ======\")\n\tif args.full:\n\t\tprint(p.content)\n\telse:\n\t\tprint(p.summary)\n\tif args.link:\n\t\ttitle = p.title\n\t\ttitle = title.replace(\" \", \"_\")\n\t\tprint(title)\n\t\tprint(\"https://\"+lang+\".wikipedia.org/wiki/\"+title)\n\t\nexcept wikipedia.exceptions.DisambiguationError as e:\n\tprint(\"Too Many results, be more specific\")\n\tprint(e)\n","sub_path":"wicli.py","file_name":"wicli.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"26995055","text":"# Game states\nGAME_STATE_CREATED = 1\nGAME_STATE_STARTED = 2\nGAME_STATE_FINISHED = 3\n\n# Turn states\nSELECTING_ACTION = 1\nMOVING_CHARACTER = 2\nMAKING_SUGGESTION = 3\nWAITING_ON_SUGGESTION = 4\nREFUTING_SUGGESTION = 5\nMAKING_ACCUSATION = 6\n\n\n\n# IDs for queries (still have to manually change in AJAX command)\nGET_VALID_MOVES = 'get-valid-moves'\nSELECT_ACCUSATION_CARDS = 'select-accusation-cards'\nMAKE_ACCUSATION = 'make-accusation'\nSELECT_SUGGESTION_CARDS = 'select-suggestion-cards'\nMAKE_SUGGESTION = 'make-suggestion'\n","sub_path":"clueless/game/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"496069464","text":"from types import SimpleNamespace\nfrom .topology import Topology\nfrom .non_bonded import NonBonded\n\nfrom abc import ABC, abstractmethod\n#\nimport numpy as np\n#\nfrom .storage import TermStorage, MultipleTermStorge\n\n\nclass TermABC(ABC):\n \"\"\"Represents a ForceField term.\"\"\"\n\n __slots__ = ('atomids', 'equ', 'idx', 'fconst', '_typename', '_name', 'n_params')\n\n name = 'NOT_NAMED'\n\n def __init__(self, atomids: list[int], equ: float, typename: str, n_params: int,\n fconst: np.ndarray=None):\n \"\"\"Initialization of a term.\n\n Keyword arguments\n -----------------\n atomids : list[int]\n List containing the atom IDs which participate in the term\n equ : float\n Equilibrium for the term\n typename : str\n Representation of the atoms involved in the term and their bonds\n n_params : int\n The number of customizable parameters/constants which the term involves\n fconst : np.ndarray[float](n_params,) (default None)\n Values for the term constants\n \"\"\"\n self.atomids = np.array(atomids)\n self.equ = equ\n self.idx = 0\n self.fconst = fconst\n self.n_params = n_params\n self.typename = typename\n self._name = f\"{self.name}({typename})\"\n\n def __repr__(self) -> str:\n return self._name\n\n def __str__(self) -> str:\n return self._name\n\n def set_idx(self, idx: int) -> None:\n \"\"\"Set a new ID for the term.\n\n Keyword arguments\n -----------------\n idx : int\n The new ID\n\n Returns\n -------\n None\n \"\"\"\n self.idx = idx\n\n def do_force(self, crd: np.ndarray, force: np.ndarray) -> float:\n \"\"\"Force calculation with given geometry.\n\n Keyword arguments\n -----------------\n crd : np.ndarray[float](n_atoms, 3)\n XYZ coordinates for each atom in the molecule\n force : np.ndarray[float](n_atoms, 3)\n XYZ forces for each atom in the molecule\n\n Returns\n -------\n The potential energy generated by the term (float)\n \"\"\"\n return self._calc_forces(crd, force, self.fconst)\n\n def do_fitting(self, crd: np.ndarray, forces: np.ndarray, index: int=0,\n params: np.ndarray=None) -> None:\n \"\"\"Compute fitting contributions. If params are provided, they will be used for the\n constants. If not, unit parameters will be used to compute contribution.\n\n Keyword arguments\n -----------------\n crd : np.ndarray[float](n_atoms, 3)\n XYZ coordinates for each atom in the molecule\n forces : np.ndarray[float](n_atoms, 3)\n XYZ forces for each atom in the molecule\n index : int (default 0)\n index to start taking constants from \n params : np.ndarray[flaot](sum of n_params for each term to be fit,) (default None)\n stores all parameters for the terms to be fit\n\n Returns\n -------\n None\n \"\"\"\n if params is None: # Linear least squares\n self._calc_forces(crd, forces[self.idx], np.ones(self.n_params))\n else: # Non-linear least squares\n self._calc_forces(crd, forces[self.idx], params[index:index+self.n_params])\n\n @abstractmethod\n def _calc_forces(self, crd: np.ndarray, force: np.ndarray, fconst: np.ndarray) -> float:\n \"\"\"Perform actual force computation.\n\n Keyword arguments\n -----------------\n crd : np.ndarray[float](n_atoms, 3)\n XYZ coordinates for each atom in the molecule\n force : np.ndarray[float](n_atoms, 3)\n XYZ forces for each atom in the molecule\n fconst : np.ndarray[float](n_params,)\n the values for the term constants\n\n Returns\n -------\n The potential energy generated by the term (float)\n \"\"\"\n\n @classmethod\n def get_terms_container(cls):\n return TermStorage(cls.name)\n\n def __eq__(self, other):\n if isinstance(other, str):\n return other == self._name\n if isinstance(other, TermABC):\n return str(other) == self._name\n else:\n raise Exception(\"Cannot compare Term with\")\n\n def __ne__(self, other):\n if isinstance(other, str):\n return other != self._name\n if isinstance(other, TermABC):\n return str(other) != self._name\n else:\n raise Exception(\"Cannot compare Term with\")\n\n\nclass TermFactory(ABC):\n \"\"\"Factory class to create ForceField Terms of one or multiple TermABC classes.\"\"\"\n\n _term_types = None\n _multiple_terms = True\n name = \"NAME_NOT_DEFINED\"\n\n @classmethod\n def get_terms_container(cls):\n if cls._multiple_terms is False:\n return TermStorage(cls.name)\n return MultipleTermStorge(cls.name, {key: value.get_terms_container()\n for key, value in cls._term_types.items()})\n\n @classmethod\n @abstractmethod\n def get_terms(cls, topo: Topology, non_bonded: NonBonded,\n config: SimpleNamespace) -> list:\n \"\"\"Get the terms of the current class based on molecule data.\n\n Keyword arguments\n -----------------\n topo : Topology\n Stores all topology information\n non_bonded : NonBonded object\n Stores all non bonded interaction information\n config : SimpleNamespace\n Stores the global config settings\n\n Returns\n -------\n list of cls objects\n \"\"\"\n ...\n\n\nclass TermBase(TermFactory, TermABC):\n \"\"\"Base class for terms that are TermFactories for themselves as well\"\"\"\n _multiple_terms = False\n","sub_path":"qforce/molecule/baseterms.py","file_name":"baseterms.py","file_ext":"py","file_size_in_byte":5949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"371857341","text":"\r\n\r\ndef mousePressed():\r\n global platforms\r\n platforms = []\r\n starter_platform = platform([100, 700])\r\n platforms.append(starter_platform)\r\n global p1\r\n p1 = player()\r\n loop()\r\n\r\ndef setup():\r\n #global setup options\r\n size(500, 800)\r\n rectMode(CENTER)\r\n background(255)\r\n \r\n #list of platforms\r\n global platforms\r\n platforms = []\r\n starter_platform = platform([100, 700])\r\n platforms.append(starter_platform)\r\n global p1\r\n p1 = player()\r\n \r\ndef draw():\r\n frameRate(30)\r\n background(255)\r\n for platform in platforms:\r\n platform.display()\r\n p1.update(platforms)\r\n platform_manager(platforms)\r\n \r\n #this ends the game if the player falls off the screen\r\n if p1.ypos > height+25:\r\n background(0)\r\n fill(255, 255, 255)\r\n textAlign(CENTER, CENTER)\r\n textSize(80)\r\n text(\"GAME\", width/2, 2*height/10)\r\n text(\"OVER\", width/2, 3*height/10)\r\n textSize(40)\r\n text(\"Score: \"+str(p1.score/100), width/2, 5*height/10)\r\n text(\"Retry: [CLICK]\", width/2, 7*height/10)\r\n text(\"Exit: [ESC]\", width/2, 8*height/10)\r\n textAlign(LEFT)\r\n noLoop()\r\n \r\n\r\n \r\n\r\n \r\n \r\n","sub_path":"sketch_180929c.pyde","file_name":"sketch_180929c.pyde","file_ext":"pyde","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58170267","text":"__author__ = 'Veselin Karamanski'\r\n\r\nimport sys\r\nimport os\r\nfrom PyQt4 import QtCore, QtGui\r\nfrom PyQt4.QtCore import Qt\r\nfrom PyQt4.QtGui import QMenu\r\nfrom PyQt4.Qsci import QsciScintilla, QsciScintillaBase\r\n\r\ntry:\r\n _fromUtf8 = QtCore.QString.fromUtf8\r\nexcept AttributeError:\r\n def _fromUtf8(s):\r\n return s\r\n\r\ntry:\r\n _encoding = QtGui.QApplication.UnicodeUTF8\r\n def _translate(context, text, disambig):\r\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\r\nexcept AttributeError:\r\n def _translate(context, text, disambig):\r\n return QtGui.QApplication.translate(context, text, disambig)\r\n\r\nclass TakeNote(object):\r\n def setupUi(self):\r\n\r\n############# CREATING MENU START ####################\r\n self.actionNew = QtGui.QAction('New', self)\r\n self.actionNew.setShortcut('Ctrl+N')\r\n self.actionNew.setStatusTip('Create new file')\r\n\r\n self.actionOpen = QtGui.QAction('Open', self)\r\n self.actionOpen.setShortcut('Ctrl+O')\r\n self.actionOpen.setStatusTip('Open a file')\r\n\r\n closeAction = QtGui.QAction('Close', self)\r\n closeAction.setShortcut('Ctrl+Q')\r\n closeAction.setStatusTip('Close')\r\n closeAction.triggered.connect(self.close)\r\n\r\n self.wordWrapModeAction = QtGui.QAction('Word wrap', self, checkable=True)\r\n self.showLineNumbersAction = QtGui.QAction('Show line numbers', self, checkable=True)\r\n\r\n self.editUndoAction = QtGui.QAction('Undo', self)\r\n self.editUndoAction.setShortcut('Ctrl+Z')\r\n self.editRedoAction = QtGui.QAction('Redo', self)\r\n self.editRedoAction.setShortcut('Ctrl+Y')\r\n\r\n self.treeAddNodeAction = QtGui.QAction('Add Node', self)\r\n self.treeAddNodeAction.setShortcut('Ctrl+T')\r\n self.treeAddSubNodeAction = QtGui.QAction('Add Subode', self)\r\n self.treeAddSubNodeAction.setShortcut('Ctrl+Shift+T')\r\n\r\n self.searchAction = QtGui.QAction('Find', self)\r\n self.searchAction.setShortcut('Ctrl+F')\r\n self.treeAddNodeAction.setShortcut('Ctrl+T')\r\n\r\n self.aboutAction = QtGui.QAction('About', self)\r\n\r\n menubar = self.menuBar()\r\n\r\n fileMenu = menubar.addMenu('&File')\r\n fileMenu.addAction(self.actionNew)\r\n fileMenu.addAction(self.actionOpen)\r\n fileMenu.addAction(closeAction)\r\n\r\n editMenu = menubar.addMenu('&Edit')\r\n editMenu.addAction(self.editUndoAction)\r\n editMenu.addAction(self.editRedoAction)\r\n\r\n self.viewMenu = menubar.addMenu('&Search')\r\n self.viewMenu.addAction(self.searchAction)\r\n\r\n self.viewMenu = menubar.addMenu('&View')\r\n self.viewMenu.addAction(self.wordWrapModeAction)\r\n self.viewMenu.addAction(self.showLineNumbersAction)\r\n\r\n treeMenu = menubar.addMenu('&Tree')\r\n treeMenu.addAction(self.treeAddNodeAction)\r\n treeMenu.addAction(self.treeAddSubNodeAction)\r\n\r\n helpMenu = menubar.addMenu('&Help')\r\n helpMenu.addAction(self.aboutAction)\r\n############# CREATING MENU END ####################\r\n\r\n############# CREATING WIDGETS START ####################\r\n #self.resize(800, 600)\r\n self.splitter = QtGui.QSplitter()\r\n self.setCentralWidget(self.splitter)\r\n self.vbox = QtGui.QVBoxLayout(self.splitter)\r\n\r\n ### CREATE TREE WIDGET START ###\r\n self.treeWidget = QtGui.QTreeWidget(self)\r\n self.treeWidget.headerItem().setText(0, \"Tree\")\r\n self.vbox.addWidget(self.treeWidget)\r\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\r\n sizePolicy.setHorizontalStretch(25)\r\n sizePolicy.setVerticalStretch(0)\r\n sizePolicy.setHeightForWidth(self.treeWidget.sizePolicy().hasHeightForWidth())\r\n self.treeWidget.setSizePolicy(sizePolicy)\r\n treeFont = QtGui.QFont()\r\n treeFont.setPointSize(10)\r\n self.treeWidget.setFont(treeFont)\r\n ### CREATE TREE WIDGET STOP ###\r\n\r\n ### CREATE TEXT EDIT START ###\r\n self.textEdit = QsciScintilla(self)\r\n self.vbox.addWidget(self.textEdit)\r\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\r\n sizePolicy.setHorizontalStretch(60)\r\n sizePolicy.setVerticalStretch(0)\r\n sizePolicy.setHeightForWidth(self.textEdit.sizePolicy().hasHeightForWidth())\r\n self.textEdit.setSizePolicy(sizePolicy)\r\n\r\n self.textEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 1)\r\n self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETADDITIONALSELECTIONTYPING, True)\r\n self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETMULTIPLESELECTION, True)\r\n self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETCARETLINEBACK, True)\r\n self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETCARETLINEVISIBLE, True)\r\n self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETCARETSTYLE, 1)\r\n self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETCARETWIDTH, 3)\r\n self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETMULTIPASTE, 1)\r\n #self.textEdit.SendScintilla(QsciScintillaBase.SCI_SETSELECTIONMODE, 3)\r\n\r\n # Current line visible with special background color\r\n self.textEdit.setCaretLineVisible(True)\r\n self.textEdit.setCaretLineBackgroundColor(QtGui.QColor(\"#F5F5DC\"))\r\n\r\n self.setWindowTitle('TakeNote')\r\n############# CREATING WIDGETS STOP ####################","sub_path":"TakeNote_GUI.py","file_name":"TakeNote_GUI.py","file_ext":"py","file_size_in_byte":5463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439107527","text":"from urllib.request import Request, urlopen\nfrom urllib.parse import urlencode\nfrom itertools import product\n\nchars = '0123456789zxcvbnmlkjhgfdsaqwertyuiop' # chars to look for\nurl = \"http://grupy.schocker.pl/5sem/index.php?action=remove&student=202113&code=\"\n\nfor lenght in range( 33, 34 ):\n\tto_attempt = product(chars, repeat=lenght)\n\tfor attempt in to_attempt:\n\t\treq = Request(url + \"\".join(attempt), headers={'User-Agent': 'Mozilla/5.0'})\n\t\tresp = urlopen(req)","sub_path":"Atak DDOS group2.py","file_name":"Atak DDOS group2.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75411703","text":"# Contains functions for error-checking user input\n\n\n# Request user for an integer input\ndef intInput(request):\n output = raw_input(request)\n while True:\n try:\n intOutput = int(output)\n if intOutput <= 0:\n raise ValueError\n return intOutput\n except ValueError:\n output = raw_input(\"Please enter a positive number: \")\n continue\n \n\n# Request user for integer input between [min, max]\ndef intInputInRange(request, min, max):\n output = raw_input(request)\n while True:\n try:\n intOutput = int(output)\n if intOutput < min or intOutput > max:\n raise ValueError\n return intOutput\n except ValueError:\n output = raw_input(\"Please enter a number between %d and %d: \" %min %max)\n ","sub_path":"src/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"143917759","text":"#\n# BSD 3-Clause License\n#\n# Copyright (c) 2017 xxxx\n# All rights reserved.\n# Copyright 2021 Huawei Technologies Co., Ltd\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# ============================================================================\n#from __future__ import print_function, division\nimport sys\nsys.path.append('core')\n\nimport argparse\nimport os\nimport cv2\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom torch.utils.data import DataLoader\nfrom raft_cpu import RAFT\nimport evaluate\nimport datasets\n\nfrom torch.utils.tensorboard import SummaryWriter\n\ntry:\n from torch.cuda.ampp import GradScaler\nexcept:\n # dummy GradScaler for PyTorch < 1.6\n class GradScaler:\n def __init__(self):\n pass\n def scale(self, loss):\n return loss\n def unscale_(self, optimizer):\n pass\n def step(self, optimizer):\n optimizer.step()\n def update(self):\n pass\n\n\n# exclude extremly large displacements\nMAX_FLOW = 400\nSUM_FREQ = 100\nVAL_FREQ = 5000\n\ndef sequence_loss(flow_preds, flow_gt, valid, gamma=0.8, max_flow=MAX_FLOW):\n \"\"\" Loss function defined over sequence of flow predictions \"\"\"\n\n n_predictions = len(flow_preds) \n flow_loss = 0.0\n\n # exlude invalid pixels and extremely large diplacements\n mag = torch.sum(flow_gt**2, dim=1).sqrt()\n valid = (valid >= 0.5) & (mag < max_flow)\n\n for i in range(n_predictions):\n i_weight = gamma**(n_predictions - i - 1)\n i_loss = (flow_preds[i] - flow_gt).abs()\n #flow_loss += i_weight * (valid[:, None] * i_loss).mean()\n flow_loss += i_weight * (i_loss).mean()\n\n epe = torch.sum((flow_preds[-1] - flow_gt)**2, dim=1).sqrt()\n epe = epe.view(-1)[valid.view(-1)]\n #import pdb \n #pdb.set_trace()\n metrics = {\n #'epe': epe.mean().item(),\n #'1px': (epe < 1).float().mean().item(),\n #'3px': (epe < 3).float().mean().item(),\n #'5px': (epe < 5).float().mean().item(),\n }\n\n return flow_loss, metrics\n\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndef fetch_optimizer(args, model):\n \"\"\" Create the optimizer and learning rate scheduler \"\"\"\n optimizer = optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.wdecay, eps=args.epsilon)\n\n scheduler = optim.lr_scheduler.OneCycleLR(optimizer, args.lr, args.num_steps+100,\n pct_start=0.05, cycle_momentum=False, anneal_strategy='linear')\n\n return optimizer, scheduler\n \n\nclass Logger:\n def __init__(self, model, scheduler):\n self.model = model\n self.scheduler = scheduler\n self.total_steps = 0\n self.running_loss = {}\n self.writer = None\n\n def _print_training_status(self):\n metrics_data = [self.running_loss[k]/SUM_FREQ for k in sorted(self.running_loss.keys())]\n training_str = \"[{:6d}, {:10.7f}] \".format(self.total_steps+1, self.scheduler.get_last_lr()[0])\n metrics_str = (\"{:10.4f}, \"*len(metrics_data)).format(*metrics_data)\n \n # print the training status\n print(training_str + metrics_str)\n\n if self.writer is None:\n self.writer = SummaryWriter()\n\n for k in self.running_loss:\n self.writer.add_scalar(k, self.running_loss[k]/SUM_FREQ, self.total_steps)\n self.running_loss[k] = 0.0\n\n def push(self, metrics):\n self.total_steps += 1\n\n for key in metrics:\n if key not in self.running_loss:\n self.running_loss[key] = 0.0\n\n self.running_loss[key] += metrics[key]\n\n if self.total_steps % SUM_FREQ == SUM_FREQ-1:\n self._print_training_status()\n self.running_loss = {}\n\n def write_dict(self, results):\n if self.writer is None:\n self.writer = SummaryWriter()\n\n for key in results:\n self.writer.add_scalar(key, results[key], self.total_steps)\n\n def close(self):\n self.writer.close()\n\n\ndef train(args):\n\n #model = nn.DataParallel(RAFT(args), device_ids=args.gpus)\n model = RAFT(args)\n print(\"Parameter Count: %d\" % count_parameters(model))\n\n #if args.restore_ckpt is not None:\n #model.load_state_dict(torch.load(args.restore_ckpt),map_location=torch.device('cpu:0'),strict=False)\n\n model.cpu()\n model.train()\n\n #if args.stage != 'chairs':\n #model.module.freeze_bn()\n\n train_loader = datasets.fetch_dataloader(args)\n optimizer, scheduler = fetch_optimizer(args, model)\n\n total_steps = 0\n scaler = GradScaler()\n #scaler = GradScaler(enabled=args.mixed_precision)\n #logger = Logger(model, scheduler)\n\n VAL_FREQ = 5000\n add_noise = True\n\n should_keep_training = True\n while should_keep_training:\n\n for i_batch, data_blob in enumerate(train_loader):\n optimizer.zero_grad()\n image1, image2, flow, valid = [x.cpu() for x in data_blob]\n\n if args.add_noise:\n stdv = np.random.uniform(0.0, 5.0)\n image1 = (image1 + stdv * torch.randn(*image1.shape).cpu()).clamp(0.0, 255.0)\n image2 = (image2 + stdv * torch.randn(*image2.shape).cpu()).clamp(0.0, 255.0)\n\n flow_predictions = model(image1, image2, iters=args.iters) \n\n loss, metrics = sequence_loss(flow_predictions, flow, valid, args.gamma)\n scaler.scale(loss).backward()\n scaler.unscale_(optimizer) \n torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)\n \n scaler.step(optimizer)\n scheduler.step()\n scaler.update()\n #print(loss)\n #print(model.unfold_w)\n\n #logger.push(metrics)\n print('Total Steps: ',total_steps+1,'loss:',loss,'i_batch:',i_batch)\n #print(f'Total Steps: {total_steps+1}')\n\n if total_steps % VAL_FREQ == VAL_FREQ - 1:\n PATH = 'checkpoints/%d_%s.pth' % (total_steps+1, args.name)\n torch.save(model.state_dict(), PATH)\n \n results = {}\n for val_dataset in args.validation:\n if val_dataset == 'chairs':\n results.update(evaluate.validate_chairs(model))\n elif val_dataset == 'sintel':\n results.update(evaluate.validate_sintel(model))\n elif val_dataset == 'kitti':\n results.update(evaluate.validate_kitti(model))\n\n #logger.write_dict(results)\n print('val Total Steps: ',total_steps+1,'val:',results)\n \n model.train()\n if args.stage != 'chairs':\n model.freeze_bn()\n \n total_steps += 1\n\n if total_steps > args.num_steps:\n should_keep_training = False\n break\n\n #logger.close()\n PATH = 'checkpoints/%s.pth' % args.name\n torch.save(model.state_dict(), PATH)\n\n return PATH\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--name', default='raft', help=\"name your experiment\")\n parser.add_argument('--stage', help=\"determines which dataset to use for training\") \n parser.add_argument('--restore_ckpt', help=\"restore checkpoint\")\n parser.add_argument('--small', action='store_true', help='use small model')\n parser.add_argument('--validation', type=str, nargs='+')\n\n parser.add_argument('--lr', type=float, default=0.00002)\n parser.add_argument('--num_steps', type=int, default=100000)\n parser.add_argument('--batch_size', type=int, default=6)\n parser.add_argument('--image_size', type=int, nargs='+', default=[384, 512])\n parser.add_argument('--gpus', type=int, nargs='+', default=[0,1])\n parser.add_argument('--mixed_precision', action='store_true', help='use mixed precision')\n\n parser.add_argument('--iters', type=int, default=12)\n parser.add_argument('--wdecay', type=float, default=.00005)\n parser.add_argument('--epsilon', type=float, default=1e-8)\n parser.add_argument('--clip', type=float, default=1.0)\n parser.add_argument('--dropout', type=float, default=0.0)\n parser.add_argument('--gamma', type=float, default=0.8, help='exponential weighting')\n parser.add_argument('--add_noise', action='store_true')\n args = parser.parse_args()\n\n torch.manual_seed(1234)\n np.random.seed(1234)\n\n if not os.path.isdir('checkpoints'):\n os.mkdir('checkpoints')\n\n train(args)\n","sub_path":"PyTorch/dev/cv/image_classification/RAFT_for_PyTorch/00-access/RAFT/train_cpu.py","file_name":"train_cpu.py","file_ext":"py","file_size_in_byte":10102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"408973862","text":"# -*- coding: utf-8 -*-\nfrom PyQt5.QtWidgets import QMainWindow, QAction, QMessageBox\nfrom PyQt5.QtGui import QIcon\nfrom img import *\nfrom CenterWidget import CenterWidget\n\nclass MainWindow(QMainWindow):\n def __init__(self, parent):\n super(MainWindow, self).__init__()\n self.resize(800,300)\n self.setWindowTitle(\"测试窗口\")\n self.fileMenu()\n self.setCentralWidget(CenterWidget(self))\n\n def fileMenu(self):\n fm = self.menuBar().addMenu(\"文件\")\n openAction = QAction(\"打开\", fm)\n openAction.triggered.connect(self.oepn)\n openAction.setIcon(QIcon(\":/img/open.png\"))\n fm.addAction(openAction)\n tb = self.addToolBar(\"file\")\n tb.addAction(openAction)\n tb.insertSeparator(openAction)\n\n self.statusBar().showMessage(\"状态栏 hello world\")\n\n def oepn(self):\n box = QMessageBox()\n box.setText(\"我的测试box\")\n box.setWindowTitle(\"提示消息\")\n box.setInformativeText(\"确认保存文档\")\n box.setStandardButtons(QMessageBox.Save|QMessageBox.Ok|QMessageBox.Cancel)\n box.setDetailedText(\"my name is tuxl\")\n res = box.exec()\n","sub_path":"mainwindow/MainWindow.py","file_name":"MainWindow.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467571714","text":"import numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nimport os\n\nfrom VAE.VAE import VAE\nfrom VAE.DataBase import DataBase as VAE_DataBase\nfrom ProcessData.Utils import *\nfrom ProcessData.Skeleton import Skeleton\n\nimport Format\nfrom ProcessData import NormData\n\nclass DataBase(Dataset):\n\n def __init__(self, source_dir, vae_dir):\n self.fileNames = []\n loadedFiles = []\n self.fileLengths = []\n\n\n for file in os.listdir(source_dir):\n if os.path.splitext(file)[-1] == '.PoseData': \n self.fileNames.append(os.path.splitext(file)[0])\n loadedFiles.append(torch.load(source_dir+'/'+file))\n self.fileLengths.append(loadedFiles[-1]['N_Frames'])\n\n print('Found Files: '+ str(self.fileNames))\n \n self.length = sum(self.fileLengths) - Format.epRange[1] * len(self.fileLengths)\n\n self.fileLengths= torch.tensor(self.fileLengths)\n \n self.poseDim = 0\n self.poseDimDiv = []\n self.poses = []\n\n self.featureDim = 0\n self.featureDimDiv = []\n self.features = []\n \n self.latents = []\n\n for c in Format.poseComponents:\n self.poseDimDiv.append(len(loadedFiles[0][c][0]))\n self.poseDim = sum(self.poseDimDiv)\n\n for c in Format.featureComponents:\n self.featureDimDiv.append(len(loadedFiles[0][c][0]))\n self.featureDim = sum(self.featureDimDiv)\n\n for f in range(len(loadedFiles)):\n for t in range(loadedFiles[f]['N_Frames']):\n frame_pose = []\n for c in Format.poseComponents:\n frame_pose.append(loadedFiles[f][c][t])\n self.poses.append(torch.cat(frame_pose))\n \n frame_feature = []\n for c in Format.featureComponents:\n frame_feature.append(loadedFiles[f][c][t])\n self.features.append(torch.cat(frame_feature))\n\n self.AE_network = VAE(self.featureDim, self.poseDim, Format.latentDim)\n self.AE_network.load_state_dict(torch.load(vae_dir, map_location=torch.device('cpu')))\n self.AE_network.eval()\n\n for p in self.AE_network.parameters(): p.requires_grad = False\n\n self.poses = torch.vstack(self.poses)\n self.features = torch.vstack(self.features)\n\n NormData.stdPose, NormData.meanPose = torch.std_mean(self.poses, dim=0, keepdim=True)\n NormData.stdFeature, NormData.meanFeature = torch.std_mean(self.features, dim=0, keepdim=True)\n \n with torch.no_grad(): self.latents = self.AE_network.encoder(self.poses, self.features)[0]\n\n del loadedFiles\n \n def __len__(self):\n return self.length\n\n def get_decoder(self):\n return self.AE_network.decoder\n \n def get_encoder(self):\n return self.AE_network.encoder\n\n def __getitem__(self, idx):\n deltaT = np.random.randint(Format.epRange[0], Format.epRange[1])\n cumsum = torch.cumsum(self.fileLengths - deltaT, 0)\n file_idx = torch.where(cumsum > idx)[0][0].item()\n frame = idx + (deltaT) * file_idx\n \n features_tm1 = self.features[frame]\n code_tm1 = self.latents[frame]\n code_t = self.latents[frame + deltaT]\n pose_t = self.poses[frame + deltaT]\n deltaT = (deltaT - Format.epRange[0] + 1)\n\n return features_tm1, code_tm1, code_t, pose_t, torch.tensor([deltaT])\n","sub_path":"LowFrequency_2/DataBase.py","file_name":"DataBase.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"171574337","text":"\"\"\"\n This spider is a HealthCareSourceJarmc spider created on top of the ATSSpider\n scrapy crawl healthcaresource_jarmc -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://www.healthcaresource.com/jarmc\"\n\n sample job url:\n https://www.healthcaresource.com/jarmc/index.cfm?fuseaction=search.jobDetails&template=dsp_job_details.cfm&cJobId=100143\n\"\"\"\n\nfrom re import compile, sub\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, HtmlFormatter, Replace\nfrom brightcorp.lib.utils import get_hidden_inputs\nfrom urllib import urlencode\n\n\nclass HealthCareSourceJarmc(ATSSpider):\n\n name = \"healthcaresource_jarmc\"\n loc_replace_re = compile(r\"(, \\d+)\")\n Ref_Num = compile(r\"&cJobId=(\\d+)\")\n cur_page = 1\n Company_Name = compile(r\"healthcaresource\\.com\\/(\\S+)\")\n company = ''\n company_xpath = {}\n jobs_xpath = '//tr[contains(@class, \"form\")]/td/a/@href'\n details_xpath = '//td[text()=\"%s\"]/following-sibling::td/text()'\n desc_xpath = '//td[text()=\"%s\"]/following-sibling::td'\n title_xpath = '//tr[@class=\"banner\"]/td/text()'\n\n def __init__(self, *args, **kwargs):\n super(HealthCareSourceJarmc, self).__init__(*args, **kwargs)\n self.company = self.Company_Name.search(self.start_urls[0])\n if self.company:\n self.company = self.company.group(1)\n\n\n def parse(self, response):\n params = get_hidden_inputs(response)\n params['ijobpostondaysold'] = ''\n params['ijobcatid'] = '100'\n params['cjobattr1'] = 'All'\n params['customsearch'] = ''\n params['cjoborderby'] = ''\n yield Request(\n callback=self.parse_jobs_list,\n url=urljoin(\n response.url,\n '/%s/index.cfm?%s' % (self.company, urlencode(\n dict((k.lower(), v) for k, v in params.iteritems()))\n )\n )\n )\n\n def parse_jobs_list(self, response):\n selector = Selector(response)\n if not self.expected_job_count_set:\n job_count = selector.re(r\"Displaying .+ of (\\d+) Record\")\n if not job_count:\n job_count = selector.xpath(\n '//strong[contains(text(), \"Results:\")]/following-sibling::text()'\n ).extract()\n if job_count:\n self.expected_job_count = job_count\n\n jobs = selector.xpath(self.jobs_xpath).extract()\n for job in jobs:\n yield Request(\n callback=self.parse_job_callback(),\n url=urljoin(response.url, job)\n )\n\n next_page = selector.xpath(\n '//input[@name=\"submit_NextPage\" or contains(@value, \"Next Page\")]/@value').extract()\n if next_page:\n self.cur_page += 1\n if 'ijobrowset' not in response.url:\n yield Request(\n callback=self.parse_jobs_list,\n url=sub(\n 'ijobrowstart=(\\d+)',\n 'ijobrowset=%s' % self.cur_page, response.url\n )\n )\n else:\n yield Request(\n callback=self.parse_jobs_list,\n url=sub(\n 'ijobrowset=(\\d+)',\n 'ijobrowset=%s' % self.cur_page, response.url\n )\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n loader.add_xpath(\n 'description', self.desc_xpath % \"Job Details:\", HtmlFormatter()\n )\n loader.add_xpath('industry', self.details_xpath % \"Department:\")\n loader.add_xpath('jobcategory', self.details_xpath % \"Category:\")\n loader.add_xpath('location', self.details_xpath % \"Location:\")\n loader.add_xpath('workhours', self.details_xpath % \"Scheduled Hours:\")\n loader.add_xpath('title', self.title_xpath)\n loader.add_xpath('workhours', self.details_xpath % \"Hours:\")\n\n loader.add_value(\n 'referencenumber', response.url,\n Prefix('%s-' % self.company), re=self.Ref_Num\n )\n if not self.company_xpath:\n loader.add_value('company', self.company)\n else:\n loader.add_xpath('company', self.company_xpath['xpath'], *self.company_xpath['processors'])\n\n loader.add_value('url', response.url)\n\n if not loader.get_output_value('location'):\n loader.add_value('location', response.meta.get('loc'), Replace(self.loc_replace_re))\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/healthcaresource_jarmc.py","file_name":"healthcaresource_jarmc.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"201613814","text":"#!/usr/bin/python\nimport psycopg2\nfrom dbconnect import dbconfig\n\nimport pandas as pd\nimport numpy as np\n\nparams = dbconfig()\nconn = psycopg2.connect(**params)\ncur = conn.cursor()\n\nq_select = \"\"\"select\n count(case when extract(dow from creation_date) = 1 then 1 end) as Mon,\n count(extract(dow from creation_date) = 2 or null) as Tue,\n count(extract(dow from creation_date) = 3 or null) as Wed,\n count(*) filter (where extract(dow from creation_date) = 4) as Thu,\n count(extract(dow from creation_date) = 5 or null) as Fri,\n count(extract(dow from creation_date) = 6 or null) as Sat,\n count(extract(dow from creation_date) = 0 or null) as Sun\n from posts\"\"\"\n\nd = {}\ndic_query = {}\ndic_query['Java'] = \" where tags like '%%'\"\ndic_query['Java EE'] = \" where tags like '%%'\"\ndic_query['Android'] = \" where tags like '%%'\"\ndic_query['JDBC'] = \" where tags like '%%'\"\ndic_query['Python'] = \" where tags like '%%'\"\ndic_query['C#'] = \" where tags like '%%'\"\ndic_query['RoR'] = \" where tags like '%%'\"\ndic_query['SQL Server'] = \" where tags like '%%'\"\ndic_query['C++'] = \" where tags like '%%'\"\ndic_query['Maven'] = \" where tags like '%%'\"\ndic_query['.NET'] = \" where tags like '%<.net>%'\"\ndic_query['iPhone'] = \" where tags like '%%'\"\ndic_query['XML'] = \" where tags like '%%'\"\ndic_query['All'] = \"\"\n\nfor key, value in dic_query.items():\n query = q_select + value\n cur.execute(query)\n results = cur.fetchall()\n d[key] = [i * 100 / sum(results[0]) for i in results[0]]\n\ndf = pd.DataFrame(d, index=['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'])\ndf = df[list(dic_query.keys())]\n\n# df.loc['sum'] = df.sum()\n\nprint (df.to_string())\n\n\n","sub_path":"hobby_or_serious.py","file_name":"hobby_or_serious.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262983129","text":"from game import Game\nfrom match import Match\n\nclass Server:\n\n\tdef __init__(self, datas):\n\n\t\tself._match = None\n\t\tself._games = None\n\n\t\tif(datas.__contains__(\"match\")):\n\t\t\tself._match = Match(datas['match'])\n\t\tif(datas.__contains__(\"games\")):\n\n\t\t\tgames = list()\n\t\t\tfor data in datas['games']:\n\t\t\t\tgames.append(Game(data))\n\n\t\t\tself._games = games\n\n\tdef __str__(self):\n\n\t\tres = \"\"\n\t\tres += \"Match = \"\n\t\tif self.match != None:\n\t\t\tres += \"{\\n\"\n\t\t\tres += self.match.__str__()\n\t\t\tres += \"}\\n\"\n\t\telse:\n\t\t\tres += \"None\\n\"\n\n\t\tres += \"Games = \"\n\t\tif self.games != None:\n\t\t\tres += \"[\"\n\t\t\tfor game in self.games:\n\t\t\t\tres += \"\\n{\"\n\t\t\t\tres += game.__str__()\n\t\t\t\tres += \"}\\n\"\n\t\t\tres += \"]\\n\"\n\t\telse:\n\t\t\tres += \"None\\n\"\n\n\t\treturn res\n\n\tdef _get_match(self):\n\t\treturn self._match\n\n\tdef _get_games(self):\n\t\treturn self._games\n\n\tmatch = property(_get_match)\n\tgames = property(_get_games)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"368617354","text":"#Travis LaBounty\r\n#Homework 4\r\ndef main():\r\n birthday = {}\r\n menu()\r\ndef menu():\r\n birthday = {'Travis' : '01/03/1992',\r\n 'Cassidy' : '02/20/1994',\r\n 'Remi' : '01/08/2013'}\r\n print ('Please choose from the options below: \\n',\r\n '1. Look up birthday \\n',\r\n '2. Add a new birthday \\n',\r\n '3. Change a birthday \\n',\r\n '4. Delete a birthday \\n',\r\n '5. Quit program')\r\n userinput = input(\"Choice: \")\r\n \r\n if(userinput == '1'):\r\n lookup(birthday)\r\n elif(userinput == '2'):\r\n add(birthday)\r\n menu()\r\n \r\n elif(userinput == '3'):\r\n change(birthday)\r\n menu()\r\n elif(userinput == '4'):\r\n delete(birthday)\r\n menu()\r\n elif(userinput == '5'):\r\n quitPro()\r\n else:\r\n print(\"I'm sorry, that option does not exist\")\r\n return menu()\r\n \r\n\r\ndef lookup(birthday):\r\n name = input(\"Please enter the name of the person you wish to look up: \") \r\n if name in birthday:\r\n print(name + ' has a birthday on ' + birthday[name])\r\n return menu()\r\n else:\r\n print(\"I'm sorry, that person does not exist\")\r\n return menu()\r\n \r\n \r\ndef add(birthday):\r\n name = input(\"Enter in a name: \" )\r\n dob = input(\"Enter in that person's birthday (MM/DD/YYYY): \")\r\n birthday.update({name : dob})\r\n print (name + \"'s birthday was successfully added to the list\")\r\n print(birthday)\r\n return birthday\r\n \r\n\r\n\r\ndef change(birthday):\r\n change = input(\"Enter in the name of the person's birthday you wish to change: \")\r\n newBday = input(\"Enter in the new birthday (MM/DD/YYY): \")\r\n if change in birthday:\r\n birthday.update({ change : newBday})\r\n print (change+ \"'s birthday is now \" + newBday)\r\n print(birthday)\r\n else:\r\n print(\"I'm sorry. That person does not exist\")\r\n return birthday\r\n\r\n \r\n \r\ndef delete(birthday):\r\n name = input(\"Enter in the name of the person you wish to delete: \")\r\n for k in birthday:\r\n if name in birthday:\r\n del (birthday[name])\r\n print(name + \" has been deleted from the list\")\r\n print(birthday)\r\n else:\r\n print(\"I'm sorry. That person does not exist\")\r\n return birthday\r\n\r\n\r\ndef quitPro():\r\n print(\"You have ended the program\")\r\n exit()\r\n\r\n\r\n\r\n \r\nmain()\r\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"20581407","text":"# %load q04_plot_runs_by_balls/build.py\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\nipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None)\n\n\n# Solution\ndef plot_runs_by_balls():\n plt.scatter(ipl_df['runs'],ipl_df.index)\n plt.show()\n \n\nplt.scatter(ipl_df['runs'],ipl_df.index)\nplt.show()\nfig, ax = plt.subplots(1,2)\nax[0].hist(x, bins=10, alpha = 0.5, color = 'r')\nax[1].hist(y, bins=10, alpha = 0.5, color = 'g')\nplt.show()\nplot_runs_by_balls()\n\n\n","sub_path":"q04_plot_runs_by_balls/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"591405188","text":"from json import dumps as json_dumps\n\nimport pytest\nfrom fastapi import Body, Response\n\n\n@pytest.fixture\ndef probe_ep(ep):\n @ep.method()\n def probe(\n response: Response,\n data: str = Body(..., example='123'),\n ) -> str:\n response.set_cookie(key='probe-cookie', value=data)\n response.status_code = 404\n return data\n\n return ep\n\n\ndef test_basic(probe_ep, raw_request):\n body = json_dumps({\n 'id': 1,\n 'jsonrpc': '2.0',\n 'method': 'probe',\n 'params': {'data': 'data-123'},\n })\n response = raw_request(body)\n assert response.cookies['probe-cookie'] == 'data-123'\n assert response.status_code == 404\n","sub_path":"tests/test_sub_response.py","file_name":"test_sub_response.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76844591","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#1\n#is_two defines a single parameter, x (whatever user input), and determines whether or not that input is\n#two (it returns a Boolean value of True or False)\n\ndef is_two(x):\n #check to make sure the input is explicitly the integer two or the numerical string for two\n if x == 2 or x == '2': \n #return bool True if it is two\n return True\n else:\n #return bool False if not\n return False\n\nis_two('2')\n\n\n# In[ ]:\n\n\n#2\n#is_vowel defines a single parameter, x (assuming it is a string of one character), and determines whether the input \n#is a vowel or not (returns Boolean True or False)\ndef is_vowel(x):\n #check to see if the input (lowercased just in case input is uppercased) is in this complete string of vowels\n if x.lower() in 'aeiou':\n #return bool True if it's in the string\n return True\n else:\n #return bool False if not\n return False\n \nis_vowel('A')\n\n\n# In[ ]:\n\n\n#3\n#is_consonant defines a single parameter, x (string of one character), and returns a Boolean True or False\ndef is_consonant(x):\n #check to see if the input character is in this complete list of consonants\n if x.lower() in 'bcdfghjklmnpqrstvwxyz':\n #return bool True if it is a consonant\n return True\n else:\n #return bool False if it is not a consonant\n return False\n \nis_consonant('B')\n\n\n# In[ ]:\n\n\n#4\n#capitalize_consonant_words defines a single parameter, a string, and returns a string capitalized\n#if it begins with a consonant\ndef capitalize_consonant_words(string):\n #check to see if the first letter of the string is a consonant\n if is_consonant(string[0]) == True:\n #return the string capitalized if the first letter checks out\n return string.capitalize()\n else:\n #return the string as it was input; does not capitlize string if first letter not a consonant\n return string\n \ncapitalize_consonant_words('success')\n\n\n# In[ ]:\n\n\n#5\n#calculate_tip defines two parameters, a float and another float, and returns a float value\ndef calculate_tip(percentage, bill):\n #set identifier 'tip' to the value of the product for the percentage (float 1) and the bill (float 2) \n tip = bill * percentage\n #we just want the tip (rounded to two decimal places)\n return round(tip, 2)\n\ncalculate_tip(.22, 18.24)\n\n\n# In[ ]:\n\n\n#6 \n#apply_discount defines two parameters, two floats, and returns a float value\ndef apply_discount(price, disc):\n #return the discounted price (price minus discount) as a float, rounded to two decimals\n return round(price * (1 - disc), 2)\n\napply_discount(24.99, .8)\n\n\n# In[ ]:\n\n\n#7\n#my handle_commas defines a single parameter, a string, and returns a float value\ndef handle_commas(string):\n #assign a variable to an empty string to work with\n c_handled = ''\n #start a loop to check every character in string input\n for c in string:\n #if the character is a number, add to the variable (string)\n if c.isdigit():\n c_handled += c\n #if the character is a decimal, add to the string\n elif c == '.':\n c_handled += '.'\n #return the string as a float\n return float(c_handled)\n\nhandle_commas('12,345,678.9')\n\n\n# In[ ]:\n\n\n#8\n#get_letter_grade determines a single parameter, an integer, and returns a string value\ndef get_letter_grade(x):\n #check if the integer is above the value of 89, return string value 'A' if it is\n if x > 89:\n return 'A'\n #since we are checking if the input is greater than a certain value, and python reads top-to-bottom, we can \n #just check if the input is above a value less than the previous if-clause value and return the \n #appropriate/ corresponding string value\n elif x > 79:\n return 'B'\n elif x > 69:\n return 'C'\n elif x > 64:\n return 'D'\n else:\n return 'F' \n \nget_letter_grade(69)\n\n\n# In[ ]:\n\n\n#9\n#remove_vowels determines a single parameter, a string, and returns a string\ndef remove_vowels(string):\n #assign a variable to an empty string\n v_removed = ''\n #start a loop to check if characters in input string are not vowels\n for l in string:\n if not is_vowel(l):\n #only add vowel-opposite characters to the string variable\n v_removed += l\n #return the string variable with characters that are not vowels\n return v_removed\n\nremove_vowels('Nnnnooooooooooo!!!!')\n\n\n# In[ ]:\n\n\n#10\n#normalize_name defines a single parameter, a string, and returns a string value\ndef normalize_name(string):\n #python identifiers can not start with numbers. Loop through string until first character of string is not \n #a number. move numbers to the back\n while string[0].isdigit():\n string = string[1:] + string[0]\n #assign a variable to: the input string stripped of all leading or trailing white space, as well as with all\n #lowercased characters\n f_name = string.strip().lower() \n #assign a variable to an empty string\n e_name = ''\n #twice\n end_game = ''\n #start a loop to see if string characters are python identifer compliant\n for char in f_name:\n #include space so we don't have random underscores at the beginning or end if original string input includes\n #invalid characters for python-identifier compliance at the beginning or end of original input and spaces\n #inbetween those invalid characters and valid ones. check to see if characters are in approved list\n if char in 'abcdefghijklmnopqrstuvwxyz_0123456789 ':\n #add all the approved characters to the first empty string variable\n e_name += char\n #assign a variable to the result stripped of all the leftover leading or trailing whitespace\n g_name = e_name.strip()\n #start another for loop to get a cleaner string\n for char in g_name:\n #check to see if character is py-id compliant\n if char in 'abcdefghijklmnopqrstuvwxyz_0123456789':\n #add py-id compliant characters to second empty string variable\n end_game += char\n #check to see if character is a space\n if char == ' ':\n #add an underscore to the second string variable in a space's stead\n end_game += '_'\n #return the python-identifier-compliant second string variable value\n return end_game\n\nif __name__ == '__main__':\n print(normalize_name('First name'))\n print(normalize_name('Name'))\n print(normalize_name('% Completed'))\n print(normalize_name('1man'))\n\n\n# In[ ]:\n\n\n#Example code\n#cumulative_sum([1, 1, 1]) returns [1, 2, 3]\n#cumulative_sum([1, 2, 3, 4]) returns [1, 3, 6, 10]\n\n#interpretation\n#if A = [1, 1, 1], then cumulative_sum(A) = [(A[0]), (A[0] + A[1]), (A[0] + A[1] + A[2])]\n#cumulative_sum(A) = [sum(A[:1]), sum(A[:2]), sum(A[:3])]\n#cumulative_sum(A) = [sum(A[:0 + 1]), sum(A[:1 + 1]), sum(A[:2 + 1])]\n#range(len(A)) = range(0, 3) --> which is zero to two (0, 1, 2)--> which is the complete index for A\n\n#cumulative_sum defines a single parameter, a list, and returns a list\ndef cumulative_sum(L):\n #return a list of numbers that are each the sum of a number in the input list plus all of the numbers prior to\n #this number in the index. use python's zero-indexing to format the individual sums for the return list. \n #use a for loop to run through the index of the input list and generate sums for each item on the return list.\n return [sum(L[:n + 1]) for n in range(len(L))]\n\nc = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ncumulative_sum(c)\n\n\n# In[ ]:\n\n\n#Mason's personal functions\n#import mason_functions as mf\n\n\n# In[ ]:\n\n\n#pull a number from a string with one number \ndef pull_an_integer_from_a_string_with_one_integer(string):\n number = ''\n for char in string:\n if char.isdigit():\n number += char\n return int(number)\n\npull_an_integer_from_a_string_with_one_integer('Yo! You have 38 unread messages!')\n#good to alias it as 'pin'\n#can copy and paste below after '#' marker:\n#from mason_functions import pull_an_integer_from_a_string_with_one_integer as pin\n\n\n# In[ ]:\n\n\n#get an average of one list (take one paramater and return a float)\ndef average(n):\n return sum(n) / len(n)\n\na = [1, 2, 3, 4,]\naverage(a)\n\n\n# In[ ]:\n\n\n#move the first item in an sequence to the last position of a sequence (take one parameter and return a list)\ndef first_to_last(s):\n #assign a variable to the first item of the sequence\n x = s[0]\n #assign a variable to the sequence starting with the second item and add the first item to the end of the sequence\n s = s[1:] + [x]\n #return the new sequence with the first item at the end and the second item in front\n return s\n\nfirst_to_last([1, 2, 3, 4, 5,])\n\n\n# In[ ]:\n\n\n#get the median of a list of numbers (take one parameter and return a float)\ndef median(x):\n #sort the list so function code can slice into an appropriate data set\n x.sort()\n #assign a variable to the total number of items in the list (how many data points do we have?)\n l = len(x)\n #assign a variable to half of the total of numbers(data points) in the list. If the list is even or odd, the\n #value of this variable is an integer that represents how many times the value two goes into the total of\n #numbers, i.e., 9 // 2 = 4 and 8 // 2 = 4\n n = l // 2\n #introduce an 'if' conditional to determine if the total number of datapoints is odd\n if l % 2 == 1:\n #if it is, return the middle datapoint\n return x[n]\n #otherwise, just return the value in the middle of the two middlest points\n return (x[n - 1] + x[n]) / 2 \n\n#condensed\n#def median(x):\n #x.sort()\n #l = len(x)\n #n = l // 2\n #if l % 2 == 1:\n #return x[n]\n #return (x[n - 1] + x[n]) / 2\n\nif __name__ == '__main__':\n print(median([1, 2, 70, 80, 90, 100]))\n print(median([1, 2, 3, 4, 5]))\n print(median([4, 8, 1, 2, 38]))\n print(median([1, 100, 2, 90]))\n\n\n# In[ ]:\n\n\n#count some vowels m8\ndef count_vowels(string):\n count = 0\n for x in string:\n if is_vowel(x):\n count += 1\n return count\n\ncount_vowels('Hadouken!')\n\n\n# In[ ]:\n\n\n#count some consonants m9\ndef count_consonants(string):\n count = 0\n for x in string:\n if is_consonant(x):\n count += 1\n return count\n\ncount_consonants('Shoryuken!')\n\n\n# In[ ]:\n\n\n#Is it true, Brutus? Ay tu?\ndef count_Trues(list):\n count = 0\n for bool in list:\n if bool == True:\n count += 1\n return count\n\ncount_Trues([True, False, True, False, True, False, True])\n\n\n# In[ ]:\n\n\n#Thank you, Ryan Orsinger\ndef get_db_url(db_name):\n from env import host, user, password\n return f'mysql+pymysql://{user}:{password}@{host}/{db_name}'\n\n\n# In[ ]:\n\n\n#is it 3?\ndef is_three(x):\n if x == 3 or x == '3' or x.lower() == 'three':\n return True\n else:\n return False\nif __name__ == '__main__': \n print(is_three('ThREe'))\n print(is_three('3'))\n print(is_three(3))\n\n","sub_path":"mason_functions.py","file_name":"mason_functions.py","file_ext":"py","file_size_in_byte":11002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410950686","text":"import numpy as np\r\nimport cv2\r\n\r\ncap=cv2.VideoCapture(0) #カメラの使用を宣言。引数はカメラのデバイス番号\r\n\r\nwhile(True):\r\n ret,frame=cap.read() #カメラによる映像の入力。retはフレームが正しく読み込まれたかのtrue or false。frameはフレーム\r\n gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) #フレームをグレースケールに変換\r\n cv2.imshow('frame',frame) #フレームを出力\r\n if cv2.waitKey(1) & 0xFF == ord('q'): #1msec 間隔でキー入力を待つ。'q'が入力されたらwhileを抜ける。\r\n break\r\n\r\ncap.release() #カメラデバイスの開放\r\ncv2.destroyAllWindows() #開いたウィンドウをすべて閉じる。\r\n","sub_path":"movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"123896256","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# This Jupyter notebook, which is based on Python 3, is designed to calculate the abundances of N elements in the neutron star merger mixture. The notebook will contain several functions to easily calculate values such as temperature, abundances, and ionization potentials.\n\n# In this notebook, I have a function for the potentials, initialization of values, calculation of abundances, and plotting\n\n# In[1]:\n\n\n#Importing Libraries\nimport saha_mult #Class used to calculate abundances \nimport saha\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport scipy.constants as sc\nfrom time import process_time #Useful for finding calculation times\nimport pickle #for saving data in lists to txt files.\n\n\nimport importlib \nimportlib.reload(saha_mult) #This command ensures that any changes made to saha_mult class are reflected in this notebook\n\n\n# In[2]:\n\n\n#Read in data for ionization potentials and skynet stuff\n#Note that the NIST data table includes many elements that just skip ionization potentials, so I set a cutoff at Lr.\nnist = pd.read_excel(\"NIST Data Table.xlsx\")\nhf = h5py.File(\"SkyNet_r-process.h5\")\n\n\n# In[3]:\n\n\n#This function here will return all the ionization potentials of the desired elements. Enter the starting element and\n#ending element Z number. This will return an array of arrays. Note the starting position of the array!\n\n#The way I did this was similar to the Multiple Elements Scenario code, but I added an extra array called \n#returned_potentials, which is designed to return an array of all the desired potentials we wanted\nion_energies1d = nist[' Ionization Energy (eV)']\n\ndef ionization_generator(elements):\n max_el = 103 #This is defined to be the Z of the last element that I want in the list \n ion_energies = list()\n returned_potentials = list()\n counter = 0\n\n for i in range(0,max_el+1):\n specific_list = list()\n\n for j in range(i):\n\n if isinstance(ion_energies1d[counter],str):\n\n if len(ion_energies1d[counter]) ==3:\n specific_list.append(0)\n counter+=1\n else:\n str_num = '' \n\n for k in ion_energies1d[counter]:\n\n if (k != ' ') and (k !='[') and (k !=']') and (k !='(') and (k !=')'):\n str_num+=k\n\n specific_list.append(np.abs(float(str_num)))\n counter+=1\n\n\n else:\n specific_list.append(np.array((np.abs(ion_energies1d[counter]))))\n counter+=1\n\n ion_energies.append(specific_list)\n ion_energies[-1][-2] = np.average([ion_energies[-1][-1],ion_energies[-1][-3]])\n \n for i in range(len(elements)):\n returned_potentials.append(np.array((ion_energies[elements[i]]))) \n \n return np.array(returned_potentials)\n\n\n# In[4]:\n\n\n#This cell is simply for temperature, and since it does not change no matter the elements used, I do not use a function\n#At some point, I will have to find a way to find the places to calculate the indices to use to find slope for other hdf5s\ntemperature = hf[\"Temperature\"]\ntime = hf[\"Time\"]\nmod_temp = []\nfull_temp = []\n\nlinear = np.polyfit(np.log10(np.array(time[900:1700])),np.log10(np.array(temperature[900:1700])),1)\nm = linear[0]\n\nfor i in range(0,len(temperature)):\n if i < 1700:\n mod_temp.append(np.log10(temperature[i]))\n full_temp.append(temperature[i])\n else:\n del_t = m*(np.log10(time[i]) - np.log10(time[i-1]))\n mod_temp.append(mod_temp[i-1]+del_t)\n full_temp.append(10**mod_temp[i])\n\n\n# In[14]:\n\n\n#initialization of ionization potentials and full abundances from Skynet\n#used in the abundance calculation function\nabundance = hf[\"Y\"]\ncharge = hf[\"Z\"]\ndensity = hf[\"Density\"]\nkbEvpGK = 8.617e-5*1e9\n\ndef initialization(elements):\n\n full_abundance = []\n ion_potential = ionization_generator(elements)\n \n for i in range(len(elements)):\n temp_index = []\n temp_abundance = []\n \n for j in range(len(charge)):\n \n if charge[j] == (elements[i]): ##charge of element\n temp_index.append(j)\n \n temp_abundance = np.sum(abundance[:, temp_index], 1)\n full_abundance.append(temp_abundance)\n \n return np.array(full_abundance),np.array(ion_potential)\n\n\n# In[6]:\n\n\n#Abundance function\ndef abundance_calculation(elements):\n x,y = initialization(elements)\n return (saha_mult.GetAbundances(x,np.array(full_temp),np.array(density),y))\n\n\n# In[7]:\n\n\n#Function to plot the abundances, the sum of all ionization states, and the graphical check\n#At some point, I might add functionality to choosing which things to graph\n\n#1 hr = 3600 sec\n#2 Weeks = 1.21e+6 seconds\n\ndef plotter(abun):\n \n time_start = process_time()\n #colors = ['r','b'] #Just a color scheme to indicate varying elements instead of having too many colors.\n x = np.zeros((len(abun[0]),len(abun[-1][0]))) #Initializing the array useful in tracking ionization state abundances\n checksum = []#Another way to calculating the total sum across time. \n index_total = [] #Calculating total sum across time \n \n #Plotting abundances vs Temp\n for Y in abun:\n Ytot = np.sum(Y,1)\n for i in range(len(Y[0])):\n plt.semilogx(kbEvpGK*np.array(full_temp),(Y[:,i])/Ytot,)\n plt.xlabel(\"Temperature(eV)\")\n plt.ylabel(\"Rel. Abundance\")\n plt.title(\"Rel. Abundances of Elements in Mixture vs Temperature\")\n \n plt.show()\n \n \n #Plotting abundances vs Time\n for Y in abun:\n Ytot = np.sum(Y,1)\n for i in range(len(Y[0])):\n plt.semilogx(time,(Y[:,i])/Ytot,)\n plt.xlabel(\"Time(sec)\")\n plt.ylabel(\"Rel. Abundance\")\n plt.title(\"Rel. Abundances of Elements in Mixture vs Time\")\n \n plt.show()\n \n \n #PLot of all Rel. Isoelectronic State Abundances over Temperature\n #So this sums up the abundances of everything with the same number of electrons.\n for Y in abun:\n x[0:len(Y),0:len(Y[0])]+=Y[:,-1::-1]\n \n for i in range(len(abun[-1][0])):\n Ytot = np.sum(x,1)\n plt.loglog(kbEvpGK*np.array(full_temp),x[:,i]/Ytot,label = i)\n plt.legend()\n plt.xlabel(\"Temperature(eV)\")\n plt.ylabel(\"Rel. Abundance of Isoelectronic States\")\n plt.title(\"Rel. Abundances of All Isoelectronic States vs Temperature\")\n plt.xlim([0.1,10])\n plt.ylim([1.e-3, 1])\n \n \n plt.show()\n \n #Time vs Total Rel.Isoelectronic State Abundances\n\n for i in range(len(abun[-1][0])):\n Ytot = np.sum(x,1)\n plt.loglog(time,x[:,i]/Ytot,label = i)\n plt.legend()\n plt.xlabel(\"Time(sec)\")\n plt.ylabel(\"Rel. Abundance of Isoelectronic States\")\n plt.title(\"Rel. Abundances of All Isoelectronic States vs Time\")\n plt.xlim([3600,1.21e+6]) #Specific range for 1 hr to 2 weeks of time in sec\n plt.ylim([1.e-3, 1])\n \n plt.show()\n \n \n #Plotting the Graphical Check\n for i in range(len(abun[0])):\n summation = 0\n temp_sum = 0\n for Y in abun:\n summation+=np.sum(Y[i])\n temp_sum+=np.sum(Y,1)\n checksum.append(summation)\n index_total.append(temp_sum)\n \n plt.semilogx(kbEvpGK*np.array(full_temp),np.array(checksum)/np.array(index_total))\n plt.xlabel(\"Energy(eV)\")\n plt.ylabel(\"Ratio of Sum of Rel. Abundances per Timestep over Total\")\n plt.title(\"Graphical Check of Rel. Abundances\")\n plt.show()\n \n \n #Quick calculation of how long it takes\n time_elapsed = (process_time() - time_start)\n print(\"This calculation took\",time_elapsed,' sec to graph')\n\n\n# In[8]:\n\n\n#def plotterfunction2 for graphing the majority of the graphs\n\n\n# In[9]:\n\n\n#Call to function to generate data. Also, calculate time it takes.\n\ntime_start = process_time()\nYI = abundance_calculation([8,9])\ntime_elapsed = (process_time() - time_start)\nprint(\"This calculation took\",time_elapsed,' sec')\nplotter(YI)\n\n\n# In[15]:\n\n\n#This is the calculation to make the time plot. Currently, it is commented out for convenience\n'''times = []\nelements = np.arange(1,104,1)\n\nfor i in elements:\n time_start = process_time()\n YI = abundance_calculation([i])\n times.append(process_time() - time_start)\n \nplt.plot(elements,times)\nplt.xlabel('Element Number')\nplt.ylabel('Times(sec)')\nplt.title('Calculation Times for Abundances')\nplt.grid()\nplt.savefig('times.png')'''\n\n\n# In[9]:\n\n\n#This cell exists to make the entire lanthanide calculation. \n'''time_start = process_time()\nYI = abundance_calculation(np.arange(58,72,1))\ntime_elapsed = process_time() - time_start\ntime_elapsed'''\n\n\n# In[19]:\n\n\nwith open(\"Lanthanides.txt\", \"rb\") as fp: # Unpickling\n YI = pickle.load(fp)\n\n\n# In[20]:\n\n\nplotter(YI)\n\n\n# In[11]:\n\n\n#Just plotting all the lanthanide abundances seperately\nelement_num = 58 #Z of first lanthanide\nfor Y in YI:\n #Temperature\n Ytot = np.sum(Y,1)\n print('This is the graph for element ',element_num,'so there are ',element_num+1,' ionization states graphed')\n for i in range(len(Y[0])):\n plt.semilogx(kbEvpGK*np.array(full_temp),(Y[:,i])/Ytot)\n plt.xlabel(\"Temperature(eV)\")\n plt.ylabel(\"Rel. Abundance\")\n plt.title(\"Rel. Abundances of Elements in Mixture vs Temperature\")\n plt.show()\n \n #Time\n for i in range(len(Y[0])):\n plt.semilogx(np.array(time),(Y[:,i])/Ytot)\n plt.xlabel(\"Time(sec)\")\n plt.ylabel(\"Rel. Abundance\")\n plt.title(\"Rel. Abundances of Elements in Mixture vs Time\")\n plt.xlim([3600,1.21e+6])\n element_num+=1\n plt.show()\n \n\n\n# In[11]:\n\n\n#isotopic_abundances,potentials = initialization(np.arange(58,72,1))\n\n\n# In[26]:\n\n\n'''for i in range(len(isotopic_abundances)):\n print('This is the abundance graph of element: ',(i+58))\n Ytot_isotopic = np.sum(isotopic_abundances[i])\n plt.semilogx(kbEvpGK*np.array(full_temp),isotopic_abundances[i]/Ytot_isotopic,label = (i+58))\n plt.legend()\n plt.xlabel(\"Temperature(eV)\")\n plt.ylabel(\"Total Abundance of Each Lanthanide\")\n plt.title(\"Abundances of All Elemental Abundances vs Temperature\")\n plt.show()'''\n\n\n# In[27]:\n\n\n#This cell exists to make the entire lanthanide+actinide calculation. \n'''time_start = process_time()\nYI = abundance_calculation(np.arange(58,103,1))\ntime_elapsed = process_time() - time_start\ntime_elapsed'''\n\n\n# In[17]:\n\n\nwith open(\"Lanthanides_Actinides.txt\", \"rb\") as fp: # Unpickling\n YI = pickle.load(fp)\n\n\n# In[13]:\n\n\nplotter(YI)\n\n\n# In[16]:\n\n\n#Just plotting all the lanthanide and actinide abundances seperately\nelement_num = 58 #Z of first lanthanide\nfor Y in YI:\n Ytot = np.sum(Y,1)\n print('This is the graph for element ',element_num,'so there are ',element_num+1,' ionization states graphed')\n for i in range(len(Y[0])):\n plt.semilogx(kbEvpGK*np.array(full_temp),(Y[:,i])/Ytot)\n plt.xlabel(\"Temperature(eV)\")\n plt.ylabel(\"Rel. Abundance\")\n plt.title(\"Rel. Abundances of Elements in Mixture vs Temperature\")\n plt.show()\n for i in range(len(Y[0])):\n plt.semilogx(np.array(time),(Y[:,i])/Ytot)\n plt.xlabel(\"Time(sec)\")\n plt.ylabel(\"Rel. Abundance\")\n plt.title(\"Rel. Abundances of Elements in Mixture vs Time\")\n plt.xlim([3600,1.21e+6])\n element_num+=1\n plt.show()\n \n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Abundance_Calculations/Single_and_Initial_Multi_Element/Abundance_Function.py","file_name":"Abundance_Function.py","file_ext":"py","file_size_in_byte":11571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"137369455","text":"import sys; input=sys.stdin.readline\n\nn, c = map(int, input().split())\narr = [int(input()) for _ in range(n)]\narr.sort()\n\nstart = 1\nend = arr[-1]-arr[0]\nresult = 0\n\nwhile (start<=end):\n mid = (start+end)//2\n value = arr[0]\n cnt = 1\n for i in range(1, len(arr)):\n if arr[i]>=value+mid:\n value = arr[i]\n cnt += 1\n \n if cnt >= c:\n start = mid+1\n result = mid\n else:\n end = mid-1\nprint(result)","sub_path":"argorithm/2110_re.py","file_name":"2110_re.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"367294233","text":"#/usr/bin/env python\n#-*- coding:utf-8 -*-\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nfrom Service.caimenu.ServiceCaiMenu import CaiMenu_Service\n\ncategory = {\n '/category/40076':1,\n '/category/40078':2,\n '/category/51848':3,\n '/category/52354':4,\n '/category/20130':5,\n '/category/20137':6\n\n}\ncate_dish ={\n 'jiachangcai':1,\n 'xiafancai':2,\n 'sucai':3,\n 'dayudarou':4,\n 'tanggeng':5,\n 'liangcai':6\n}\n\ndef open_url_keword(keyword):\n data = {'keyword':keyword,'cat':1001}\n session = requests.session()\n html = session.get('http://www.xiachufang.com/search/?',params=data)\n html.encoding = 'utf-8'\n return html\n\n\ndef open_url(url):\n session = requests.session()\n html = session.get(url)\n html.encoding = 'ut-8'\n return html\n\n\ndef get_keyword_step(url):\n html = open_url(url)\n\n soup = BeautifulSoup(html.text,'lxml')\n\n steps = soup.find('div',class_='steps').find_all('p')\n steps = list(steps)\n for i in steps:\n print(i)\n print(type(steps),steps)\n step = ' '.join(steps)\n return steps\n\ndef page_tab_data(url,category_url):\n html = open_url(url)\n soup = BeautifulSoup(html.text, 'lxml')\n if soup.select('.search-result-list'):\n search_list = soup.find('div',class_='search-result-list').find('ul',class_='list').find_all('li')\n else:\n search_list = soup.find('div',class_='normal-recipe-list').find('ul', class_='list').find_all('li')\n search_detail = []\n for li in search_list:\n title = li.find('p', class_='name').find('a').text.strip().split(' ')[0]\n url = 'http://www.xiachufang.com' + li.find('p', class_='name').find('a')['href'].strip()\n side_dish = li.find('p', class_='ing ellipsis').text.strip()\n img = li.find('img')['data-src'].strip()\n stats = str(li.find('p', class_='stats')).strip()\n add_caidan = CaiMenu_Service()\n response = add_caidan.check_dish_exits(title)\n if not response.status:\n add_caidan.add_dish(title, url, img, side_dish, stats, category[category_url])\n dish_detail = {'title': title, 'url': url, 'img': img,\n 'side_dish': side_dish, 'stats': str(stats)}\n search_detail.append(dish_detail)\n return search_detail\n\n\ndef get_search_html(keyword,perfect_match=False,cate=None):\n html = open_url_keword(keyword.strip())\n response_url = html.url.replace('http://www.xiachufang.com','')\n soup = BeautifulSoup(html.text,'lxml')\n if soup.select('.search-result-list'):\n search_list = soup.find('div',class_='search-result-list').find('ul',class_='list').find_all('li')\n else:\n search_list = soup.find('div',class_='normal-recipe-list').find('ul', class_='list').find_all('li')\n search_detail = []\n for li in search_list:\n title = li.find('p',class_='name').find('a').text\n url = 'http://www.xiachufang.com' + li.find('p',class_='name').find('a')['href']\n side_dish = li.find('p',class_='ing ellipsis').text\n img = li.find('img')['data-src']\n stats = str(li.find('p',class_='stats'))\n dish_detail = {'title':title,'url':url,'img':img,\n 'side_dish':side_dish,'stats':stats}\n if perfect_match:\n if keyword.strip() == title.strip():\n add_caidan = CaiMenu_Service()\n add_caidan.add_dish(title, url, img, side_dish, stats, cate_dish[cate])\n return dish_detail\n search_detail.append(dish_detail)\n return search_detail,response_url\n\n\n\n","sub_path":"Common/sousuocaimin.py","file_name":"sousuocaimin.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"207418399","text":"#Python Pushups - warmup 2 'array_font9'\ndef array_front9(nums):\n checklist = nums[0:4]\n if 9 in checklist:\n return True\n return False\nprint(array_front9([1, 9, 3, 4, 9]))\n\ndef tempconverter(temp):\n if temp[-1] == 'C':\n celtemp = float(temp[:-1])\n tempinfar = ((celtemp)*(9/5) + 32)\n return (\"{} Farenheit\".format(tempinfar))\n elif temp[-1] == 'F':\n fartemp = float(temp[:-1])\n tempincel = (fartemp - 32)*(5/9)\n return (\"{} Celcius\".format(tempincel))\n\ntempinput = input(\"Enter a temperature, followed by 'F' or 'C'\")\nprint(tempconverter(tempinput))\n","sub_path":"students/johnwachter/session04/pythonpushupsweek4.py","file_name":"pythonpushupsweek4.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"336028404","text":"# https://www.hackerrank.com/challenges/apple-and-orange/problem\ndef countApplesAndOranges(s, t, a, b, apples, oranges):\n appleCount = 0\n orangeCount = 0\n appanges = [apples, oranges]\n ranges = [a, b]\n for i in range(len(appanges)):\n for j in range(len(appanges[i])):\n if appanges[i][j] + ranges[i] <= t and appanges[i][j] + ranges[i] >= s:\n if i == 0:\n appleCount += 1\n else:\n orangeCount += 1\n print(\"%d\\n%d\"% (appleCount, orangeCount))\n","sub_path":"Easy/countApllesAndOranges.py","file_name":"countApllesAndOranges.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"445030861","text":"# Copyright 2015 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nfrom common.skia import global_constants\n\n\nDEPS = [\n 'ct',\n 'file',\n 'depot_tools/gclient',\n 'gsutil',\n 'recipe_engine/path',\n 'recipe_engine/properties',\n 'recipe_engine/step',\n 'recipe_engine/time',\n 'skia',\n 'skia_swarming',\n 'swarming',\n 'swarming_client',\n 'depot_tools/tryserver',\n]\n\n\nCT_SKPS_ISOLATE = 'ct_skps.isolate'\n\n# Do not batch archive more slaves than this value. This is used to prevent\n# no output timeouts in the 'isolate tests' step.\nMAX_SLAVES_TO_BATCHARCHIVE = 100\n\n# Number of slaves to shard CT runs to.\nDEFAULT_CT_NUM_SLAVES = 100\n\n# The SKP repository to use.\nDEFAULT_SKPS_CHROMIUM_BUILD = '57259e0-05dcb4c'\n\n\ndef RunSteps(api):\n # Figure out which repository to use.\n buildername = api.properties['buildername']\n if '10k' in buildername:\n ct_page_type = '10k'\n elif '1m' in buildername:\n ct_page_type = 'All'\n else:\n raise Exception('Do not recognise the buildername %s.' % buildername)\n\n # Figure out which configuration to build.\n if 'Release' in buildername:\n configuration = 'Release'\n else:\n configuration = 'Debug'\n\n # Figure out which tool to use.\n if 'DM' in buildername:\n skia_tool = 'dm'\n elif 'BENCH' in buildername:\n skia_tool = 'nanobench'\n else:\n raise Exception('Do not recognise the buildername %s.' % buildername)\n\n ct_num_slaves = api.properties.get('ct_num_slaves', DEFAULT_CT_NUM_SLAVES)\n\n # Optimize 10k DM runs by not sharding to 100 swarming bots. Shard to\n # only 1, sharding to more than that ends up taking more time due to overhead.\n if ct_page_type == '10k' and skia_tool == 'dm':\n ct_num_slaves = 1\n ct_page_type = 'All'\n\n # Checkout Skia and Chromium.\n gclient_cfg = api.gclient.make_config()\n\n skia = gclient_cfg.solutions.add()\n skia.name = 'skia'\n skia.managed = False\n skia.url = global_constants.SKIA_REPO\n skia.revision = (api.properties.get('parent_got_revision') or\n api.properties.get('orig_revision') or\n api.properties.get('revision') or\n 'origin/master')\n gclient_cfg.got_revision_mapping['skia'] = 'got_revision'\n\n src = gclient_cfg.solutions.add()\n src.name = 'src'\n src.managed = False\n src.url = 'https://chromium.googlesource.com/chromium/src.git'\n src.revision = 'origin/master' # Always checkout Chromium at ToT.\n\n for repo in (skia, src):\n api.skia.update_repo(repo)\n\n update_step = api.gclient.checkout(gclient_config=gclient_cfg)\n skia_hash = update_step.presentation.properties['got_revision']\n\n # Checkout Swarming scripts.\n # Explicitly set revision to empty string to checkout swarming ToT. If this is\n # not done then it crashes due to missing\n # api.properties['parent_got_swarming_client_revision'] which seems to be\n # set only for Chromium bots.\n api.swarming_client.checkout(revision='')\n # Ensure swarming_client is compatible with what recipes expect.\n api.swarming.check_client_version()\n # Setup Go isolate binary.\n chromium_checkout = api.path['slave_build'].join('src')\n api.skia_swarming.setup_go_isolate(chromium_checkout.join('tools', 'luci-go'))\n\n # Apply issue to the Skia checkout if this is a trybot run.\n api.tryserver.maybe_apply_issue()\n\n # Build the tool.\n api.step('build %s' % skia_tool,\n ['make', skia_tool, 'BUILDTYPE=%s' % configuration],\n cwd=api.path['checkout'])\n\n skps_chromium_build = api.properties.get(\n 'skps_chromium_build', DEFAULT_SKPS_CHROMIUM_BUILD)\n\n # Set build property to make finding SKPs convenient.\n api.step.active_result.presentation.properties['Location of SKPs'] = (\n 'https://pantheon.corp.google.com/storage/browser/%s/skps/%s/%s/' % (\n api.ct.CT_GS_BUCKET, ct_page_type, skps_chromium_build))\n\n # Delete swarming_temp_dir to ensure it starts from a clean slate.\n api.file.rmtree('swarming temp dir', api.skia_swarming.swarming_temp_dir)\n\n for slave_num in range(1, ct_num_slaves + 1):\n # Download SKPs.\n api.ct.download_skps(\n ct_page_type, slave_num, skps_chromium_build,\n api.path['slave_build'].join('skps'))\n\n # Create this slave's isolated.gen.json file to use for batcharchiving.\n isolate_dir = chromium_checkout.join('chrome')\n isolate_path = isolate_dir.join(CT_SKPS_ISOLATE)\n extra_variables = {\n 'SLAVE_NUM': str(slave_num),\n 'TOOL_NAME': skia_tool,\n 'GIT_HASH': skia_hash,\n 'CONFIGURATION': configuration,\n }\n api.skia_swarming.create_isolated_gen_json(\n isolate_path, isolate_dir, 'linux', 'ct-%s-%s' % (skia_tool, slave_num),\n extra_variables)\n\n # Batcharchive everything on the isolate server for efficiency.\n max_slaves_to_batcharchive = MAX_SLAVES_TO_BATCHARCHIVE\n if '1m' in buildername:\n # Break up the \"isolate tests\" step into batches with <100k files due to\n # https://github.com/luci/luci-go/issues/9\n max_slaves_to_batcharchive = 5\n tasks_to_swarm_hashes = []\n for slave_start_num in xrange(1, ct_num_slaves+1, max_slaves_to_batcharchive):\n m = min(max_slaves_to_batcharchive, ct_num_slaves)\n batcharchive_output = api.skia_swarming.batcharchive(\n targets=['ct-' + skia_tool + '-%s' % num for num in range(\n slave_start_num, slave_start_num + m)])\n tasks_to_swarm_hashes.extend(batcharchive_output)\n # Sort the list to go through tasks in order.\n tasks_to_swarm_hashes.sort()\n\n # Trigger all swarming tasks.\n dimensions={'os': 'Ubuntu-14.04', 'cpu': 'x86-64', 'pool': 'Chrome'}\n if skia_tool == 'nanobench':\n # Run on GPU bots for nanobench.\n dimensions['gpu'] = '10de:104a'\n tasks = api.skia_swarming.trigger_swarming_tasks(\n tasks_to_swarm_hashes, dimensions=dimensions)\n\n # Now collect all tasks.\n failed_tasks = []\n for task in tasks:\n try:\n api.skia_swarming.collect_swarming_task(task)\n\n if skia_tool == 'nanobench':\n output_dir = api.skia_swarming.tasks_output_dir.join(\n task.title).join('0')\n utc = api.time.utcnow()\n gs_dest_dir = 'ct/%s/%d/%02d/%02d/%02d/' % (\n ct_page_type, utc.year, utc.month, utc.day, utc.hour)\n for json_output in api.file.listdir('output dir', output_dir):\n # TODO(rmistry): Use api.skia.gsutil_upload once the skia recipe\n # is usable without needing to call gen_steps first.\n api.gsutil.upload(\n name='upload json output',\n source=output_dir.join(json_output),\n bucket='skia-perf',\n dest=gs_dest_dir,\n env={'AWS_CREDENTIAL_FILE': None, 'BOTO_CONFIG': None},\n args=['-R']\n )\n\n except api.step.StepFailure as e:\n failed_tasks.append(e)\n\n if failed_tasks:\n raise api.step.StepFailure(\n 'Failed steps: %s' % ', '.join([f.name for f in failed_tasks]))\n\n\ndef GenTests(api):\n ct_num_slaves = 5\n skia_revision = 'abc123'\n\n yield(\n api.test('CT_DM_10k_SKPs') +\n api.properties(\n buildername='Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Debug-CT_DM_10k_SKPs',\n ct_num_slaves=ct_num_slaves,\n revision=skia_revision,\n )\n )\n\n yield(\n api.test('CT_BENCH_10k_SKPs') +\n api.properties(\n buildername=\n 'Perf-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Release-CT_BENCH_10k_SKPs',\n ct_num_slaves=ct_num_slaves,\n revision=skia_revision,\n ) +\n api.path.exists(\n api.path['slave_build'].join('skia'),\n api.path['slave_build'].join('src')\n )\n )\n\n yield(\n api.test('CT_DM_1m_SKPs') +\n api.properties(\n buildername='Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Debug-CT_DM_1m_SKPs',\n ct_num_slaves=ct_num_slaves,\n revision=skia_revision,\n )\n )\n\n yield (\n api.test('CT_DM_SKPs_UnknownBuilder') +\n api.properties(\n buildername=\n 'Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Debug-CT_DM_UnknownRepo_SKPs',\n ct_num_slaves=ct_num_slaves,\n revision=skia_revision,\n ) +\n api.expect_exception('Exception')\n )\n\n yield (\n api.test('CT_10k_SKPs_UnknownBuilder') +\n api.properties(\n buildername=\n 'Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Debug-CT_UnknownTool_10k_SKPs',\n ct_num_slaves=ct_num_slaves,\n revision=skia_revision,\n ) +\n api.expect_exception('Exception')\n )\n\n yield(\n api.test('CT_DM_1m_SKPs_slave3_failure') +\n api.step_data('ct-dm-3 on Ubuntu-14.04', retcode=1) +\n api.properties(\n buildername='Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Debug-CT_DM_1m_SKPs',\n ct_num_slaves=ct_num_slaves,\n revision=skia_revision,\n )\n )\n\n yield(\n api.test('CT_DM_1m_SKPs_2slaves_failure') +\n api.step_data('ct-dm-1 on Ubuntu-14.04', retcode=1) +\n api.step_data('ct-dm-3 on Ubuntu-14.04', retcode=1) +\n api.properties(\n buildername='Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Debug-CT_DM_1m_SKPs',\n ct_num_slaves=ct_num_slaves,\n revision=skia_revision,\n )\n )\n\n yield(\n api.test('CT_DM_10k_SKPs_Trybot') +\n api.properties(\n buildername=\n 'Test-Ubuntu-GCC-GCE-CPU-AVX2-x86_64-Debug-CT_DM_10k_SKPs-Trybot',\n ct_num_slaves=ct_num_slaves,\n rietveld='codereview.chromium.org',\n issue=1499623002,\n patchset=1,\n )\n )\n","sub_path":"scripts/slave/recipes/skia/ct_skps.py","file_name":"ct_skps.py","file_ext":"py","file_size_in_byte":9368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"298263336","text":"import json\nimport os\nfrom urllib import request\n\nurl = \"https://api.github.com/repositories\"\nsavename = \"./file/repo.json\"\n\n# 여기가 저장과정..\n# urllib.request.urlretrieve(url주소, 저장장소와 이름)\nif not os.path.exists(savename):\n request.urlretrieve(url, savename)\n\n# open('r') : 파일을 여는 역할\n# .read() : 파일을 읽는 역할\nitems = json.load(open(savename,'r',encoding='utf-8'))\n\n# s = open(savename, \"r\", encoding=\"utf-8\").read()\n# items = json.load(s)\n# print(items)\n\nfor item in items:\n # item[\"owner\"][\"login\"] : 딕셔너리안에 키:딕셔너리로 저장되어있어서\n # 호출 하는 방법이 key:owner로 value:딕셔너리를 호출하고,\n # key:login으로 value를 호출한다.\n print(item[\"name\"] + \"_\" + item[\"owner\"][\"login\"])\n","sub_path":"crawling_data/data_3(json파일 만들기).py","file_name":"data_3(json파일 만들기).py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"495022240","text":"import session\r\ncursor = session.cursor\r\n\r\nlist_s_1 = []\r\n\r\nsql_open_new = \"select * from menu\";\r\nsql_update = \"update menu set count\"\r\ncursor.execute(sql_open_new);\r\nresults = cursor.fetchall();\r\nfor record in results:\r\n count = record[1]\r\n list_s_1.append(count)\r\n\r\nprint(list_s_1)\r\n\r\nrev = [1,4,3,2,8]\r\n\r\nlong = len(rev)\r\n\r\n#for i in range(len(rev)):\r\n #list_s_1.insert(i, list_s_1[i] + 1)\r\n\r\n\r\n\r\n#for i in range(len(list_s_1)):\r\nn = \"update menu set id=3 where count=2\"\r\n #sql_update = \"update menu set count=\" + list_s_1[i] + \" where id=\" + \" \"+i;\r\ncursor.execute(n)\r\n","sub_path":"bot/venv/testings.py","file_name":"testings.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"138062493","text":"import gym\nimport numpy as np\nimport torch\nfrom model_softmax import Policy, Val\nimport qn\nimport torch.nn.functional as F\nfrom torch import nn, optim\nfrom torch.autograd import grad\nfrom random import shuffle\nfrom torch.distributions.categorical import Categorical\n\n#env knowledge\nobs_dim = 4\naction_dim = 2\n\n# parameters\nepochs = 500\nD_size = 4\ngamma = 0.99\nlda = 0.97 # for generalized advantage esitmate\n\nval_epochs = 5\nval_lr = 1e-3\n\npolicy_lr = 3e-4\n\n\npolicy = Policy(obs_dim,action_dim)\nval = Val(obs_dim)\n\nval_optim = optim.Adam(val.parameters(), lr=val_lr)\npolicy_optim = optim.Adam(policy.parameters(),lr=policy_lr)\n\n#%%\neps_lens = []\nenv = gym.make('CartPole-v1')\nfor k in range(epochs):\n print('epoch: {}'.format(k))\n # collect D\n D = []\n for _ in range(D_size):\n eps = []\n obs = env.reset()\n done = False\n i = 0\n while not done:\n obs_tensor = torch.from_numpy(obs.astype('float32'))\n p = policy(obs_tensor)\n# print(p)\n categorical = Categorical(p)\n a = env.action_space.sample()\n logp = torch.log(p[a])\n wi = torch.exp(logp).detach()/0.5\n #g = grad(obj,policy.parameters())\n obs_new, r, done, info = env.step(a)\n eps.append([obs,a,r,wi,logp,obs_new])\n obs = obs_new\n i += 1\n print('end in {} steps'.format(i+1))\n D.append(eps)\n eps_lens.append(np.mean([len(x) for x in D]))\n \n \n \n #fit val\n mat = []\n y = []\n for eps in D:\n v = 0\n for item in eps[::-1]:\n mat.append(item[0])\n v = v*gamma + item[2]\n y.append(v)\n mat = torch.from_numpy(np.array(mat,dtype='float32'))\n y = torch.from_numpy(np.array(y,dtype='float32')[:,None])\n for _ in range(val_epochs):\n y_pred = val(mat)\n v_loss = F.mse_loss(y_pred,y)\n# print(v_loss)\n val_optim.zero_grad()\n v_loss.backward()\n val_optim.step()\n \n\n #fit policy simple\n# scalar = 1\n scalar = D_size\n# scalar = D_size*sum([len(x) for x in D])\n policy_optim.zero_grad()\n for eps in D:\n delta_cum = 0\n for item in eps[::-1]:\n obs,a,r,wi,logp, obs_new = item\n # delta for GAE\n obs = torch.from_numpy(obs.astype('float32'))\n obs_new = torch.from_numpy(obs_new.astype('float32'))\n delta = (gamma*val(obs_new)+r - val(obs))[0].detach()\n delta_cum = delta + gamma*lda*delta_cum\n# print(delta,delta_cum)\n # accumulate grads\n (-logp*delta_cum/scalar).backward()\n# for p in policy.parameters():\n# p.grad /= D_size\n policy_optim.step()\n\n#%%\nimport matplotlib.pyplot as plt\n#\n#plt.plot(eps_lens1)\neps_lensd = qn.load('eps_lens_std.pkl')\nplt.plot(eps_lensd)\nplt.plot(eps_lens[:200])\n\n\n\n\n#%%\nenv = gym.make('CartPole-v1')\ntotal_t = []\nfor i_episode in range(50):\n obs = env.reset()\n done = False\n t = 0\n while not done:\n# env.render()\n obs_tensor = torch.from_numpy(obs.astype('float32'))\n p = policy(obs_tensor)\n# print(p)\n categorical = Categorical(p)\n a = categorical.sample()\n logp = torch.log(p[a])\n #g = grad(obj,policy.parameters())\n obs_new, r, done, info = env.step(a.data.tolist())\n# action_explore = np.clip(action + noise(action),-1,1)\n# print(done)\n #history.append([obs,action[0],reward,obs_new])\n obs = obs_new\n t += 1\n total_t.append(t)\n \nprint(np.mean(total_t))\n \n","sub_path":"cartpole/vpg/vpg_off_policy.py","file_name":"vpg_off_policy.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394709509","text":"\r\n\r\nimport unittest\r\n\r\n\r\nfrom pony.orm import *\r\n\r\ndb = Database()\r\n\r\nclass TestPost(db.Entity):\r\n category = Optional('TestCategory')\r\n name = Optional(str, default='Noname')\r\n\r\nclass TestCategory(db.Entity):\r\n posts = Set(TestPost)\r\n\r\ndb.bind('sqlite', ':memory:')\r\ndb.generate_mapping(create_tables=True)\r\n\r\nwith db_session:\r\n post = TestPost()\r\n\r\n\r\nclass TransactionLockTestCase(unittest.TestCase):\r\n\r\n __call__ = db_session(unittest.TestCase.__call__)\r\n\r\n def tearDown(self):\r\n rollback()\r\n\r\n def test_create(self):\r\n p = TestPost()\r\n p.flush()\r\n cache = db._get_cache()\r\n self.assertEqual(cache.immediate, True)\r\n self.assertEqual(cache.in_transaction, True)\r\n\r\n def test_update(self):\r\n p = TestPost[post.id]\r\n p.name = 'Trash'\r\n p.flush()\r\n cache = db._get_cache()\r\n self.assertEqual(cache.immediate, True)\r\n self.assertEqual(cache.in_transaction, True)\r\n\r\n def test_delete(self):\r\n p = TestPost[post.id]\r\n p.delete()\r\n flush()\r\n cache = db._get_cache()\r\n self.assertEqual(cache.immediate, True)\r\n self.assertEqual(cache.in_transaction, True)\r\n","sub_path":"flask/lib/python2.7/site-packages/pony/orm/tests/test_transaction_lock.py","file_name":"test_transaction_lock.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600465727","text":"import numpy as np\n\nfrom allennlp.common.testing import AllenNlpTestCase\nfrom allennlp.common.util import ensure_list\nfrom nlpete.data.dataset_readers import NL2BashDatasetReader\n\n\nclass TestNL2BashReader(AllenNlpTestCase):\n\n def setUp(self):\n super(TestNL2BashReader, self).setUp()\n self.reader = NL2BashDatasetReader(\"target_tokens\")\n instances = self.reader.read(\"nlpete/tests/fixtures/nl2bash/train.tsv\")\n self.instances = ensure_list(instances)\n\n def test_tokens(self):\n assert len(self.instances) == 3\n fields = self.instances[2].fields\n assert [t.text for t in fields[\"source_tokens\"].tokens] == \\\n [\"@start@\", \"Extracts\", \" \", \"a\", \" \", \"bz\", \"2\", \" \", \"file\", \".\", \"@end@\"]\n assert [t.text for t in fields[\"target_tokens\"].tokens] == \\\n [\"@start@\", \"bunzip\", \"2\", \" \", \"file\", \".\", \"bz\", \"2\", \"@end@\"]\n\n def test_target_to_source(self):\n target_to_source = self.instances[2].fields[\"target_to_source\"]\n\n # shape should be (target_length, source_length - 2)\n assert target_to_source.array.shape == (9, 9)\n\n check = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0], # @START@\n [0, 0, 0, 0, 0, 0, 0, 0, 0], # bunzip\n [0, 0, 0, 0, 0, 1, 0, 0, 0], # 2\n [0, 1, 0, 1, 0, 0, 1, 0, 0], # \\s\n [0, 0, 0, 0, 0, 0, 0, 1, 0], # file\n [0, 0, 0, 0, 0, 0, 0, 0, 1], # .\n [0, 0, 0, 0, 1, 0, 0, 0, 0], # bz\n [0, 0, 0, 0, 0, 1, 0, 0, 0], # 2\n [0, 0, 0, 0, 0, 0, 0, 0, 0]]) # @END@\n np.testing.assert_equal(target_to_source.array, check)\n\n def test_preprocess_target(self):\n # pylint: disable=protected-access\n tgt_str = \"sudo find .\"\n check = \"find .\"\n assert self.reader._preprocess_target(tgt_str) == check\n\n tgt_str = \"$find .\"\n check = \"find .\"\n assert self.reader._preprocess_target(tgt_str) == check\n\n tgt_str = \"$ find .\"\n check = \"find .\"\n assert self.reader._preprocess_target(tgt_str) == check\n\n tgt_str = \"# find .\"\n check = \"find .\"\n assert self.reader._preprocess_target(tgt_str) == check\n\n tgt_str = \"ls -l | /bin/grep\"\n check = \"ls -l | grep\"\n assert self.reader._preprocess_target(tgt_str) == check\n\n tgt_str = \"ls -l | ~/bin/grep\"\n check = \"ls -l | ~/bin/grep\"\n assert self.reader._preprocess_target(tgt_str) == check\n","sub_path":"nlpete/tests/data/dataset_readers/nl2bash_test.py","file_name":"nl2bash_test.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"150050211","text":"import ast\nfrom typing import Union\n\nfrom flake8_plugin_utils import Visitor\n\nfrom flake8_pytest_style.config import Config\nfrom flake8_pytest_style.errors import (\n ExtraneousScopeFunction,\n FixtureFinalizerCallback,\n FixtureParamWithoutValue,\n FixturePositionalArgs,\n IncorrectFixtureNameUnderscore,\n IncorrectFixtureParenthesesStyle,\n MissingFixtureNameUnderscore,\n YieldFixture,\n)\nfrom flake8_pytest_style.utils import (\n AnyFunctionDef,\n get_all_argument_names,\n get_fixture_decorator,\n get_qualname,\n is_pytest_yield_fixture,\n is_test_function,\n)\n\n\nclass FixturesVisitor(Visitor[Config]):\n def _check_fixture_decorator_name(\n self, fixture_decorator: Union[ast.Call, ast.Attribute]\n ) -> None:\n \"\"\"Checks for PT020.\"\"\"\n if isinstance(fixture_decorator, ast.Call):\n is_yield = is_pytest_yield_fixture(fixture_decorator.func)\n else:\n is_yield = is_pytest_yield_fixture(fixture_decorator)\n if is_yield:\n self.error_from_node(YieldFixture, fixture_decorator)\n\n def _check_fixture_decorator(\n self,\n fixture_decorator: Union[ast.Call, ast.Attribute],\n fixture_func: AnyFunctionDef,\n ) -> None:\n \"\"\"Checks for PT001, PT002, PT003.\"\"\"\n if not isinstance(fixture_decorator, ast.Call):\n if self.config.fixture_parentheses:\n self.error_from_node(\n IncorrectFixtureParenthesesStyle,\n fixture_decorator,\n expected_parens='()',\n actual_parens='',\n )\n return\n\n if (\n not self.config.fixture_parentheses\n and not fixture_decorator.args\n and not fixture_decorator.keywords\n ):\n self.error_from_node(\n IncorrectFixtureParenthesesStyle,\n fixture_decorator,\n expected_parens='',\n actual_parens='()',\n )\n\n if fixture_decorator.args:\n self.error_from_node(\n FixturePositionalArgs, fixture_decorator, name=fixture_func.name\n )\n\n for keyword in fixture_decorator.keywords:\n if (\n keyword.arg == 'scope'\n and isinstance(keyword.value, ast.Str)\n and keyword.value.s == 'function'\n ):\n self.error_from_node(\n ExtraneousScopeFunction, fixture_decorator, name=fixture_func.name\n )\n\n def _check_fixture_returns(self, node: AnyFunctionDef) -> None:\n \"\"\"Checks for PT004, PT005.\"\"\"\n has_return_with_value = False\n for child in ast.walk(node):\n if isinstance(child, (ast.Return, ast.Yield)) and child.value is not None:\n has_return_with_value = True\n break\n\n if has_return_with_value and node.name.startswith('_'):\n self.error_from_node(IncorrectFixtureNameUnderscore, node, name=node.name)\n elif not has_return_with_value and not node.name.startswith('_'):\n self.error_from_node(MissingFixtureNameUnderscore, node, name=node.name)\n\n def _check_fixture_addfinalizer(self, node: AnyFunctionDef) -> None:\n \"\"\"Checks for PT021.\"\"\"\n if 'request' not in get_all_argument_names(node.args):\n return\n\n for child in ast.walk(node): # pragma: no branch\n if (\n isinstance(child, ast.Call)\n and get_qualname(child.func) == 'request.addfinalizer'\n ):\n self.error_from_node(FixtureFinalizerCallback, child)\n return\n\n def _check_test_function_args(self, node: AnyFunctionDef) -> None:\n \"\"\"Checks for PT019.\"\"\"\n # intentionally not looking at posonlyargs because pytest passes everything\n # as kwargs, so declaring fixture args as positional-only will fail anyway\n for arg in node.args.args + node.args.kwonlyargs:\n if arg.arg.startswith('_'):\n self.error_from_node(FixtureParamWithoutValue, node, name=arg.arg)\n\n def visit_FunctionDef(self, node: AnyFunctionDef) -> None:\n fixture_decorator = get_fixture_decorator(node)\n if fixture_decorator:\n self._check_fixture_decorator_name(fixture_decorator)\n self._check_fixture_decorator(fixture_decorator, node)\n self._check_fixture_returns(node)\n self._check_fixture_addfinalizer(node)\n\n if is_test_function(node):\n self._check_test_function_args(node)\n\n self.generic_visit(node)\n\n visit_AsyncFunctionDef = visit_FunctionDef # noqa: N815\n","sub_path":"flake8_pytest_style/visitors/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"547872416","text":"import random as rnd\nimport statistics as stats\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_spike_train(rate,big_t,tau_ref):\n\n if 1<=rate*tau_ref:\n print(\"firing rate not possible given refractory period f/p\")\n return []\n\n\n exp_rate=rate/(1-tau_ref*rate)\n\n spike_train=[]\n\n t=rnd.expovariate(exp_rate)\n\n while t< big_t:\n spike_train.append(t)\n t+=tau_ref+rnd.expovariate(exp_rate)\n\n return spike_train\n\n\ndef inter_spike(spike_train):\n inter_spike_t = []\n for i,x in enumerate(spike_train):\n next = i+1\n if(next < len(spike_train)):\n inter = spike_train[next]-x\n inter_spike_t.append(inter)\n return inter_spike_t\n\n \ndef count_spikes(spike_train, window_size,big_t):\n a = []\n count = 0\n start = 1\n for i,x in enumerate(spike_train):\n curr = float(window_size*start)\n if(x > curr):\n a.append(count)\n start += 1\n curr = float(window_size*start)\n while(x > curr):\n a.append(0)\n start += 1\n curr = float(window_size*start)\n count = 1\n else:\n count += 1\n if(i == len(spike_train) -1):\n a.append(count)\n return a\n\ndef fano(counts):\n var = stats.variance(counts)\n mu = stats.mean(counts)\n return var / mu\n\ndef var_coef(inter_spikes):\n sig = np.std(inter_spikes)\n mu = np.mean(inter_spikes)\n return sig / mu\n\ndef load_data(filename,T):\n\n data_array = [T(line.strip()) for line in open(filename, 'r')]\n\n return data_array\n\ndef gen_times(spikes):\n times = []\n period = 2 * 0.001\n running = float(0)\n for i in range(len(spikes)):\n if(spikes[i] == 0):\n running += period\n else:\n running +=period\n times.append(running)\n return times\n\ndef auto_corr_array(spike_train, num_spikes):\n arr = np.zeros((101,), dtype=int)\n for i in range(len(spike_train)):\n if(spike_train[i] == 1):\n for j in range(-50,51):\n if(i+j > 0 and i+j < len(spike_train)-1):\n if(spike_train[i+j] == 1):\n arr[j+50] += 1\n print(num_spikes)\n arr = [float(num)/num_spikes for num in arr]\n return arr\n\ndef plot_auto(corr_arr):\n x_label = np.arange(-100,102,2)\n plt.bar(x_label,corr_arr)\n plt.ylabel('Autocorrelation')\n plt.title('Time Interval -ms')\n plt.show()\n\ndef sta(spike_train, num_spikes, stim_train):\n \n arr = np.zeros((50,), dtype=float)\n for i in range(len(spike_train)):\n \n if(spike_train[i] == 1):\n \n for j in range(-50,0):\n \n if(i+j > 0):\n \n arr[j+50] += stim_train[i+j]\n print(num_spikes)\n print(arr)\n arr = [float(num)/num_spikes for num in arr]\n print(len(arr))\n return arr\n\ndef plot_sta(sta_arr):\n x_label = np.arange(-100,0,2)\n plt.bar(x_label,sta_arr)\n plt.ylabel('spike trigge average')\n plt.title('Time Interval -ms')\n plt.show()","sub_path":"coursework2/submission/poisson.py","file_name":"poisson.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"157676538","text":"def factors(n):\n facts = [1]\n i = 2\n while( i * i <= n):\n if( n%i == 0):\n facts.append(i)\n facts.append(n//i)\n i+=1\n\n return facts\n\nif __name__ == '__main__':\n amicableMap = {}\n for i in range(0, 10**5+1):\n amicableMap[i] = sum(factors(i))\n\n amicables = []\n for i in range(0, 10**5+1):\n mapVal = amicableMap[i]\n if(mapVal < 10**5 and i == amicableMap[mapVal] and i != mapVal ):\n amicables.append(i)\n\n print(amicables)\n\n for _ in range(0, int(input())):\n n = int(input())\n print( sum( [ x for x in amicables if x < n ] ) ) \n","sub_path":"Problem_20_29/Problem_21/amicable.py","file_name":"amicable.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"545725876","text":"# pylint: disable=W0201\n# Discord Packages\nimport discord\nfrom discord.ext import commands\n\n# Bot Utilities\nfrom cogs.utils.logging import Logger\nfrom cogs.utils.settings import Settings\n\nimport time\nimport traceback\nfrom argparse import ArgumentParser, RawTextHelpFormatter\n\nintents = discord.Intents.none()\nintents.guilds = True\nintents.members = True\nintents.emojis = True\nintents.presences = True\nintents.messages = True\nintents.guild_reactions = True\nintents.guild_typing = True\n\nmentions = discord.AllowedMentions(\n everyone=False,\n replied_user=False\n)\n\n\ndef _get_prefix(bot, message):\n if not message.guild:\n prefixes = settings.prefix\n return commands.when_mentioned_or(*prefixes)(bot, message)\n prefixes = settings.prefix\n return commands.when_mentioned_or(*prefixes)(bot, message)\n\n\nclass Bot(commands.Bot):\n def __init__(self):\n super().__init__(command_prefix=_get_prefix, intents=intents, allowed_mentions=mentions)\n self.logger = logger\n self.data_dir = data_dir\n self.settings = settings.extra\n\n async def on_message(self, message):\n if message.author.bot:\n return\n await self.process_commands(message)\n\n async def on_ready(self):\n if not hasattr(self, \"uptime\"):\n self.uptime = time.time()\n if not hasattr(self, \"appinfo\"):\n self.appinfo = await self.application_info()\n\n self.logger.info(\"Logged in as: %s in %s servers.\", self.user.name, len(self.guilds))\n self.logger.info(\"DiscordPY: %s\", discord.__version__)\n self.logger.debug(\"Bot Ready;Prefixes: %s\", \", \".join(settings.prefix))\n\n extensions = [\"cogs.misc\", \"cogs.poeng\", \"cogs.errors\", \"cogs.github\", \"cogs.broder\"]\n for extension in extensions:\n try:\n self.logger.debug(\"Loading extension %s\", extension)\n self.load_extension(extension)\n except Exception as e:\n self.logger.exception(\"Loading of extension %s failed: %s\", extension, e)\n\n def run(self):\n try:\n super().run(settings.token)\n except Exception as e:\n tb = e.__traceback__\n self.logger.error(traceback.extract_tb(tb))\n print(e)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(prog=\"Roxedus' ProgBott\",\n description=\"Programmeringsbot for Norsk programmering\",\n formatter_class=RawTextHelpFormatter)\n\n parser.add_argument(\"-D\", \"--debug\", action=\"store_true\", help=\"Sets debug to true\")\n parser.add_argument(\"-l\", \"--level\", help=\"Sets debug level\",\n choices=[\"critical\", \"error\", \"warning\", \"info\", \"debug\"], default=\"warning\")\n parser.add_argument(\"-d\", \"--data-directory\",\n help=\"Define an alternate data directory location\", default=\"data\", type=str)\n parser.add_argument(\"-f\", \"--log-to-file\", action=\"store_true\", help=\"Save log to file\", default=True)\n\n args = parser.parse_args()\n\n level = args.level\n data_dir = args.data_directory\n\n if args.debug:\n level = \"DEBUG\"\n\n settings = Settings(data_dir=data_dir, log_level=level, log_to_file=args.log_to_file)\n\n logger = Logger(location=settings.data_dir, level=settings.log_level, to_file=settings.log_to_file).logger\n logger.debug(\"Data folder: %s\", settings.data_dir)\n\n Bot().run()\n","sub_path":"launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"365916492","text":"with open(\"hightemp.txt\") as f:\n lines = f.readlines()\n\nline_set = set()\nfor line in lines:\n line = line.split(\"\\t\")\n line_set.add(line[0])\n\nfor line in line_set:\n print(line)\n","sub_path":"2/17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"473261380","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef make_weight_matrix(x, dm, tau):\n return np.diag(np.exp(-(x-dm.x1)**2/(2*tau**2)))\n\ndef non_weighted_theta(dm, y):\n a = np.linalg.inv(np.dot(design_matrix.T, design_matrix))\n b = np.dot(design_matrix.T, df.y)\n return np.dot(a,b)\n\ndef weighted_theta(x, dm, y, tau):\n w = make_weight_matrix(x, dm, tau)\n a = np.dot(w, dm)\n inv = np.linalg.inv(np.dot(dm.T, a))\n b = np.dot(w, y)\n c = np.dot(dm.T, b)\n return np.dot(inv, c)\n\n# Load the data into numpy arrays\nxdata = np.loadtxt('data/q2x.dat')\nydata = np.loadtxt('data/q2y.dat')\n\n# Create the Data Frame out of a python dictionary\ndata = {'x0' : [1. for i in xdata], 'x1' : xdata, 'y' : ydata}\ndf = pd.DataFrame(data)\ndesign_matrix = df[['x0', 'x1']]\n\n# Some xvalues for making the fitted curves from regression\nx_for_fitting = np.linspace(np.min(df.x1), np.max(df.x1), 50)\n\n# Calculate parameters from non-weighted linear regression\nlinear_theta_0, linear_theta_1 = non_weighted_theta(design_matrix, df.y)\n\n# Calculate parameters from weighted regression. This creates a theta-vector\n# for each input x point. Input xpoints are the pairs [1,x] where the x come\n# from x_for_fitting.\ntaus = [(0.1,'yellow'), (0.3,'orange'), (2,'red'), (10,'magenta')]\n\n# Make a list of tuples (theta_vector, 'tau', 'color') for plotting\nthetas= [(np.array(map(lambda x: weighted_theta(x,design_matrix,df.y,tau),\n x_for_fitting)), str(tau), color) for tau,color in taus]\n\nplt.figure()\nplt.grid()\nplt.title('Weighted/Unweighted Fitting')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.plot(df.x1, df.y, marker='o', color='blue', markeredgecolor='k',\n markeredgewidth=1.5, markersize=13, alpha=.7, linestyle='none')\nplt.plot(x_for_fitting, linear_theta_0 + linear_theta_1 * x_for_fitting, 'g-',\n linewidth=4, alpha=.8, label='unweighted')\n\n# Plot the fitted curves for the different tau values.\nfor theta,label,color in thetas:\n plt.plot(x_for_fitting, theta[:,0] + theta[:,1] * x_for_fitting,\n linewidth=4, label=r'$\\tau = $'+label, alpha=.8, color=color)\n\nplt.legend(loc=4)\nplt.show()\n","sub_path":"cs229_1-2.py","file_name":"cs229_1-2.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"183263755","text":"import shutil\r\nimport os\r\nfrom tkinter import *\r\nfrom tkinter import filedialog\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nimport linecache\r\nimport settings_db\r\nimport re\r\n\r\n\r\nclass Selector:\r\n\tdef __init__(self, window):\r\n\t\t# main app\r\n\t\tself.window = window\r\n\r\n\t\t# prepare arguments\r\n\t\tself.mods = []\r\n\t\tself.dlc = []\r\n\t\tself.mod = []\r\n\t\tself.game = ''\r\n\t\tself.x = 0\r\n\t\tself.y = 0\r\n\r\n\t\t# get paths, either saved or default, see functions\r\n\t\tself.path = self.set_path()\r\n\t\tself.playpath = self.set_playpath()\r\n\r\n\t\t# create the database to store data, see settings_db.py\r\n\t\tself.database = settings_db.db()\r\n\r\n\t\t# create the GUI, can also be put completely in the __init method\r\n\t\tself.interface()\r\n\r\n\t\t# for closing the database, when app is closed, see self._close function\r\n\t\tself.window.protocol(\"WM_DELETE_WINDOW\", self._close)\r\n\r\n\t\tself.helptext = '''Create new settings:\r\n1) Set the path to settings.txt and (optional) the path to Steam\r\n2) Select the Game you want\r\n3) Start the Launcher and set the settings you want to save\r\n4) Either close the Launcher or start the game \r\n(otherwise the settings.txt won't be saved)\r\n5) Enter a Name for your settings and click the button to save\r\n \r\nStart the game using settings:\r\n1) Select the game you want to start\r\n2) Select the settings you want to use in the dropdown menu\r\n3) Click \"Use\"\r\n4) Either start EU4 via Steam or the directly via the Play Button if Steampath is set\r\n \r\nDelete settings:\r\n1) Select the game\r\n2) Select the settings you want to delete in the dropdown menu\r\n3) Click Delete'''\r\n\r\n\tdef interface(self):\r\n\t\tself.window.title('PDX Settings Selector')\r\n\t\tself.style = ttk.Style()\r\n\r\n\t\t# HEADER\r\n\t\tself.frame_header = ttk.Frame(self.window)\r\n\t\tself.frame_header.grid(row=1, column=0)\r\n\t\t# self.logo = PhotoImage(file='eu4.gif')\r\n\t\t# removed because it crashed the compile process, not sure why\r\n\r\n\t\t# ttk.Label(self.frame_header, image=self.logo).grid(column=0, row=0, rowspan=2)\r\n\t\tself.header = ttk.Label(self.frame_header, text='Paradox\\nSettings Selector', font=('Arial', 20, 'bold'),\r\n\t\t\t\t\t\t\t\tjustify=CENTER).grid(row=0, column=0)\r\n\r\n\t\t# help\r\n\t\tself.helpframe = ttk.Frame(self.frame_header, padding=(5, 5))\r\n\t\tself.helpframe.grid(row=1, column=0)\r\n\t\tself.help = ttk.Button(self.helpframe, text=\"How to use this tool\", command=lambda: self.helpmessage())\r\n\t\tself.help.grid(row=0, column=0, columnspan=2, pady=5)\r\n\r\n\t\tttk.Separator(self.window, orient=HORIZONTAL).grid(row=2, column=0, sticky=\"ew\", pady=10)\r\n\r\n\t\t# give me your path\r\n\t\tself.frame_path = ttk.LabelFrame(self.window, text='Path', padding=(3, 3), height=75, width=300, borderwidth=3)\r\n\t\tself.frame_path.grid(row=3, column=0)\r\n\t\tself.frame_path.grid_propagate(0)\r\n\t\tself.frame_pathentry = ttk.Entry(self.frame_path, width=47)\r\n\t\tself.frame_pathentry.grid(row=0, column=0, columnspan=2)\r\n\t\tself.frame_pathentry.insert(0, self.path)\r\n\r\n\t\tself.frame_game = ttk.LabelFrame(self.window, text='Select Game', padding=(3, 3), height=75, width=300, borderwidth=3)\r\n\t\tself.frame_game.grid(row=4, column=0)\r\n\t\tself.frame_game.grid_propagate(0)\r\n\t\tself.eubutton = ttk.Button(self.frame_game, text='Europa Universalis IV', width=22,\r\n\t\t\t\t\t\t\t\t\tcommand=lambda: self.populate_selectionbox('Europa Universalis IV'))\r\n\t\tself.hoibutton = ttk.Button(self.frame_game, text='Hearts of Iron IV', width=22,\r\n\t\t\t\t\t\t\t\t\tcommand=lambda: self.populate_selectionbox('Hearts of Iron IV'))\r\n\t\tself.stebutton = ttk.Button(self.frame_game, text='Stellaris', width=22,\r\n\t\t\t\t\t\t\t\t\tcommand=lambda: self.populate_selectionbox('Stellaris'))\r\n\t\tself.ckbutton = ttk.Button(self.frame_game, text='Crusader Kings II', width=22,\r\n\t\t\t\t\t\t\t\t\tcommand=lambda: self.populate_selectionbox('Crusader Kings II'))\r\n\t\tself.eubutton.grid(row=1, column=0)\r\n\t\tself.hoibutton.grid(row=1, column=1)\r\n\t\tself.stebutton.grid(row=2, column=0)\r\n\t\tself.ckbutton.grid(row=2, column=1)\r\n\t\tself.ckbutton['state'] = 'disabled'\r\n\r\n\t\t# select path\r\n\t\tself.frame_pathbutton = ttk.Button(self.frame_path, text='Select Paradox Documents Path...',\r\n\t\t\t\t\t\t\t\t\t\t command=lambda: self.getdirectory())\r\n\t\tself.frame_pathbutton.grid(row=1, column=0, sticky=\"w\")\r\n\r\n\t\tttk.Separator(self.window, orient=HORIZONTAL).grid(row=5, column=0, sticky=\"ew\", pady=10)\r\n\r\n\t\t# insert name\r\n\t\tself.frame_name = ttk.LabelFrame(self.window, text='Name', padding=(3, 3), height=75, width=300, borderwidth=3)\r\n\t\tself.frame_name.grid(row=6, column=0)\r\n\t\tself.frame_name.grid_propagate(0)\r\n\t\tself.frame_name_entry = ttk.Entry(self.frame_name, width=47)\r\n\t\tself.frame_name_entry.grid(row=0, column=0, columnspan=2)\r\n\r\n\t\t# parsing settings.txt\r\n\t\tself.frame_setting = ttk.Button(self.frame_name, text='Scrape and Save Current Settings',\r\n\t\t\t\t\t\t\t\t\t\tcommand=lambda: self.scrape(self.game))\r\n\t\tself.frame_setting.grid(row=1, column=0, sticky=\"w\")\r\n\r\n\t\tttk.Separator(self.window, orient=HORIZONTAL).grid(row=7, column=0, sticky=\"ew\", pady=10)\r\n\r\n\t\t# selector\r\n\t\tself.frame_selector = ttk.LabelFrame(self.window, text='Selector', padding=(3, 3), borderwidth=3, height=55,\r\n\t\t\t\t\t\t\t\t\t\t\t width=300)\r\n\t\tself.frame_selector.grid(row=8, column=0)\r\n\t\tself.frame_selector.grid_propagate(0)\r\n\r\n\t\tselection = StringVar()\r\n\t\tself.selectionbox = ttk.Combobox(self.frame_selector, textvariable=selection)\r\n\t\tself.selectionbox.grid(row=0, column=0, sticky=\"e\")\r\n\t\t# self.populate_selectionbox()\r\n\r\n\t\tself.use_button = ttk.Button(self.frame_selector, text=\"Use\", width=10, command=lambda: self.write_settings())\r\n\t\tself.use_button.grid(row=0, column=1, sticky=\"e\")\r\n\r\n\t\tself.delete_button = ttk.Button(self.frame_selector, text=\"Delete\", width=10,\r\n\t\t\t\t\t\t\t\t\t\tcommand=lambda: self.delete_settings())\r\n\t\tself.delete_button.grid(row=0, column=2, sticky=\"e\")\r\n\r\n\t\tttk.Separator(self.window, orient=HORIZONTAL).grid(row=9, column=0, sticky=\"ew\", pady=10)\r\n\r\n\t\t# play-section\r\n\t\tself.frame_play = ttk.LabelFrame(self.window, text='Play', padding=(3, 3), height=80, width=300)\r\n\t\tself.frame_play.grid(row=10, column=0)\r\n\t\tself.frame_play.grid_propagate(0)\r\n\r\n\t\tself.playentry = ttk.Entry(self.frame_play, width=47)\r\n\t\tself.playentry.grid(row=0, column=0, columnspan=2)\r\n\t\tself.playentry.insert(0, self.playpath)\r\n\r\n\t\tself.play_button = ttk.Button(self.frame_play, text=\"Play\", width=20, command=lambda: self.start())\r\n\t\tself.play_button.grid(row=1, column=0, sticky='w')\r\n\r\n\t\tself.play_setpath = ttk.Button(self.frame_play, text=\"Set Steam Path...\", width=20,\r\n\t\t\t\t\t\t\t\t\t command=lambda: self.getplaydirectory())\r\n\t\tself.play_setpath.grid(row=1, column=1, sticky='e')\r\n\r\n\tdef helpmessage(self):\r\n\t\tmessagebox.showinfo(title=\"How to use\", message=self.helptext)\r\n\r\n\tdef set_path(self):\r\n\t\tif os.path.exists('path.txt'):\r\n\t\t\twith open('path.txt', 'r') as f:\r\n\t\t\t\treturn f.read()\r\n\t\telse:\r\n\t\t\twith open('path.txt', 'w') as f:\r\n\t\t\t\tf.write('C:\\\\Users\\\\YOURUSERNAME\\\\Documents\\\\Paradox Interactive')\r\n\t\t\t\treturn 'C:\\\\Users\\\\YOURUSERNAME\\\\Documents\\\\Paradox Interactive'\r\n\r\n\tdef set_playpath(self):\r\n\t\tif os.path.exists('playpath.txt'):\r\n\t\t\twith open('playpath.txt', 'r') as f:\r\n\t\t\t\treturn f.read()\r\n\t\telse:\r\n\t\t\twith open('playpath.txt', 'w') as f:\r\n\t\t\t\t# print('why')\r\n\t\t\t\tf.write('C:\\\\Program Files\\\\Steam\\\\steamapps\\\\common')\r\n\t\t\t\treturn 'C:\\\\Program Files\\\\Steam\\\\steamapps\\\\common'\r\n\r\n\tdef start(self):\r\n\t\t# starts the game with the used settings\r\n\t\tworkpath = os.getcwd()\r\n\t\ttry:\r\n\t\t\tos.chdir(self.playpath)\r\n\t\texcept FileNotFoundError:\r\n\t\t\tmessagebox.showerror(title=\"Path not found\", message=\"Could not find specified path!\")\r\n\t\t\treturn\r\n\t\tgame = self.game\r\n\t\tif game == '':\r\n\t\t\tmessagebox.showinfo(title=\"No Game selected\", message='Please select the game you want to start')\r\n\t\telif game == 'Europa Universalis IV':\r\n\t\t\tos.chdir(game)\r\n\t\t\tos.system(r'eu4.exe -skiplauncher')\r\n\t\telif game == 'Hearts of Iron IV':\r\n\t\t\tos.chdir(game)\r\n\t\t\t# HoI does not have -skiplauncher and -nolauncher ignores for some reason the mods, so we have to do this...\r\n\t\t\tspecialhoistring = 'hoi4.exe -nolauncher'\r\n\t\t\tdata = self.database.get(self.selectionbox.get(), self.game)\r\n\t\t\tmodlist = data['mods'].split(',')\r\n\t\t\tfor mod in modlist:\r\n\t\t\t\tspecialhoistring = specialhoistring + ' -mod=mod/' + mod\r\n\t\t\t# print(specialhoistring)\r\n\t\t\tos.system(specialhoistring)\r\n\t\telif game == 'Stellaris':\r\n\t\t\tos.chdir(game)\r\n\t\t\tos.system(r'stellaris.exe -skiplauncher')\r\n\t\tos.chdir(workpath)\r\n\r\n\tdef _close(self):\r\n\t\t\"\"\"closes the db, before closing the window\"\"\"\r\n\t\tself.database.close()\r\n\t\tself.window.destroy()\r\n\r\n\tdef getdirectory(self):\r\n\t\t\"\"\"Asks Directory for Documents Paradox Folder\"\"\"\r\n\t\tself.path = filedialog.askdirectory()\r\n\t\tself.frame_pathentry.delete(0, END)\r\n\t\tself.frame_pathentry.insert(0, self.path)\r\n\t\twith open('path.txt', 'w') as f:\r\n\t\t\tf.write(self.path)\r\n\r\n\tdef getplaydirectory(self):\r\n\t\t\"\"\"Asks Steam/steamapps/common folder for game starting\"\"\"\r\n\t\tself.playpath = filedialog.askdirectory()\r\n\t\tself.playentry.delete(0, END)\r\n\t\tself.playentry.insert(0, self.playpath)\r\n\t\twith open('playpath.txt', 'w') as f:\r\n\t\t\tf.write(self.playpath)\r\n\r\n\tdef populate_selectionbox(self, game):\r\n\t\t\"\"\"Puts the valid settings in the selectionbox\"\"\"\r\n\t\t# games = {'Europa Universalis IV': 'EU4', 'Hearts of Iron IV': 'HoI 4', 'Stellaris': 'Stellaris'}\r\n\t\tnames = []\r\n\t\tself.game = game\r\n\t\tfor row in self.database:\r\n\t\t\tif row['game'] == game:\r\n\t\t\t\tnames.append(row['name'])\r\n\t\tself.selectionbox.config(values=names)\r\n\t\tif names:\r\n\t\t\tself.selectionbox.set(names[-1])\r\n\t\telse:\r\n\t\t\t# set to empty when no settings to select\r\n\t\t\tself.selectionbox.set('')\r\n\r\n\tdef scrape(self, game):\r\n\t\t\"\"\"Scrapes the settings.txt for settings, takes name of the game\"\"\"\r\n\t\tset_name = self.frame_name_entry.get()\r\n\t\t# check if name is entered:\r\n\t\tif len(set_name) == 0:\r\n\t\t\tmessagebox.showinfo(title=\"No Name\", message=\"Please enter name for settings\")\r\n\t\t\treturn\r\n\t\tif self.game == '':\r\n\t\t\tmessagebox.showinfo(title=\"No Game\", message=\"Please select the game you want to save settings for\")\r\n\t\t\treturn\r\n\t\t# print (self.database.check(set_name))\r\n\t\t# check if name is in use:\r\n\t\tif self.database.check(game, set_name):\r\n\t\t\tmessagebox.showinfo(title=\"Duplicate\",\r\n\t\t\t\t\t\t\t\tmessage=\"Name is already used for settings. Either Delete Set to create a new one under this name or choose a different name\")\r\n\t\t\treturn\r\n\t\tworkpath = os.getcwd()\r\n\t\tos.chdir(self.path + '\\\\' + game)\r\n\t\t# print(os.getcwd())\r\n\t\t# error message if path is not correct, since this will already throw an exception, no further\r\n\t\t# handling down for the open command.\r\n\t\t# print(linecache.getline('settings.txt', 5))\r\n\t\ttry:\r\n\t\t# using linenumber because it's always the same and x= is twice in the file\r\n\t\t\tself.x = int(number_re(linecache.getline('settings.txt', 5)))\r\n\t\t\tself.y = int(number_re(linecache.getline('settings.txt', 6)))\r\n\t\texcept FileNotFoundError:\r\n\t\t\tmessagebox.showerror(title='Parsing Error',\r\n\t\t\t\t\t\t\t\t message='Error parsing settings.txt, did you set the path correctly?')\r\n\t\t\treturn\r\n\t\tself.dlc = []\r\n\t\tself.mod = []\r\n\t\tfile = open('settings.txt', 'r')\r\n\t\t# going through the file, saving the relevant information\r\n\t\t# could have used RE instead of list-slicing\r\n\t\tfor line in file:\r\n\t\t\t# print(line)\r\n\t\t\tif 'language' in line:\r\n\t\t\t\tself.lang = line[12:-2]\r\n\t\t\telif 'fullScreen' in line:\r\n\t\t\t\tif ('no' in line[12:]):\r\n\t\t\t\t\tself.fs = 0\r\n\t\t\t\telif ('yes' in line[12:]):\r\n\t\t\t\t\tself.fs = 1\r\n\t\t\telif 'borderless' in line:\r\n\t\t\t\tif ('no' in line[12:]):\r\n\t\t\t\t\tself.bl = 0\r\n\t\t\t\telif ('yes' in line[12:]):\r\n\t\t\t\t\tself.bl = 1\r\n\t\t\telif '.dlc' in line:\r\n\t\t\t\tself.dlc.append(line[6:-2])\r\n\t\t\telif '.mod' in line:\r\n\t\t\t\tself.mod.append(line[6:-2])\r\n\t\t# put the data in the database\r\n\t\tself.database.new(game=game, name=set_name, lang=self.lang, rx=self.x, ry=self.y, fs=self.fs, bl=self.bl,\r\n\t\t\t\t\t\t mods=self.mod,\r\n\t\t\t\t\t\t dlc=self.dlc)\r\n\t\tself.populate_selectionbox(self.game)\r\n\t\tmessagebox.showinfo(title=\"Done\", message=\"Saved Current settings.txt for \" + game + \" under \" + set_name)\r\n\t\tself.frame_name_entry.delete(0, END)\r\n\t\t# I always go back to the workpath, isn't really necessary\r\n\t\tos.chdir(workpath)\r\n\r\n\tdef write_settings(self):\r\n\t\t\"\"\"Writes the data into the settings.txt, no arguments, uses self.game\"\"\"\r\n\t\tdata = self.database.get(self.selectionbox.get(), self.game)\r\n\t\tworkpath = os.getcwd()\r\n\t\tos.chdir(self.path + '\\\\' + self.game)\r\n\t\t# print(data)\r\n\t\t# print(os.getcwd())\r\n\t\ttry:\r\n\t\t\twith open('settings.txt', 'r') as f:\r\n\t\t\t\tfile = f.read()\r\n\t\texcept FileNotFoundError:\r\n\t\t\tmessagebox.showerror(title='Not Found', message=\"Couldn't find settings.txt, something is wrong with the Path!\")\r\n\t\t\treturn\r\n\t\t# put content of settings.txt in text to do string-manipulations\r\n\t\ttext = file.splitlines()\r\n\t\t# uses linenumber, breaks, when PDX decides to change layout of settings.txt\r\n\t\t# some of this could have be done nice with REs now that I think about it\r\n\t\t# print(text)\r\n\t\ttext[1] = 'language=\"l_' + data['lang'] + '\"'\r\n\t\ttext[4] = '\\t\\tx=' + str(data['rx'])\r\n\t\ttext[5] = '\\t\\ty=' + str(data['ry'])\r\n\t\t# writes data\r\n\t\tfs = self.yes_no(data['fs'])\r\n\t\tindex = [i for i, s in enumerate(text) if 'fullScreen' in s]\r\n\t\ttext[index[0]] = '\\tfullScreen=' + fs\r\n\t\tbl = self.yes_no(data['bl'])\r\n\t\tindex = [i for i, s in enumerate(text) if 'borderless' in s]\r\n\t\ttext[index[0]]= '\\tborderless=' + bl\r\n\t\t# remove current dlc/mods in settings.txt to write the ones we want\r\n\t\ttext = [x for x in text if '.dlc' not in x]\r\n\t\ttext = [x for x in text if '.mod' not in x]\r\n\t\t# print(text)\r\n\t\t# put dlcs and mods from database into a list\r\n\t\tdlclist = data['dlc'].split(',')\r\n\t\t# print(dlclist)\r\n\t\tmodlist = data['mods'].split(',')\r\n\t\t# print(modlist)\r\n\t\t# prepare for if-monster\r\n\t\t# the different games want the mods/dlc part at different part of the settings file\r\n\t\t# when no dlcs are activated the part is removed and needs to be added empty before filling up with DLCs & Mods\r\n\t\tif self.game == 'Europa Universalis IV':\r\n\t\t\tif 'last_dlcs={' not in text:\r\n\t\t\t\ttext = text + ['last_dlcs={','}']\r\n\t\t\tif 'last_mods={' not in text:\r\n\t\t\t\ttext = text + ['last_mods={','}']\r\n\t\tif self.game == 'Hearts of Iron IV':\r\n\t\t\tif 'last_dlcs={' not in text:\r\n\t\t\t\ttext.insert(self.select_contain(text, 'hints') + 1, 'last_dlcs={')\r\n\t\t\t\ttext.insert(self.select_contain(text, 'last_dlcs={') + 1, '}')\r\n\t\t\tif 'last_mods={' not in text:\r\n\t\t\t\ttext.insert(self.select_contain(text, 'counter'), 'last_mods={')\r\n\t\t\t\ttext.insert(self.select_contain(text, 'counter'), '}')\r\n\t\tif self.game == 'Stellaris':\r\n\t\t\tif 'last_dlcs={' not in text:\r\n\t\t\t\ttext.insert(self.select_contain(text, 'name=') + 1, 'last_dlcs={')\r\n\t\t\t\ttext.insert(self.select_contain(text, 'last_dlcs={') + 1, '}')\r\n\t\t\tif 'last_mods={' not in text:\r\n\t\t\t\ttext.insert(self.select_contain(text, 'autosave'), 'last_mods={')\r\n\t\t\t\ttext.insert(self.select_contain(text, 'autosave'), '}')\r\n\t\t# now last_dlcs and last_mods exist at the correct part of the setting.txt, let's populate it\r\n\t\tif dlclist != ['']:\r\n\t\t\tfor dlc in dlclist:\r\n\t\t\t\ttext.insert(self.select_contain(text, 'last_dlcs') + 1, '\\t\"dlc/' + dlc + '\"')\r\n\t\tif modlist != ['']:\r\n\t\t\tfor mod in modlist:\r\n\t\t\t\ttext.insert(self.select_contain(text, 'last_mods') + 1, '\\t\"mod/' + mod + '\"')\r\n\t\t# make text into a multiline string to write to data\r\n\t\ttext2 = [x + '\\n' for x in text]\r\n\t\ttext2 = ''.join(text2)\r\n\t\twith open('settings.txt', 'w') as f:\r\n\t\t\tf.write(text2)\r\n\t\t\tf.close()\r\n\t\tos.chdir(workpath)\r\n\r\n\tdef select_contain(self, list, string):\r\n\t\t\"\"\"selects the line in list that contains string, returns index\"\"\"\r\n\t\t# why didn't I use text[text.index()] directly?\r\n\t\tfor item in list:\r\n\t\t\tif string in item:\r\n\t\t\t\t# print(item)\r\n\t\t\t\treturn list.index(item)\r\n\r\n\tdef yes_no(self, int):\r\n\t\t\"\"\"turns int into yes or no\"\"\"\r\n\t\tif int == 0:\r\n\t\t\treturn 'no'\r\n\t\telif int == 1:\r\n\t\t\treturn 'yes'\r\n\r\n\tdef delete_settings(self):\r\n\t\t\"\"\"deletes settings from database\"\"\"\r\n\t\tself.database.delete(self.selectionbox.get(), self.game)\r\n\t\tself.populate_selectionbox(self.game)\r\n\r\n\r\n\r\n###############################################################################################\r\n\r\ndef main():\r\n\twindow = Tk()\r\n\t# build me a GUI\r\n\tselector = Selector(window)\r\n\twindow.mainloop()\r\n\r\n\r\ndef number_re(text):\r\n\tfind = re.search('[0-9]+', text)\r\n\tif find:\r\n\t\treturn find.group()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","sub_path":"settings_selector.py","file_name":"settings_selector.py","file_ext":"py","file_size_in_byte":16156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"346068359","text":"#\n# Arquivo com exemplos para manipulação de dados na Internet\n#\n\nimport urllib.request\n\ndef ConectaInternet():\n objUrl = urllib.request.urlopen(\"http://www.google.com\")\n\n if objUrl.getcode() == 200:\n dados = objUrl.read()\n print(dados)\n\nConectaInternet()\n","sub_path":"ConexaoInternet_start.py","file_name":"ConexaoInternet_start.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190370600","text":"import sys\nfrom string import ascii_letters\n\n# part one AND part two\ncoords = [ (int(x.split(',')[0]), int(x.split(',')[1])) for x in sys.stdin.readlines() ]\n\ndef dist(a: (int, int), b: (int, int)) -> int:\n return dist_x(a, b) + dist_y(a, b)\n\ndef dist_x(a: (int, int), b: (int, int)) -> int:\n return abs(b[0] - a[0])\n\ndef dist_y(a: (int, int), b: (int, int)) -> int:\n return abs(b[1] - a[1])\n\ndef isFinite(x: (int, int), ys: [(int, int)]) -> bool:\n left = [ x[0] > y[0] and dist_y(y, x) <= dist_x(y, x) for y in ys if x != y ]\n right = [ x[0] < y[0] and dist_y(y, x) <= dist_x(y, x) for y in ys if x != y ]\n down = [ x[1] < y[1] and dist_y(y, x) >= dist_x(y, x) for y in ys if x != y ]\n up = [ x[1] > y[1] and dist_y(y, x) >= dist_x(y, x) for y in ys if x != y ]\n return any(left) and any(right) and any(down) and any(up)\n\nmax_x, max_y = max(coords, key=lambda x: x[0])[0], max(coords, key=lambda x: x[1])[1]\n\nwidth = max_x\nheight = max_y\n\ngrid = [ '' ] * height\nareas = { c: 0 for c in coords}\nchars = { coords[i]: ascii_letters[i] for i in range(len(coords)) }\n\nsafe = 0\nfor i in range(height):\n for j in range(width):\n distances = { x: dist((j, i), x) for x in coords }\n total_dist = sum(distances.values())\n safe += 1 if total_dist < 10000 else 0\n closest = min(distances, key=distances.get)\n closest_dist = distances[closest]\n # if owned by one\n if sum(v == closest_dist for v in distances.values()) == 1:\n grid[i] += chars[closest]\n areas[closest] += 1\n else: grid[i] += '.'\n\nfinites = { k: v for (k, v) in areas.items() if isFinite(k, coords) }\nmax_area = max(finites, key=finites.get)\nprint('{}: {}'.format(max_area, areas[max_area]))\nprint('Safe size: {}'.format(safe))\n\nwith open('out.txt', 'w+') as f:\n for l in grid:\n f.write(''.join(l) + '\\n')\n","sub_path":"6/6.py","file_name":"6.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535327770","text":"from bs4 import BeautifulSoup\nfrom bs4.dammit import EncodingDetector\nimport requests\n\n\ndef desi_crawler(u_r_l):\n web_list = []\n url = u_r_l\n web_list.append(url)\n domain = url\n\n if \"www.\" not in domain:\n div = domain.replace('//', ' ').replace('.', ' ').split()\n domain = div[1]\n else:\n div = domain.replace('//', ' ').replace('.', ' ').split()\n domain = div[2]\n\n for url in web_list:\n response = requests.get(url)\n http_encoding = response.encoding if 'charset' in response.headers.get('content-type', '').lower() else None\n html_encoding = EncodingDetector.find_declared_encoding(response.content, is_html=True)\n encoding = html_encoding or http_encoding\n soup = BeautifulSoup(response.content, from_encoding=encoding)\n\n for link in soup.find_all('a', href=True):\n if domain in link['href']:\n if link['href'] not in web_list:\n web_list.append(link['href'])\n\n\ndef fingerprint_webapp(u_r_l):\n # values = ['X-AspNetMvc-Version', 'X-AspNet-Version', 'Server', 'X-Powered-By']\n url = u_r_l\n response = requests.get(url)\n for key, value in response.headers.iteritems():\n print (key, \":\", value)\n","sub_path":"webmap/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"439754072","text":"from pathlib import Path\nfrom importlib import import_module\nfrom helper import clean_width_cache\nfrom subprocess import call\n# from multiprocessing import Pool, cpu_count\ntry:\n has_mpi = True\n from mpi4py import rank, size, world\nexcept ImportError:\n has_mpi = False\n rank = 0\n size = 1\n\nroot = Path(\".\")\n\n# Customize this to exclude the submodules\nexclude_mods = [\"helper\", \"test\"]\nexclude_files = [\"__init__\", ]\nfunc=\"plot_main\"\n\n\n# Minimal class for terminal ANSI color output\nclass TColors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\ndef run_plot(mod_name, func=func):\n \"\"\"Single function to run the plot_main inside module m\"\"\"\n try:\n m = import_module(mod_name)\n except ImportError:\n print(TColors.FAIL + \"Module {0} import error!\".format(mod_name) \\\n + TColors.ENDC)\n return False\n if hasattr(m, func):\n try:\n getattr(m, func)()\n print(TColors.OKGREEN + \"Module {0} plot finish!\".format(mod_name) \\\n + TColors.ENDC)\n return True\n except Exception as e:\n print(TColors.FAIL + \"Module {0} plot failed with {1}!\".format(mod_name, e) \\\n + TColors.ENDC)\n return False\n \ndef main():\n jobs = []\n for f in root.rglob(\"*.py\"):\n # parents starting from root\n parents = list(map(lambda x: x.name, f.parents))[-1::-1]\n script_name = f.with_suffix(\"\").name\n if (len(parents) > 1) and \\\n (all([p not in exclude_mods for p in parents[1:]])) and \\\n (script_name not in exclude_files):\n # import the module and test if plot_main is inside\n mod_name = \".\".join(parents[1:] + [script_name])\n jobs.append(mod_name)\n # print(mod_name)\n # try:\n # m = import_module(mod_name)\n # except ImportError:\n # print(TColors.FAIL + \"Module {0} import error!\".format(mod_name) \\\n # + TColors.ENDC)\n # continue\n # if hasattr(m, func):\n # try:\n # getattr(m, func)()\n # print(\"Module {0} plot finish!\".format(mod_name))\n # except Exception as e:\n # print(\"Module {0} plot failed with {1}!\".format(mod_name, e))\n if has_mpi:\n world.barrier()\n for i, mod_ in enumerate(jobs):\n if i % size == rank:\n run_plot(mod_)\n \n if rank == 0: \n clean_width_cache()\n \n if has_mpi:\n world.barrier()\n\n # Clean up width\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/run_all.py","file_name":"run_all.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"151574729","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n\"\"\"\n\n跟卖检查\n\n\"\"\"\n\nimport traceback\nfrom fun1 import *\n\nstime = int(time.time())\ncdir = os.path.dirname(os.path.abspath(__file__))\nlogfile = cdir + \"/00gm.log\"\nfile_write(logfile, \"{}\\n{}\\n\\n\".format(__file__, now()), 'w')\n\ndb = mssqlc.mssql(CONFIG3) if IS_MSSQL else mysqlc.mysql(CONFIG)\nDIC['gm2mail'] = {}\n\nUARGS = sys.argv\n\nisellers = db.fetch(\"select SalesID from ckshops where SalesID!=''\") # 取出全部店铺数据\nDIC['db_sellers'] = add_list(isellers)\nprint('db_sellers: {}'.format(len(DIC['db_sellers'])))\n\nManagers = db.get_dict(\"select Type_Name,FllowManage from ckproducttype where FllowManage!=''\")\n# print(Managers)\n\nfor key,val in Managers.items():\n DIC['gm2mail'][key] = []\n\n# print(DIC['gm2mail'])\n\nManagers1 = list(Managers.values())\nManagers3 = list(set(\",\".join(Managers1).split(',')))\nManagers4 = \"','\".join(Managers3)\n\ndb2 = mssqlc.mssql(CONFIG4) if IS_MSSQL else mysqlc.mysql(CONFIG)\nUsers = db2.get_dict(\"select UserCode,Description from sys_user where UserCode in ('{}')\".format(Managers4))\nprint(Users)\n\ndb2.close()\n\n# exit(5)\n\ndef main(product_id, asin='', Country=''):\n\n try:\n parse_gm_page(product_id, asin, Country)\n except Exception as e:\n ss = traceback.format_exc()\n print(\"https://{}/gp/offer-listing/{}/ref=olp_page_1?ie=UTF8&f_all=true --------------- {}\".format(Country, asin, ss))\n\nmain(5893)\nexit(44)\n\ncountry = ''\nMAXID = 0\ndtime = days_before(0, 1)\n\n# 单独采集P_ID\nif len(UARGS) == 2 and UARGS[1].isdigit():\n main(UARGS[1])\n exit('-----------------')\n\n# 单独采集国家\nif len(UARGS) == 2:\n country = wcountry(UARGS[1])\n\n# 指定采集时间 cp.py de -1\nif len(UARGS) == 3 and (UARGS[2].isdigit() or UARGS[2].startswith(\"-\")):\n country = wcountry(UARGS[1])\n dtime = days_before(int(UARGS[2]), 1)\n\n# 指定ID范围、采集时间、国家 cp.py de 0 1000-5000, UARGS[1]是0时不限国家\nif len(UARGS) == 4 :\n country = \"and P_ID between {}\".format(UARGS[3].replace(\"-\", ' and ')) + wcountry(UARGS[1])\n dtime = days_before(int(UARGS[2]), 1)\n\ncond = \"State!=2 and is_gm=1 and (gm_time<'{}' or gm_time is null) and P_ID>{} {}\"\n\nsql0 = \"select count(*) from ckfbaproducts where {}\".format(cond).format( dtime, MAXID, country)\nsql1 = \"select P_ID, ASIN, Country from ckfbaproducts where {} limit 10\"\nsql2 = \"select top 10 P_ID,ASIN,Country from CKFBAProducts where {}\"\n\nnum = db.field(sql0)\npagesize = 10\npages = math.ceil(num / pagesize)\nprint(\"num: {} pages: {}\\n\".format(num, pages))\nprint(sql0)\n\ndb.close()\n\nfor i in range(1, pages + 1):\n try:\n db = mssqlc.mssql(CONFIG3) if IS_MSSQL else mysqlc.mysql(CONFIG)\n sql = sql2.format(cond).format( dtime, MAXID, country) if IS_MSSQL else sql1.format(cond).format( dtime, MAXID, country)\n rows = db.fetch(sql)\n print(i, rows)\n print(sql)\n\n if not rows: continue\n MAXID = max([W[0] for W in rows])\n\n DIC['fp'] = open(logfile, \"a\", encoding='UTF-8')\n threads_run(main, rows)\n DIC['fp'].close()\n\n print(\"{} 休眠 {}s\".format(i, SLEEPTIME) )\n time.sleep(SLEEPTIME)\n\n db.close()\n\n except Exception as e:\n ss = traceback.format_exc()\n print(\"forError {}: {} ----\\n {}\".format(i, e, ss))\n file_write( logfile, \"forError {}: {} ----\\n {}\".format(i, e, ss), 'a')\n\n\nprint(DIC['gm2mail'])\n\nprint(\"start mail ................................\")\n\n\nfor key, val in DIC['gm2mail'].items():\n if not val: continue\n users = Managers[key]\n if not users: continue\n mailaddrs = users.split(\",\")\n for i in mailaddrs:\n if not i in Users: continue\n receiver = Users[i]\n content = mail_txt(val, MAIL['template'])\n # print(\"{} \\n {}\\....\\n\".format(receiver, content))\n # sendEmail(MAIL['smtp'], MAIL['port'], MAIL['user'], MAIL['passwd'], receiver, MAIL['title'], content, 'html')\n\netime = time.time() - stime\nrun_time = \"%.2fs \" % etime\nprint(run_time)\n\nlogtxt = \"num: {}, pages: {}\\n\".format(num, pages)\nlogtxt += \"每页耗时: {}, 总耗时: {}, 内存: {}\\n\".format( round(etime/max(pages,1), 2), run_time, mem())\nlogtxt += \"验证码 {}\\n\".format(DIC['yzm'])\nlogtxt += now() + \"\\n\"\nfile_write(logfile, logtxt, 'a')\n","sub_path":"amazon/gm.py","file_name":"gm.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"626816924","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Feb 8 21:45:13 2020\r\n\r\n@author: Varun\r\n\"\"\"\r\n##########importing libraries###################\r\nimport os\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\nimport struct\r\nimport numpy as np\r\nimport random\r\nimport operator\r\nimport matplotlib.pyplot as plt\r\nimport gzip\r\n###########changing working directory################################\r\nmypath=r'C:\\Users\\Varun\\Desktop\\Neural Networks\\hw2'\r\nos.chdir(mypath)\r\nonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\r\n##########reading training data & labels######################################\r\nwith gzip.open('train-labels-idx1-ubyte.gz', 'rb') as f:\r\n zero, data_type, dims = struct.unpack('>HBB', f.read(4))\r\n shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))\r\n train_labels=np.fromstring(f.read(), dtype=np.uint8).reshape(shape)\r\nwith gzip.open('train-images-idx3-ubyte.gz', 'rb') as f:\r\n zero, data_type, dims = struct.unpack('>HBB', f.read(4))\r\n shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))\r\n train_images=np.fromstring(f.read(), dtype=np.uint8).reshape(shape)\r\n#############labels##########################################################\r\ntrain_labels_coded=list(train_labels)\r\ntrain_labels_coded_n_values = np.max(train_labels_coded) + 1\r\nOneHotEncoded_train_labels_coded=np.eye(train_labels_coded_n_values)[train_labels_coded]\r\n######################initialise weights with random values###############################\r\nSizeofInputVectors=train_images[0].size\r\nSizeofOutputVectors=max(train_labels)-min(train_labels)+1\r\nWeights=[]\r\nfor i in range(0,(SizeofOutputVectors)):\r\n Weights.append([round(random.uniform(-1, 1),2) for j in range(0,SizeofInputVectors)])\r\n##########prepared data set#######################3\r\ntraining_data_processed=[]\r\nfor i in range(0,len( train_images)):\r\n temp=train_images[i].tolist()\r\n merged=[] \r\n for j in temp:\r\n merged=merged+j \r\n training_data_processed.append(merged)\r\n\r\n#############################################################\r\nprint(\"Dim of Weights\",len(Weights[0]),len(Weights))\r\nprint(\"Dim of training data\",len(training_data_processed[0]),len(training_data_processed))\r\nprint(\"Dim of train labels\",len(OneHotEncoded_train_labels_coded))\r\n###################configure number of data points (n) and eta###################################3\r\n###########################################################################################\r\n###########################################################################################\r\neta=1\r\nthreshold=11#missclassificaton rate is alwasy less than this\r\nn=60000#no. of datapoints\r\n###########################################################################################\r\n###########################################################################################\r\n###########################################################################################\r\n\r\nprint(\"eta\",eta)\r\nprint(\"threshold or maximum error rate\",threshold)\r\nprint(\"data points or value of n\",n)\r\n\r\ntraining_data_processed=training_data_processed[:n]\r\nOneHotEncoded_train_labels_coded=OneHotEncoded_train_labels_coded[:n]\r\n\r\nepoch=0\r\nerror=0\r\nmissclassificationrate=[]\r\nfor k in range(0,len(training_data_processed)):\r\n trainingimage=training_data_processed[k]\r\n ImagePred=[(np.dot(trainingimage,Weights[j])) for j in range(0,SizeofOutputVectors)]\r\n maxval=max(ImagePred)\r\n Output=[1.0 if j==maxval and j>0 else 0.0 for j in ImagePred ]\r\n try:\r\n indexof1inOutput=Output.index(1)\r\n except:\r\n #print(ImagePred)\r\n indexof1inOutput=np.nan\r\n \r\n indexofcorrect=OneHotEncoded_train_labels_coded[k].tolist().index(1)\r\n if indexofcorrect!=indexof1inOutput:\r\n error=error+1\r\nmissclassificationrate.append(error)\r\nprint(\"Missclassifications with random initial weights\",error)\r\nprint(\"Missclassification rate with random initial weights\",(error/n)*100)\r\n\r\n##########################BEGIN TRAINING###################################\r\nepoch=1\r\nwhile True:\r\n error=0\r\n for k in range(0,len(training_data_processed)):\r\n trainingimage=training_data_processed[k]\r\n ImagePred=[(np.dot(trainingimage,Weights[j])) for j in range(0,SizeofOutputVectors)]\r\n maxval=max(ImagePred)\r\n Output=[1.0 if j==maxval and j>0 else 0.0 for j in ImagePred ] \r\n try:\r\n indexof1inOutput=Output.index(1)\r\n except:\r\n #print(ImagePred)\r\n indexof1inOutput=np.nan \r\n indexofcorrect=OneHotEncoded_train_labels_coded[k].tolist().index(1) \r\n \r\n if indexofcorrect!=indexof1inOutput:\r\n error=error+1\r\n \r\n D=OneHotEncoded_train_labels_coded[k].tolist()\r\n map_object = list(map(operator.sub, D, Output)) \r\n Weightsprior=Weights \r\n \r\n #####weight adjustment####################### \r\n WeightsNew=[]\r\n for wtx in range(0,len(Weights)):\r\n partb=np.dot(eta*map_object[wtx],trainingimage)\r\n parta=Weights[wtx]\r\n WeightsNew.append(list(map(operator.add, parta, partb)))\r\n Weights=WeightsNew\r\n #else:\r\n #don't adjust weight\r\n missclassificationrate.append(error)\r\n epoch=epoch+1\r\n print(\"epoch.....\",epoch)\r\n print(\"error.....\",error)\r\n \r\n if (error/n)*100 <= threshold:\r\n break\r\n\r\nprint(\"Training Error Rate\", (error/n)*100)\r\nprint(\"Missclassifications\",missclassificationrate)\r\nprint(\"Epochs\",[i for i in range(1,epoch+1)])\r\n\r\n#################################################################\r\nFinalWeights=Weights\r\n#################################################################\r\n#################################################################\r\n#################################################################\r\n#################################################################\r\n######################testing###################################\r\n\r\nonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\r\nwith gzip.open('t10k-labels-idx1-ubyte.gz', 'rb') as f:\r\n zero, data_type, dims = struct.unpack('>HBB', f.read(4))\r\n shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))\r\n test_labels=np.fromstring(f.read(), dtype=np.uint8).reshape(shape)\r\n \r\n\r\nwith gzip.open('t10k-images-idx3-ubyte.gz', 'rb') as f:\r\n zero, data_type, dims = struct.unpack('>HBB', f.read(4))\r\n shape = tuple(struct.unpack('>I', f.read(4))[0] for d in range(dims))\r\n test_images=np.fromstring(f.read(), dtype=np.uint8).reshape(shape)\r\n\r\n###########labels################\r\ntest_labels_coded=list(test_labels)\r\ntest_labels_coded_n_values = np.max(test_labels_coded) + 1\r\nOneHotEncoded_test_labels_coded=np.eye(test_labels_coded_n_values)[test_labels_coded]\r\n\r\n##########Prepare data set#######################3\r\ntesting_data_processed=[]\r\nfor i in range(0,len( test_images)):\r\n temp=test_images[i].tolist()\r\n merged=[] \r\n for j in temp:\r\n merged=merged+j \r\n testing_data_processed.append(merged)\r\n\r\nlen(FinalWeights)\r\nlen(FinalWeights[0])\r\n\r\nlen(testing_data_processed)\r\nlen(testing_data_processed[0])\r\n\r\nlen(OneHotEncoded_test_labels_coded)\r\n#####################################################\r\nerror=0\r\nfor k in range(0,len(testing_data_processed)):\r\n testingimage=testing_data_processed[k]\r\n ImagePred=[(np.dot(testingimage,FinalWeights[j])) for j in range(0,SizeofOutputVectors)]\r\n maxval=max(ImagePred)\r\n Output=[1.0 if j==maxval and j>0 else 0.0 for j in ImagePred ]\r\n \r\n try:\r\n indexof1inOutput=Output.index(1)\r\n except:\r\n #print(ImagePred)\r\n indexof1inOutput=np.nan\r\n \r\n indexofcorrect=OneHotEncoded_test_labels_coded[k].tolist().index(1)\r\n \r\n if indexofcorrect!=indexof1inOutput:\r\n error=error+1\r\n\r\nprint(\"TestingSet Errors\", error)\r\nprint(\"TestingSet Error Rate\", error/len(testing_data_processed)*100)\r\n#####################questions###############################################\r\n\"\"\"\r\nMissclassifications = [52980, 8753, 7380, 7213, 6979, 6948, 6789, 6792, 6756, 6642, 6681, 6627, 6609, 6528]\r\nEpochs = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\r\nplt.scatter(Epochs, Missclassifications)\r\nplt.title('Epoch vs Misclassifications')\r\nplt.xlabel('Missclassifications')\r\nplt.ylabel('Epochs')\r\nplt.show()\r\n\"\"\"\r\n\r\n","sub_path":"NeuralNet/Code.py","file_name":"Code.py","file_ext":"py","file_size_in_byte":8438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560560292","text":"'''\n semantics.py - semantic analyzer for MLang\n'''\n\nimport libmlang.types as types\nimport pprint\nimport copy\nimport collections\n\ndef keypaths(nested):\n for key, value in nested.items():\n if isinstance(value, collections.Mapping):\n for subkey, subvalue in keypaths(value):\n yield [key] + subkey, subvalue\n else:\n yield [key], value\n'''\nclass SectorScope:\n def __init__(self):\n self.global_scope = {\n \"main\": {\n 0: None\n }\n }\n self.current = \"main\"\n self.current_scope = None\n self.reverse_scope = None\n self._update()\n\n def _update(self):\n print('update', self.current)\n\n\n self.current_scope = self.global_scope[self.current]\n self.reverse_scope = {value: keypath for keypath, value in keypaths(self.global_scope)}\n\n def new_sector(self, name):\n print('new', name)\n pprint.pprint(self.reverse_scope)\n pprint.pprint(self.global_scope)\n self.current_scope[name] = {}\n pprint.pprint(self.global_scope)\n self.current = name\n self._update()\n return name\n\n def close_sector():\n print('close', self.current)\n get_keys(self.global_scope, self.current)\n self.current = result[-1]'''\n\ndef basic_env():\n return {\n \"vars\": {},\n \"sectors\": {\n \"main\": [],\n },\n \"inst\": {}, # instruments\n \"libs\": {},\n \"status\": 0,\n }\n\ndef check_semantics(env, line, elements):\n sscope = []\n\n current_sector = \"main\"\n\n scope = 0\n\n # generate a suitable enviroment for scope checking\n for element in elements:\n if isinstance(element, types.Sector):\n # Sector declaration, register the trajectory\n\n if element.name == ':':\n print(\">%s\" % current_sector)\n continue\n\n if element.name in env['sectors']:\n print(\"line %d: Repeated sector declaration\" % line)\n return False\n\n print(\"<%s\" % element.name)\n current_sector = element.name\n sscope.append(current_sector)\n env['sectors'][current_sector] = []\n\n\n elif isinstance(element, types.PlaySectors):\n for sector in element.sectors:\n print(\"check %s\" % sector)\n if sector not in env['sectors']:\n print(\"line %d: playing an undefined sector\" % line)\n return False\n\n print(\"PlaySectors: %s\" % ', '.join(element.sectors))\n env[\"sectors\"][current_sector].append(element)\n\n else:\n # append to current sector\n print(\"\\t%s => %s\" % (element, current_sector))\n env['sectors'][current_sector].append(element)\n\n return env\n","sub_path":"libmlang/semantics.py","file_name":"semantics.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297343684","text":"from scipy.optimize import fsolve\nimport numpy as np\n\n# Problem 01 Part E\nC_0 = 1000\nR = 8.314\n\nK_1 = 2.31 / C_0\n\nC_A = C_0 / np.exp(K_1 * 10 * 60)\n\nK_2 = 2.31 / (C_A)\n\nT_1 = 27 + 273.15\nT_2 = 40 + 273.15\n\ndef f(variables):\n (A,E_A) = variables\n Eq_1 = K_1 - A * np.exp(-E_A / (R * T_1))\n Eq_2 = K_2 - A * np.exp(-E_A / (R * T_2))\n return [Eq_1,Eq_2]\n\nsolution_1 = fsolve(f, (0.1,1))\nprint('Activation Energy:', solution_1[1], ' J/mol')","sub_path":"PS3_1E.py","file_name":"PS3_1E.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"74854944","text":"import pandas as pd\r\nimport time\r\n\r\nstart_t = time.time()\r\n\r\ndata_top = pd.read_csv(\"sub_top.csv\")\r\n\r\n\r\n\r\nprint(\"\\n [OUT] : Initial Data Shape: \",data_top.shape)\r\n#print(data_top.shape[1])\r\n\r\n#droping columns that are not necessary for processing further\r\ncolumn_to_drop = ['description','inStock', 'codAvailable', 'offers','deliveryTime', 'sizeUnit', 'storage', 'displaySize',\r\n 'specificationList', 'sellerAverageRating','sellerNoOfRatings', 'sellerNoOfReviews', 'idealFor']\r\n\r\ndata_top.drop(column_to_drop,axis=1,inplace=True)\r\n\r\nprint(\"\\n [OUT] : Ater dropping columns Data Shape is :\", data_top.shape)\r\n\r\nprint(\"\\n [OUT] : Before processing(rows) missing values : \\n\", data_top.isnull().sum())\r\n\r\ndrop_row_with_null_columns= ['productId', 'imageUrlStr', 'mrp', 'sellingPrice','specialPrice', 'productUrl', 'categories', 'productBrand',\r\n 'productFamily', 'discount', 'shippingCharges', 'size', 'color','keySpecsStr', 'detailedSpecsStr', 'sellerName', 'sleeve', 'neck']\r\n\r\ndata_top.dropna(axis=0,how='any',subset=drop_row_with_null_columns,inplace=True)\r\n\r\nprint(\"\\n [OUT] : Rows with missing values dropped. \")\r\n\r\ndata_top[data_top.title.isnull()==True] = 'None'\r\n\r\nprint(\"\\n [OUT] : After processing(rows) missing vaules:\\n\",data_top.isnull().sum())\r\n\r\n#sorting with resepect to sellerName,productBrand,mrp\r\n\r\ndata_top.sort_values(by=['sellerName','productBrand','mrp'],inplace=True) \r\n\r\n#writting to csv\r\n\r\ndata_top.to_csv('processed_Dataset.csv',encoding='utf-8',sep=',',index=False)\r\n\r\nend_t = time.time() - start_t\r\n\r\nprint(\"<------- Data Proccessing Done------>\")\r\nprint(\"\\n [OUT] : Final shape: \",data_top.shape)\r\nprint(\"\\n [OUT] : Total time in processing the data {}\".format(str(round(end_t,4))))\r\n","sub_path":"procceessing _data.py","file_name":"procceessing _data.py","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"215217365","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef get_indeed_pages(url):\n result = requests.get(url)\n soup = BeautifulSoup(result.text, \"html.parser\")\n pagination = soup.find(\"div\", {\"class\": \"pagination\"})\n pages = pagination.find_all(\"a\")\n spans = []\n for page in pages[:-1]:\n spans.append(int(page.string))\n max_page = max(spans)\n\n return max_page\n\ndef extract_jobs_indeed(html_indeed):\n SITE_NAME = \"indeed\"\n\n title = html_indeed.find(\"h2\", {\"class\": \"title\"})\n title = title.find(\"a\")[\"title\"]\n company = html_indeed.find(\"span\", {\"class\": \"company\"})\n company_anchor = company.find(\"a\")\n if company_anchor is not None:\n company = str(company_anchor.string)\n else:\n company = str(company.string)\n company = company.strip()\n location = html_indeed.find(\"div\", {\"class\": \"recJobLoc\"})[\"data-rc-loc\"]\n salary = html_indeed.find(\"span\", {\"class\": \"salaryText\"})\n salary = salary.string if salary is not None else \"not opened\"\n job_id = html_indeed[\"data-jk\"]\n\n return {\n \"site\": SITE_NAME,\n \"title\": title,\n \"company\": company,\n \"location\": location,\n \"salary\": salary,\n \"link\": f\"https://www.indeed.com/viewjob?jk={job_id}\"\n }\n\ndef extract_indeed_htmls(last_page, url, LIMIT):\n jobs_indeed = []\n for page in range(last_page):\n print(f\"========== indeed: {page+1}page ==========\")\n\n response = requests.get(f\"{url}&start={page*LIMIT}\")\n soup = BeautifulSoup(response.text, \"html.parser\")\n results = soup.find_all(\"div\", {\"class\": \"jobsearch-SerpJobCard\"})\n\n for result in results:\n jobs_indeed.append(extract_jobs_indeed(result))\n \n return jobs_indeed\n\ndef get_jobs_indeed(keyword, desire_pages = None):\n LIMIT = 50\n url = f\"https://www.indeed.com/jobs?as_and={keyword}&sort=&limit={LIMIT}\"\n\n last_page = get_indeed_pages(url) if desire_pages is None else desire_pages\n jobs = extract_indeed_htmls(last_page, url, LIMIT)\n return jobs","sub_path":"python_files/extractor/indeed.py","file_name":"indeed.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50594843","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\n\n\n# In[3]:\n\n\nurl = 'https://m.search.naver.com/p/csearch/content/qapirender.nhn?'\n\n\n# In[4]:\n\n\ntitle = []\n\nfor i in range(1, 164, 6):\n params = {\n 'where':'nexearch',\n 'key':'onGoingExhibitions',\n 'q' : '서울전시회',\n 'start' : i,\n }\n \n json_string = requests.get(url, params).text\n data_list = json.loads(json_string)\n data_list = data_list['listView']['htmls']\n \n for data in data_list:\n soup = BeautifulSoup(data, 'html.parser')\n temp = soup.select('dd a')[0]\n# print(temp)\n for i in range(len(temp)):\n title.append(temp.text)\n\ntitle = set(title)\n\n\n\n# In[5]:\n\n\nurl = \"https://search.naver.com/search.naver\"\n\n\n# In[6]:\n\n\nexhibition = []\nlocation = []\n\nfor keyword in title:\n params = {\n 'query' : keyword\n }\n \n resp = requests.get(url, params)\n soup = BeautifulSoup(resp.content, 'html.parser')\n content = soup.find('div', class_ = 'contents03_sub')\n if (content != None and content.find('h4', class_ = \"detail_title\") != None):\n dt_list = content.select('dl.item_list dt')\n dd_list = content.select('dl.item_list dd')\n \n temp_title = content.find('h4', class_ = \"detail_title\").find('a').text\n temp_poster = content.find('div', class_ = \"img_box\").find('img')['src']\n \n temp_period = None\n temp_time = None \n temp_location = None\n temp_host = None \n temp_price = None\n\n for i in range(len(dt_list)):\n if dt_list[i].text == '기간':\n temp_period = dd_list[i].text\n if dt_list[i].text == '시간':\n temp_time = dd_list[i].text\n if dt_list[i].text == '장소':\n temp_location = dd_list[i].find('a').text\n if dt_list[i].text == '주최':\n temp_host = dd_list[i].text\n if dt_list[i].text == '요금':\n temp_price = dd_list[i].text\n\n temp = {\n 'title': temp_title,\n 'period': temp_period,\n 'time': temp_time, \n 'loc': temp_location, \n 'host': temp_host,\n 'price': temp_price,\n 'poster': temp_poster\n }\n\n exhibition.append(temp)\n location.append(temp_location)\n\n\n\n# In[7]:\n\n\ncount = 0\n\n# In[8]:\nprint(\"In[8]\")\n\nlocation_set = set(location)\n\n\n# In[9]:\n\n\naddress = []\nurl = 'https://map.naver.com/v5/api/search'\n# https://map.naver.com/v5/search/%EC%84%9C%EC%9A%B8%EC%8B%9C%EB%A6%BD%EB%AF%B8%EC%88%A0%EA%B4%80?c=14133724.2115743,4518044.4291165,14,0,0,0,dh\n\nfor loc in location_set:\n \n params = {\n 'query' : loc\n }\n\n \n json_string = requests.get(url, params).text\n print(json_string)\n data_list = json.loads(json_string, encoding='utf-8')\n \n try:\n temp_addr = data_list['result']['place']['list'][0]['roadAddress']\n \n temp = {\n 'location': loc,\n 'address': temp_addr\n }\n \n address.append(temp)\n \n except TypeError:\n continue\n\n\n# In[10]:\n\nprint(\"In[10]\")\n# In[11]:\n\n\njsonDict_1 = {'data': exhibition}\n\nwith open('./routes/Crawler/exhibition.json', 'w', encoding='utf-8') as f:\n json.dump(jsonDict_1, f, ensure_ascii=False)\n\n\n# In[12]:\n\n\njsonDict_2 = {'data': address}\nwith open('./routes/Crawler/exhibition_address.json', 'w', encoding='utf-8') as f:\n json.dump(jsonDict_2, f, ensure_ascii=False)\n\n\n# In[ ]:\n\nprint(\"last\")\n\n\n","sub_path":"src/routes/Crawler/Naver_Exhibition_crawler.py","file_name":"Naver_Exhibition_crawler.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"19065816","text":"import vk\nimport json\n\nvk_api = vk.API(vk.Session(access_token=\"0152bbbc0152bbbc0152bbbc04013f4323001520152bbbc5c995c1692c36bf31fb38a5d\"))\ngroupid = 189740662\ngroupDomain = \"redfederust\"\n\n\ndef get_members_that_liked_post(postid):\n first = vk_api.likes.getList(type=\"post\", owner_id=-groupid, item_id=postid, filter=\"likes\", offset=0, friends_only=0, count=1000, v=5.92)\n\n data = first[\"items\"]\n count = first[\"count\"] // 1000\n\n for i in range(1, count + 1):\n data = data + vk_api.likes.getList(type=\"post\", owner_id=-groupid, item_id=postid, filter=\"likes\", offset=i*1000, friends_only=0, count=1000, v=5.92)[\"items\"]\n return data\n\n\ndef get_all_posts():\n first = vk_api.wall.get(domain=\"redfederust\", filter=\"owner\", extended=1, offset=0, count=100, v=5.92)\n\n # data = first[\"items\"]\n # count = first[\"count\"] // 100\n #\n # for i in range(1, count + 1):\n # data = data + vk_api.wall.get(owner_id=-groupid, filter=\"owner\", offset=i*1000, friends_only=0, count=100, v=5.92)[\"items\"]\n return first\n\n\n\n\n# print('here is a list of memberships that likes post...')\n# print(get_members_that_liked_post(25))\n\n# print(get_all_posts())","sub_path":"vkRequests.py","file_name":"vkRequests.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"194410192","text":"import src.settings as settings\nimport requests\nimport urllib.parse as url\n\n\ndef exchange_code_for_token(code):\n auth_params = {\n 'client_id': settings.get_auth_client_id(),\n 'client_secret': settings.get_auth_client_secret(),\n 'code': code,\n 'redirect_uri': url.urljoin(settings.get_this_endpoint(), '/callback'),\n 'grant_type': 'authorization_code',\n 'scope': 'openid profile email',\n 'response_type': 'id_token, token'\n }\n\n auth_token_href = f'https://{settings.get_auth_domain()}/oauth/token'\n response = requests.post(auth_token_href,\n data=auth_params, headers={'Content-Type': 'application/x-www-form-urlencoded'})\n\n if response.status_code != 200:\n raise Exception(f'{response.status_code}: {response.text}')\n\n return response.json()","sub_path":"external/src/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350266444","text":"import math\nimport random\nimport time\n\n\ndef valid(num):\n if type(num) == int and num >= 0:\n return True\n else:\n return False\n\n\ndef is_prime(num):\n if not valid(num):\n print(\"Invalid is_prime number: \", num)\n return False\n else:\n limit = math.floor(math.sqrt(num))\n for i in range(2, limit + 1):\n if (num % i == 0):\n return False\n else:\n pass\n\n return True\n\n\nclass Tabulation:\n num_keys = 0\n num_buckets = 0\n num_rehashing = 0\n step_size = 32\n alpha = 1\n table = []\n t0 = []\n t1 = []\n t2 = []\n t3 = []\n\n def __init__(self):\n self.num_keys = 0\n self.num_buckets = 23\n self.num_rehashing = 0\n self.step_size = 32\n self.alpha = 1\n self.t0 = []\n self.t1 = []\n self.t2 = []\n self.t3 = []\n self.table = []\n\n for i in range(self.num_buckets):\n self.table.append([])\n\n for i in range(256):\n self.t0.append(math.floor(random.random() * 0xFFFFFFFF))\n self.t1.append(math.floor(random.random() * 0xFFFFFFFF))\n self.t2.append(math.floor(random.random() * 0xFFFFFFFF))\n self.t3.append(math.floor(random.random() * 0xFFFFFFFF))\n\n def next_prime(self):\n N = self.num_buckets\n while (True):\n N += self.step_size;\n if is_prime(N):\n return N\n\n def re_hashing(self):\n self.num_rehashing += 1\n N = self.next_prime()\n\n new_table = []\n for i in range(0, N):\n new_table.append([])\n\n for i in range(0, len(self.table)):\n if (len(self.table[i]) != 0):\n for k in self.table[i]:\n index = self.hash_value(k) % N\n new_table[index].append(k)\n\n # finally, set table reference to new_table, update num_buckets\n self.table = new_table\n self.num_buckets = N\n\n def collision(self):\n count = 0\n for i in range(0, len(self.table)):\n if (len(self.table[i]) != 0):\n count += 1\n\n return self.num_keys - count\n\n def load_factor(self):\n if (self.num_keys == 0):\n return 0\n if valid(self.num_buckets) and self.num_buckets != 0:\n return (self.num_keys + 1) / self.num_buckets\n else:\n return 0;\n\n def hash_value(self, key):\n k0 = key & 0xFF\n k1 = (key >> 8) & 0xFF\n k2 = (key >> 16) & 0xFF\n k3 = (key >> 24) & 0xFF\n T0 = self.t0[k0]\n T1 = self.t1[k1]\n T2 = self.t2[k2]\n T3 = self.t3[k3]\n res = T0 ^ T1 ^ T2 ^ T3\n return res\n\n def search(self, key):\n if valid(key):\n\n index = self.hash_value(key) % self.num_buckets\n # search the table(index) one by one\n for i in range(len(self.table[index])):\n if key == self.table[index][i]:\n return True, index, i\n\n # out of for loop, not found\n return False, index, len(self.table[index])\n else:\n print(\"Invalid key to search: \", key)\n return False, -1, -1\n\n def put(self, key):\n if valid(key):\n # if adding this key will cause load_factor to be greater than or\n # equal to preset alpha, then first re-hashing, later on put(key)\n if self.load_factor() >= self.alpha:\n self.re_hashing();\n\n found, index, chain_index = self.search(key)\n # if found, nothing happens,\n # if not found, then append key to table[index] and increment num_keys\n # always return the inserted index\n if not found:\n self.table[index].append(key)\n self.num_keys += 1\n else:\n pass\n return index\n\n else:\n print(\"Invalid key to put:\", key)\n return -1\n\n def delete(self, key):\n if valid(key):\n found, index, chain_index = self.search(key)\n\n # if found, set table[index] to be an empty list, decrement num_keys and return index\n # if not found, return -1\n if not found:\n return -1\n else:\n del self.table[index][chain_index]\n self.num_keys -= 1\n else:\n print(\"Invalid key to delete:\", key)\n return -1\n\nprint(\"\\n\\nChange number of keys inserted\")\nnums = [100, 500, 1000, 5000, 20000]\ntests = []\nfor i, num in enumerate(nums):\n tests.append([])\n for j in range(num):\n tests[i].append(math.floor(random.uniform(0, 0x7FFFFFFF)))\n\nfor j, test in enumerate(tests):\n print(\"Number of keys inserted(containing duplicate): \", nums[j])\n\n\n\n t0 = time.process_time()\n tab = Tabulation()\n for i in test:\n tab.put(i)\n print(\"Tabulation Hashing:\")\n print(\"Running time:\", time.process_time() - t0)\n print(\"# of buckets:\", tab.num_buckets, \"# of keys:\", tab.num_keys, \"load factor:\", tab.load_factor(),\n \"# of re-hashing:\", tab.num_rehashing, \"collisions:\", tab.collision())\n\n\nprint(\"\\n\\nChange α\")\ntest = []\nalphas = [0.3, 0.5, 0.6, 0.8, 1]\nfor i in range(10000):\n test.append(math.floor(random.random() * 0x7FFFFFFF))\n\nfor j, alpha in enumerate(alphas):\n print(\"alpha: \", alphas[j])\n\n t0 = time.process_time()\n tab = Tabulation()\n tab.alpha = alpha\n for i in test:\n tab.put(i)\n print(\"Tabulation Hashing:\")\n print(\"Running time:\", time.process_time() - t0)\n print(\"# of buckets:\", tab.num_buckets, \"# of keys:\", tab.num_keys, \"load factor:\", tab.load_factor(),\n \"# of re-hashing:\", tab.num_rehashing, \"collisions:\", tab.collision())\n\nprint(\"\\n\\nSearch Query:\")\n\nnums = [100, 500, 1000, 5000, 20000]\ntest = []\nfor i in range(20000):\n test.append(math.floor(random.uniform(0, 0x7FFFFFFF)))\n\n\ntab = Tabulation()\n\n\nfor i in test:\n\n tab.put(i)\n\n\nfor j, num in enumerate(nums):\n print(\"# of searching keys:\", num)\n\n\n\n\n print(\"Tabulation Hashing:\")\n t0 = time.process_time()\n for i in range(num):\n tab.search(test[i])\n print(\"Running time:\", time.process_time() - t0)\n","sub_path":"tabulation.py","file_name":"tabulation.py","file_ext":"py","file_size_in_byte":6254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"478572921","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n#-----------------------------------------------------------------------------\n# Purpose: menu with checkbox and radiobutton.\n#-----------------------------------------------------------------------------\n\nimport wx\n\nclass Frame(wx.Frame):\n\n def __init__(self):\n super(self.__class__, self).__init__(parent=None, id=-1, title='Menu with Check and Radio')\n panel = wx.Panel(self)\n\n m1 = wx.Menu()\n exit = m1.Append(id=-1, text='E&xit', help='', kind=wx.ITEM_NORMAL)\n self.Bind(event=wx.EVT_MENU, handler=self.OnExit, source=exit)\n\n m2 = wx.Menu()\n # m2.AppendCheckItem(id=-1, text='Check Item 1', help='')\n # m2.AppendCheckItem(id=-1, text='Check Item 2', help='')\n # m2.AppendCheckItem(id=-1, text='Check Item 3', help='')\n # m2.AppendSeparator()\n # m2.AppendRadioItem(id=-1, text='Radio Item 1', help='')\n # m2.AppendRadioItem(id=-1, text='Radio Item 2', help='')\n # m2.AppendRadioItem(id=-1, text='Radio Item 3', help='')\n m2.Append(id=-1, text='Check Item 1', help='', kind=wx.ITEM_CHECK)\n m2.Append(id=-1, text='Check Item 2', help='', kind=wx.ITEM_CHECK)\n m2.Append(id=-1, text='Check Item 3', help='', kind=wx.ITEM_CHECK)\n m2.Append(id=wx.ID_SEPARATOR, text='', help='', kind=wx.ITEM_SEPARATOR)\n m2.Append(id=-1, text='Radio Item 1', help='', kind=wx.ITEM_RADIO)\n m2.Append(id=-1, text='Radio Item 2', help='', kind=wx.ITEM_RADIO)\n m2.Append(id=-1, text='Radio Item 3', help='', kind=wx.ITEM_RADIO)\n\n mb = wx.MenuBar()\n mb.Append(menu=m1, title='Menu')\n mb.Append(menu=m2, title='Toggle Items')\n self.SetMenuBar(mb)\n\n # layout\n self.CenterOnScreen()\n\n def OnExit(self, event):\n self.Close()\n\nclass App(wx.App):\n\n def OnInit(self):\n frame = Frame()\n self.SetTopWindow(frame)\n frame.Show()\n return True\n\nif __name__ == '__main__':\n\n app = App()\n app.MainLoop()\n\n\n\n\n","sub_path":"use_menu_with_checkbox_and_radiobutton_78.py","file_name":"use_menu_with_checkbox_and_radiobutton_78.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"40399210","text":"from openerp import models, api, fields\n\n\nclass StockPicking(models.Model):\n _inherit = 'stock.picking'\n\n product_id_not_moved = fields.Many2many(\n 'product.product', string='Product Not Moved',\n compute='_compute_products_not_moved', related=False, store=True)\n\n @api.one\n @api.depends('move_line_ids.qty_done')\n def _compute_products_not_moved(self):\n res = self.env['product.product']\n for operation in self.move_line_ids:\n if operation.qty_done < operation.product_qty:\n res += operation.product_id\n self.product_id_not_moved = res\n","sub_path":"merp_picking_wave_products_skip-11.0.1.0.0/merp_picking_advanced_search/models/stock_picking.py","file_name":"stock_picking.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"346600464","text":"class Solution(object):\n def subsets(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n # start reading and coding at 9:23\n def dfs(i, path, ans):\n ans += [path];\n \n for k in range(i, len(nums)):\n dfs(k+1, path + [nums[k]], ans);\n \n nums.sort(); # why need this?\n path = [];\n ans = [];\n dfs(0, path, ans);\n return ans;\n # submit first answer at 9:28 and failed\n # pass at 9:32","sub_path":"1-100/71-80/python/78_subsets.py","file_name":"78_subsets.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"615416009","text":"import time\n\nfrom BackEnd.database.common.Base_db import Base_db\nfrom BackEnd.database.common.Stores_db import Stores_DB\n\nclass Manager:\n\n status_db = status_lt = False # lt = load_tables\n tables = []\n\n def __init__(self):\n self.db = self.open_database()\n self.load_tables()\n\n def open_database(self):\n try:\n data_base = Base_db()\n except:\n raise Exception(\"cant open the database\")\n self.status_db = True\n return data_base\n\n def load_tables(self):\n\n if self.status_db is False:\n self.open_database()\n\n if self.status_db is False:\n raise Exception(\"the data base is down!\")\n\n try:\n stores = Stores_DB(self.db)\n # products = Products_db(self.db) to be implemented\n\n self.tables.append(stores)\n except:\n return False\n return True\n\n def get_status(self):\n msg = \"Status: lt = {}, db = {}\".format(self.status_lt, self.status_db)\n print(msg)\n\n def delete_table(self, i):\n del self.tables[i]\n","sub_path":"BackEnd/database/Manager_db.py","file_name":"Manager_db.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"249549124","text":"#实现GET方法,通过GET方法返回页面的数据\nimport json\nfrom urllib import parse\nimport os\nfrom handler.base_http_handler import BaseHTTPRequestHandler\n\n\nRESOURCES_PATH = os.path.join(os.path.abspath(os.path.dirname(__name__)),\n '../resources')\n\nclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler):\n\n def __init__(self,server,request,client_address):\n BaseHTTPRequestHandler.__init__(self,server,request,client_address)\n\n def do_GET(self):\n found,resource_path = self.get_resources(self.path)\n if not found:\n self.write_error(404)\n self.send()\n else:\n with open(resource_path,'rb') as f:\n fs = os.fstat(f.fileno())\n #文件长度\n clength = str(fs[6])\n self.write_response(200)\n self.write_header('Content-Length',clength)\n #避免跨域问题\n self.write_header('Access-Control-Allow-Origin', 'http://%s:%d' %\n (self.server.server_address[0], self.server.server_address[1]))\n self.end_headers()\n while True:\n buf = f.read(1024)\n if not buf:\n break\n self.write_content(buf)\n\n\n #判断并获取资源\n def get_resources(self,path):\n url_result = parse.urlparse(path)\n resource_path = str(url_result[2])\n if resource_path.startswith('/'):\n resource_path = resource_path[1:]\n resource_path = os.path.join(RESOURCES_PATH,resource_path)\n if os.path.exists(resource_path) and os.path.isfile(resource_path): #此时我们就认为这个资源是存在的\n return True,resource_path\n else:\n return False,resource_path\n\n\n def do_POST(self):\n #从请求中取出数据\n body = json.loads(self.body)\n print(body)\n username = body['username']\n password = body['password']\n #账号密码校验\n if username == 'hxx' and password == '123456':\n response = {'message':'success','code':0}\n else:\n response = {'message':'failed','code':-1}\n\n response = json.dumps(response)\n #组成应答报文\n self.write_response(200)\n self.write_header('Content-Length',len(response))\n # 避免跨域问题\n self.write_header('Access-Control-Allow-Origin','http://%s:%d'%\n (self.server.server_address[0],self.server.server_address[1]))\n self.end_headers()\n self.write_content(response)\n\n","sub_path":"HttpServer/handler/simple_http_handler.py","file_name":"simple_http_handler.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"435969986","text":"#!/usr/bin/env python3\nfrom time import sleep\nimport ev3dev.ev3 as ev3\nimport RoutingClass as Route\nimport ArmClass as Arm\nimport MovementClass as Movement\nimport bluetooth\nimport ast\n\nhostMACAddress = '00:17:E9:F8:72:06' # The MAC address of a Bluetooth adapter on the server. The server might have multiple Bluetooth adapters.\nport = 3\nbacklog = 1\nsize = 1024\ns = bluetooth.BluetoothSocket(bluetooth.RFCOMM)\ns.bind((hostMACAddress, port))\ns.listen(backlog)\n\nclass Robot():\n def __init__(self, currentPos, path, action, gs, cs, mc, ac, rc):\n #set wheel motor for MovementController\n self.currentPos = currentPos\n self.path = path\n self.action = action\n self.cs = cs\n self.gs = gs\n self.mc = mc\n self.ac = ac\n self.rc = rc\n\n def lineFollowing(self):\n self.mc.setNormal()\n stop = False\n while not stop:\n if (self.cs.value() == 6):\n self.mc.turnLeft()\n elif (self.cs.value() == 1):\n self.mc.turnRight()\n self.mc.setSpeed(300)\n if (self.cs.value() == 5):\n self.mc.stop()\n self.processAction()\n if (len(self.path) == 0 and len(self.action) == 0):\n stop = True\n\n if (self.cs.value() == 3):\n self.mc.setSpeed(300)\n self.processRoute()\n\n\n def processRoute(self):\n print(self.path)\n if self.path[0] == \"left\":\n self.turnLeft(78)\n elif self.path[0] == \"right\":\n self.turnRight(87)\n else:\n self.forward()\n sleep(0.7)\n self.path.pop(0)\n\n def processAction(self):\n if (len(self.action) > 0):\n print(self.action[0])\n if self.action[0] == \"Pick Up\":\n self.ac.pickUp()\n elif self.action[0] == \"Put Down\":\n self.ac.putDown()\n self.mc.setInverse()\n self.forward()\n self.mc.setNormal()\n self.action.pop(0)\n\n self.turnAround(180)\n\n def turnAround(self, degree):\n self.mc.setRightInverse()\n self.mc.setLeftSpeed(200)\n self.mc.setRightSpeed(200)\n self.gs.mode = \"GYRO-RATE\"\n self.gs.mode = \"GYRO-ANG\"\n tmp = self.gs.value()\n while(abs(self.gs.value() - tmp) <= degree):\n # print(\"tmp: \",tmp)\n # print(\"value: \",self.gs.value())\n # print(abs(self.gs.value() - tmp))\n pass\n self.mc.setNormal()\n self.mc.stop()\n\n def forward(self):\n # sleep(0.4)\n self.mc.forward()\n sleep(0.5)\n\n def turnRight(self, degree):\n sleep(0.13)\n tmp = self.gs.value()\n while(abs(self.gs.value() - tmp) <= degree):\n self.mc.setLeftSpeed(200)\n self.mc.setRightSpeed(0)\n\n def turnLeft(self, degree):\n sleep(0.15)\n tmp = self.gs.value()\n self.mc.setLeftInverse()\n while(abs(self.gs.value() - tmp) <= degree):\n # mc.turnLeft()\n self.mc.setLeftSpeed(0)\n self.mc.setRightSpeed(200)\n self.mc.setNormal()\n\n def addRoute(self, start, end):\n if start == \"\":\n start = self.currentPos\n self.path += self.rc.findPath(start, end)\n self.currentPos = end\n def getRoute(self):\n return self.path\n\n def addAction(self, action):\n self.action += action\n\n def receiveCommand(self, commands):\n for command in commands:\n for location, action in command.items():\n if (location == self.currentPos):\n self.reset()\n return False\n self.addRoute('', location)\n self.addAction([action])\n return True\n\n def reset(self):\n self.path = []\n self.action = []\n\n def reload(self):\n self.reset()\n self.currentPos = \"Start\"\n\n def stop(self):\n self.mc.stop()\n\n def start(self):\n self.lineFollowing()\n\nif __name__ == \"__main__\":\n\n done = False\n rm = ev3.LargeMotor('outC')\n lm = ev3.LargeMotor('outB')\n lf = ev3.MediumMotor('outA')\n gs = ev3.GyroSensor()\n cs = ev3.ColorSensor()\n\n mc = Movement.MovementController(lm, rm)\n ac = Arm.ArmController(lf)\n rc = Route.RoutingController('', '')\n\n # action = [\"pickup\", \"putdown\", \"pickup\", \"putdown\"]\n assert cs.connected\n assert gs.connected\n cs.mode = \"COL-COLOR\"\n gs.mode = \"GYRO-ANG\"\n\n robot = Robot(\"Start\", [], [], gs, cs, mc, ac, rc)\n\n while not done:\n try:\n print(\"Waiting for Ev3-App connection\")\n client, clientInfo = s.accept()\n print(\"Ev3-App Conntected\\nWaiting for command\")\n while 1:\n data = client.recv(size)\n if data:\n commands = ast.literal_eval(data.decode(\"ascii\"))\n #format of data: a:b\n robot.reset()\n print(commands)\n if (robot.receiveCommand(commands)):\n robot.start()\n print(\"Job Done!\")\n client.send(\"done\") # Echo back to client\n else:\n client.send(\"refuse\")\n\n except KeyboardInterrupt:\n robot.stop()\n print(\"\\nShut down the robot\\n\")\n done = True\n client.close()\n s.close()\n\n except bluetooth.btcommon.BluetoothError:\n robot.stop()\n print(\"Connection lost! Closing Ev3-App socket!\")\n robot.reset()\n client.close()\n\n except:\n robot.stop()\n print(\"Something wrong happens! Please reset the robot to starting point\")\n robot.reload()\n client.close()\n\n # try:\n # robot.addRoute('','d')\n # robot.addRoute('', 'a')\n # robot.addRoute('', 'c')\n # robot.addRoute('', 'b')\n # robot.addRoute('', 'start')\n # print (robot.getRoute())\n # robot.lineFollowing()\n # mc.stop()\n # # ac.pickUp()\n # # mc.stop()\n # except KeyboardInterrupt:\n # mc.stop()\n # except:\n # mc.stop()\n\n #red: 5\n #black: 1\n #white: 6\n #blue: 2\n #green: 3\n","sub_path":"Robot.py","file_name":"Robot.py","file_ext":"py","file_size_in_byte":6354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422558514","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n#from __future__ import unicode_literals\n\nimport os.path\nfrom unittest import SkipTest\n\nimport numpy as np\nfrom numpy.testing import assert_allclose, assert_equal\nimport pytest\n\nfrom freediscovery.text import FeatureVectorizer\nfrom .run_suite import check_cache\n\n\n# adapted from https://github.com/seomoz/simhash-py/blob/master/test/test.py\njabberwocky = '''\n Twas brillig, and the slithy toves\n Did gyre and gimble in the wabe:\n All mimsy were the borogoves,\n And the mome raths outgrabe.\n \"Beware the Jabberwock, my son!\n The jaws that bite, the claws that catch!\n Beware the Jubjub bird, and shun\n The frumious Bandersnatch!\"\n He took his vorpal sword in hand:\n Long time the manxome foe he sought --\n So rested he by the Tumtum tree,\n And stood awhile in thought.\n And, as in uffish thought he stood,\n The Jabberwock, with eyes of flame,\n Came whiffling through the tulgey wood,\n And burbled as it came!\n One, two! One, two! And through and through\n The vorpal blade went snicker-snack!\n He left it dead, and with its head\n He went galumphing back.\n \"And, has thou slain the Jabberwock?\n Come to my arms, my beamish boy!\n O frabjous day! Callooh! Callay!'\n He chortled in his joy.\n `Twas brillig, and the slithy toves\n Did gyre and gimble in the wabe;\n All mimsy were the borogoves,\n And the mome raths outgrabe.'''\njabberwocky_author = ' - Lewis Carroll (Alice in Wonderland)'\n\ndef fd_setup():\n basename = os.path.dirname(__file__)\n\n cache_dir = check_cache()\n\n data_dir = os.path.join(basename, \"..\", \"data\", \"ds_001\", \"raw\")\n\n n_features = 110000\n\n fe = FeatureVectorizer(cache_dir=cache_dir)\n uuid = fe.preprocess(data_dir, file_pattern='.*\\d.txt',\n n_features=n_features, use_hashing=True,\n stop_words='english')\n uuid, filenames = fe.transform()\n return cache_dir, uuid, filenames, fe\n\n\ndef test_simhash():\n\n try:\n from simhash import num_differing_bits\n except ImportError:\n raise SkipTest\n from sklearn.feature_extraction.text import HashingVectorizer\n from freediscovery.simhash import SimhashDuplicates\n\n DISTANCE = 4\n\n fe = HashingVectorizer(ngram_range=(4,4), analyzer='word', n_features=2**30)\n\n X = fe.fit_transform([jabberwocky,\n jabberwocky + jabberwocky_author,\n jabberwocky_author,\n jabberwocky])\n\n sh = SimhashDuplicates()\n sh.fit(X)\n\n # make sure small changes in the text results in a small number of different bytes\n assert num_differing_bits(*sh._fit_shash[:2]) <= 2\n # different text produces a large number of different bytes\n assert num_differing_bits(*sh._fit_shash[1:3]) >= 30\n\n # same text produces a zero bit difference\n assert num_differing_bits(*sh._fit_shash[[0,-1]]) == 0\n\n simhash, cluster_id, dup_pairs = sh.query(distance=DISTANCE, blocks=42)\n\n assert simhash[0] == simhash[-1] # duplicate documents have the same simhash\n assert cluster_id[0] == cluster_id[-1] # and belong to the same cluster\n\n for idx, shash in enumerate(simhash):\n if (shash == simhash).sum() == 1: # ignore duplicates\n assert sh.get_index_by_hash(shash) == idx\n\n for pairs in dup_pairs:\n assert num_differing_bits(*pairs) <= DISTANCE\n\n\ndef test_dup_detection():\n try:\n import simhash\n except ImportError:\n raise SkipTest\n from freediscovery.simhash import DuplicateDetection\n cache_dir, uuid, filenames, fe = fd_setup()\n\n dd = DuplicateDetection(cache_dir=cache_dir, dsid=uuid)\n dd.fit()\n simhash, cluster_id, dup_pairs = dd.query(distance=3)\n","sub_path":"freediscovery/tests/test_dupdetection.py","file_name":"test_dupdetection.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"494310088","text":"# Coloque aqui as transições do seu autômato\nedges = { \n (0, '0') : 1,\n (0, '1') : 5,\n (1, '0') : 6,\n (1, '1') : 2,\n (2, '0') : 3,\n (2, '1') : 6,\n (3, '0') : 4,\n (3, '1') : 6,\n (4, '0') : 6,\n (4, '1') : 6,\n (5, '0') : 1,\n (5, '1') : 6,\n (6, '0') : 6,\n (6, '1') : 6,\n\n\n\n\n}\n\n#Coloque aqui os estados finais do seu autômato\naccepting = [0,1,3,5,6]\n\ninitial = 0\n\n# Função que roda o autômato\ndef dfa(string, current, edges, accepting):\n if string == \"\":\n return current in accepting \n else:\n letter = string[0]\n remainder = string[1:]\n if (current, letter) in edges:\n newstate = edges[(current, letter)]\n return dfa(remainder, newstate, edges, accepting)\n return False\n\nstring = \"01\" \nprint(\">>>>>>>>\")\nprint(string) \nprint(\"========\")\nprint(dfa(string, initial, edges, accepting)) \nprint(\"<<<<<<<<\")\n\nstring = \"0100\" \nprint(\">>>>>>>>\")\nprint(string) \nprint(\"========\")\nprint(dfa(string, initial, edges, accepting)) \nprint(\"<<<<<<<<\")\n\n\nfor i in range(5,30):\n string = \"{0:b}\".format(i) \n print(\">>>>>>>>\")\n print(string) \n print(\"========\")\n print(dfa(string, initial, edges, accepting)) \n print(\"<<<<<<<<\")\n\n\n#string = input()\n#print(dfa(string, initial, edges, accepting))\n","sub_path":"15/solver3.py","file_name":"solver3.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"648805137","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\nmonths_list = ['january', 'february', 'march', 'april', 'may', 'june', 'all']\n\nweekdays_list = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'all']\n\nchoice = ['month','day','both']\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n # Get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n\n cities = CITY_DATA.keys()\n\n while True:\n city = input(\"\\n Which city are you interested in to look at? new york city, chicago or washington?\\n\").lower()\n if city not in cities:\n print(\"Please enter the valid city name!\")\n continue\n else:\n break\n\n\n # Get user input for month, day or both\n\n while True:\n filter_by = input(\"Do you want to filter by month, day or both?Please enter month or day or both.\\n\")\n if filter_by not in choice:\n print('please enter valid choice')\n continue\n else:\n break\n\n while True:\n # when user preference is month\n if filter_by == choice[0]:\n day = 'all'\n month = input('Which month are you interested in to look at? january, february, march, april, may, june or all?\\n').lower()\n if month not in months_list:\n print('Oops!Something is wrong.Please enter the correct month')\n continue\n else:\n break\n # when user preference is day\n elif filter_by == choice[1]:\n month = 'all'\n day = input('If you are looking for a particular day please type the day as follows: sunday, monday, tuesday, wednesday, thursday, friday, saturday or all.\\n').lower()\n if day not in weekdays_list:\n print('Oops!Something is wrong.Please enter the correct weekday')\n continue\n else:\n break\n # when user prefence is both\n\n elif filter_by == choice[2]:\n while True:\n month = input('Which month are you interested in to look at? january, february, march, april, may, june or all?\\n').lower()\n if month not in months_list:\n print('Oops!Something is wrong.Please enter the correct month')\n continue\n else:\n break\n while True:\n day = input('If you are looking for a particular day please type the day as follows: sunday, monday, tuesday, wednesday, thursday, friday, saturday or all .\\n').lower()\n if day not in weekdays_list:\n print('Oops!Something is wrong.Please enter the correct weekday')\n continue\n else:\n break\n break\n\n print('-'*50)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n # Load data file into a dataframe\n df = pd.read_csv(CITY_DATA[city])\n\n # Convert the Start Time column to datetime\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n # Extract month and day of week from Start Time to create new columns\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n # Filter by month if applicable\n if month != 'all':\n # use the index of the months list to get the corresponding int\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n\n # filter by month to create the new dataframe\n df = df[df['month'] == month]\n\n # Filter by day of week if applicable\n if day != 'all':\n # filter by day of week to create the new dataframe\n df = df[df['day_of_week'] == day.title()]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Shows statistics on the most frequent times of travel by bike users.\"\"\"\n\n print('\\nCalculating the first statistics...\\n')\n start_time = time.time()\n\n # Display the most common month\n most_common_month= df['month'].mode()[0]\n print('The Most Common Month is: {}'.format(most_common_month))\n\n\n # Display the most common day of week\n most_common_weekday = df['day_of_week'].mode()[0]\n print('The Most Common Day is: {}'.format(most_common_weekday))\n\n\n # Display the most common start hour\n df['hour'] = df['Start Time'].dt.hour\n most_common_hour = df['hour'].mode()[0]\n print('The Most Common Hour is : {}'.format(most_common_hour))\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*50)\n\n\ndef station_stats(df):\n \"\"\"Shows statistics on the most popular stations and trip by bike users.\"\"\"\n\n print('\\nCalculating the next statistics...\\n')\n start_time = time.time()\n\n # Display most commonly used start station\n most_popular_start_stations = df['Start Station'].mode()[0]\n print('The most used start station is: {}'.format(most_popular_start_stations))\n\n\n # Display most commonly used end station\n most_popular_end_stations = df['End Station'].mode()[0]\n print('The most used end station is: {}'.format(most_popular_end_stations))\n\n\n # Display most frequent combination of start station and end station trip\n df['routes'] = df['Start Station'].str.cat(df['End Station'], sep = \" to \")\n popular_route = df['routes'].mode()[0]\n print('The most frequent combination of start and end station trip: {}'.format(popular_route))\n\n\n print('\\nThis took %s seconds.' % (time.time() - start_time))\n print('-'*50)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating the next statistics...\\n')\n start_time = time.time()\n\n # Display total travel time\n Total_Travel_Time = sum(df['Trip Duration'])/86400\n print('Total travel time:', Total_Travel_Time, \" Days\")\n\n\n # Display mean travel time\n\n Mean_Travel_Time = df['Trip Duration'].mean()/60\n print('Mean travel time:', Mean_Travel_Time, \" Minutes\")\n\n\n\n print('\\nThis took %s seconds.' % (time.time() - start_time))\n print('-'*50)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating the next statistics...\\n')\n start_time = time.time()\n\n # Display counts of user types\n counts_user_types = df['User Type'].value_counts()\n print('Here are the counts of various user types:',counts_user_types)\n\n\n # Display counts of gender\n #Gender data is not available for Washington city,so we may need to be careful\n try:\n gender_types = df['Gender'].value_counts()\n print('\\nGender Types:\\n', gender_types)\n except KeyError:\n print('\\nGender Types:\\nData is missing for this month.')\n\n # Display earliest, most recent, and most common year of birth\n\n try:\n Earliest_Year = int(df['Birth Year'].min())\n print('Earliest Year:', Earliest_Year)\n except KeyError:\n print('Earliest Year:\\nData is missing for this month.')\n\n try:\n Most_Recent_Year = int(df['Birth Year'].max())\n print('Most Recent Year:', Most_Recent_Year)\n except KeyError:\n print('Most Recent Year:\\nData is missing for this month.')\n\n try:\n Most_Common_Year = int(df['Birth Year'].value_counts().idxmax())\n print('Most Common Year:', Most_Common_Year)\n except KeyError:\n print('Most Common Year:\\nData is missing for this month.')\n\n\n print('\\nThis took %s seconds.' % (time.time() - start_time))\n print('-'*50)\n\ndef display_data(df):\n \"\"\"\n Display contents of the CSV file to the display as requested by\n the user.\n \"\"\"\n # Dispalying five random rows of the raw data\n\n interested_in_display = input('Do you want to see five lines of the raw data?Enter yes or no.\\n').lower()\n\n while interested_in_display == 'yes':\n print('\\nRaw Data Display:\\n', df[df.columns[0:-4]].sample(5))\n terminate_display = input('\\nDo you wish to continue?Enter yes or no.\\n').lower()\n if terminate_display == 'no':\n break\n else:\n print(\"\\nLet's print more raw data\\n\")\n\ndef main():\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n display_data(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare_2.py","file_name":"bikeshare_2.py","file_ext":"py","file_size_in_byte":9408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"112304549","text":"\"\"\"\nGiven a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.\n\nThe brackets must close in the correct order, \"()\" and \"()[]{}\" are all valid but \"(]\" and \"([)]\" are not.\n\n\"\"\"\n\n\n\nclass Solution(object):\n def isValid(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n my_stack = []\n my_dict = {']':'[','}':'{',')':'('}\n\n for ch in s :\n if ch in ['[','{','('] : #入栈\n my_stack.append(ch)\n elif ch in [']','}',')'] : #出栈判断\n if len(my_stack) == 0:\n return False\n elif my_stack.pop() != my_dict[ch] :\n return False\n else : \n pass\n\n if len(my_stack) == 0 : \n return True\n else : \n return False\n\n\n\nif __name__ == '__main__':\n S =Solution()\n ss = S.isValid(\"{{\")\n print(ss)\n\n\n\n\n\n\n\n\n\n\n\"\"\"\nQ : \n 括号匹配, 使用栈\n \n python 栈 使用list 模拟, append 和 pop 入栈出栈。\n\"\"\"","sub_path":"20_Valid Parentheses.py","file_name":"20_Valid Parentheses.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"58434556","text":"import json\nimport requests\nimport time\nfrom .base import BaseWechatAPI\nfrom .ierror import GetAccessTokenError\nfrom .msg import MSG\nimport wework.rq as rq\n\n\n__all__ = ['WorkWechatCorpAPI']\n\n\nclass WorkWechatCorpAPI(BaseWechatAPI):\n \"\"\"企业自建应用的api\"\"\"\n def __init__(self, corp_id, secret, agent_id):\n \"\"\"\n :param corp_id: 企业id \n :param secret: 企业自建应用的secret\n \"\"\"\n self.corp_id = corp_id\n self.secret = secret\n self.agent_id = agent_id\n self._global_access_token = {}\n\n @classmethod\n def new(cls, access_token, agent_id):\n obj = cls('__', '__', agent_id)\n\n def _get_access_token():\n nonlocal access_token\n t = int(time.time()) + 7200\n return access_token, t\n obj._get_access_token = _get_access_token\n return obj\n\n @property\n def msg(self):\n return MSG(self.access_token, self.agent_id)\n\n def _get_access_token(self):\n url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={}&corpsecret={}'.format(self.corp_id, self.secret)\n data = requests.get(url).json()\n if 'access_token' not in data:\n raise GetAccessTokenError(data)\n return data['access_token'], data['expires_in']\n\n @property\n def access_token(self):\n g = self._global_access_token\n if 'access_token' not in g or time.time() >= g['expires_time']:\n access_token, expires_in = self._get_access_token()\n g['access_token'] = access_token\n g['expires_time'] = expires_in + int(time.time())\n return self._global_access_token['access_token']\n\n def get_department_list(self, id=None):\n \"\"\"\n https://work.weixin.qq.com/api/doc#90000/90135/90208\n 获取部门列表\n :param id: 部门id。获取指定部门及其下的子部门。 如果不填,默认获取全量组织架构\n :return: \n [{\n \"id\": 2, # 创建的部门id\n \"name\": \"广州研发中心\", # 部门名称\n \"parentid\": 1, # 父亲部门id。根部门为1\n \"order\": 10, # 在父部门中的次序值。order值大的排序靠前。值范围是[0, 2^32)\n }],\n \"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={}'.format(self.access_token)\n if id is not None:\n url += '&id={}'.format(id)\n return rq.get(url)['department']\n\n def get_department_user_list(self, department_id, fetch_child=False):\n \"\"\"\n https://work.weixin.qq.com/api/doc#90000/90135/90200\n 获取部门成员\n :param department_id: 获取的部门id\n :param fetch_child: 1/0:是否递归获取子部门下面的成员\n :return: \n [\n {\n \"userid\": \"zhangsan\",\n \"name\": \"李四\",\n \"department\": [1, 2], # 成员所属部门列表。列表项为部门ID,32位整型\n }\n ]\n \"\"\"\n fetch_child = 1 if fetch_child else 0\n url = 'https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?' \\\n 'access_token={}&department_id={}&fetch_child={}'.format(self.access_token, department_id, fetch_child)\n return rq.get(url)['userlist']\n\n def get_department_user_detail_list(self, department_id, fetch_child=False):\n \"\"\"\n https://work.weixin.qq.com/api/doc#90000/90135/90201\n 获取所有部门成员的详情信息\n :param department_id: 获取的部门id\n :param fetch_child: 1/0:是否递归获取子部门下面的成员\n :return: \n [{\n \"userid\": \"zhangsan\", # 成员UserID。对应管理端的帐号\n \"name\": \"李四\", # 成员名称\n \"department\": [1, 2], # 成员所属部门id列表,仅返回该应用有查看权限的部门id\n \"order\": [1, 2], # 部门内的排序值,32位整数,默认为0。数量必须和department一致,数值越大排序越前面。\n \"position\": \"后台工程师\", # 职务信息;第三方仅通讯录应用可获取\n \"mobile\": \"15913215421\", # 手机号码,第三方仅通讯录应用可获取\n \"gender\": \"1\", # 性别。0表示未定义,1表示男性,2表示女性\n \"email\": \"zhangsan@gzdev.com\", # 邮箱,第三方仅通讯录应用可获取\n \"is_leader_in_dept\": [1, 0], # 表示在所在的部门内是否为上级;第三方仅通讯录应用可获取\n \"avatar\": \"url\", # 头像url。注:如果要获取小图将url最后的”/0”改成”/100”即可。第三方仅通讯录应用可获取\n \"telephone\": \"020-123456\", # 座机。第三方仅通讯录应用可获取\n \"enable\": 1, # 成员启用状态。1表示启用的成员,0表示被禁用。服务商调用接口不会返回此字段\n \"alias\": \"jackzhang\", # 别名;第三方仅通讯录应用可获取\n \"status\": 1, # 激活状态: 1=已激活,2=已禁用,4=未激活 \n 已激活代表已激活企业微信或已关注微工作台(原企业号)。未激活代表既未激活企业微信又未关注微工作台(原企业号)。\n \"extattr\": { # 扩展属性,第三方仅通讯录应用可获取\n \"attrs\": [\n {\n \"type\": 0,\n \"name\": \"文本名称\",\n \"text\": {\n \"value\": \"文本\"\n }\n },\n {\n \"type\": 1,\n \"name\": \"网页名称\",\n \"web\": {\n \"url\": \"http://www.test.com\",\n \"title\": \"标题\"\n }\n }\n ]\n },\n \"qr_code\": \"https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=xxx\", # 员工个人二维码,扫描可添加为外部联系人;第三方仅通讯录应用可获取\n \"external_position\": \"产品经理\", # 对外职务。 第三方仅通讯录应用可获取\n \"external_profile\": { # 成员对外属性,字段详情见对外属性;第三方仅通讯录应用可获取\n \"external_corp_name\": \"企业简称\",\n \"external_attr\": [{\n \"type\": 0,\n \"name\": \"文本名称\",\n \"text\": {\n \"value\": \"文本\"\n }\n },\n {\n \"type\": 1,\n \"name\": \"网页名称\",\n \"web\": {\n \"url\": \"http://www.test.com\",\n \"title\": \"标题\"\n }\n },\n {\n \"type\": 2,\n \"name\": \"测试app\",\n \"miniprogram\": {\n \"appid\": \"wx8bd80126147df384\",\n \"pagepath\": \"/index\",\n \"title\": \"miniprogram\"\n }\n }\n ]\n }\n }]\n \"\"\"\n fetch_child = 1 if fetch_child else 0\n url = 'https://qyapi.weixin.qq.com/cgi-bin/user/list?' \\\n 'access_token={}&department_id={}&fetch_child={}'.format(self.access_token, department_id, fetch_child)\n return rq.get(url)['userlist']\n\n def get_user_detail(self, user_id):\n \"\"\"\n https://work.weixin.qq.com/api/doc#90000/90135/90196\n 获取成员详细信息\n :param user_id: 成员UserID。对应管理端的帐号,企业内必须唯一。不区分大小写,长度为1~64个字节\n :return: dict\n 内容与 get_department_user_detail_list 中的字典返回值是一样的。\n \"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={}&userid={}'.format(\n self.access_token,\n user_id\n )\n return rq.get(url)\n\n def get_tag_list(self):\n \"\"\"\n https://work.weixin.qq.com/api/doc#90000/90135/90216\n 获取标签列表\n :return: \n [\n {\n 'tagid': int,\n 'tagname': str,\n }\n ]\n \"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token={}'.format(self.access_token)\n return rq.get(url)['taglist']\n\n def get_tag_user_list(self, tag_id):\n \"\"\"\n https://work.weixin.qq.com/api/doc#90000/90135/90213\n 获取标签成员\n :param tag_id: 标签ID\n :return: \n [\n {\n \"userid\": \"zhangsan\",\n \"name\": \"李四\"\n }\n ],\n \"\"\"\n url = 'https://qyapi.weixin.qq.com/cgi-bin/tag/get?access_token={}&tagid={}'.format(self.access_token, tag_id)\n return rq.get(url)['userlist']\n","sub_path":"wework/corp.py","file_name":"corp.py","file_ext":"py","file_size_in_byte":9071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"492604677","text":"'''\nPrepares bam files from staged sequence.txt files\n\nRequired for any pipelines that use the Genome Analysis Toolkit.\n\nCurrnetly, this means quality score recalibration and variant calling.\n'''\nimport gzip\nimport os\nfrom Bio import SeqIO\nfrom bz2 import BZ2File\nfrom glob import iglob, glob\n\nfrom ruffus import follows, files, inputs, merge, mkdir, regex, transform\n\nfrom ..utils import CMD_DICT, call, pmsg, read_group_re\n\ndef copy_sequence_generator():\n for in_file in iglob('staging_area/*'):\n out_file = os.path.split(in_file)[-1]\n out_file = out_file.split(os.path.extsep)[0] + '.fastq.gz'\n out_file = os.path.join('fastq', out_file)\n yield [in_file, out_file]\n\n# Copy sequence from staging area\n@follows(mkdir('fastq', 'logs'))\n@files(copy_sequence_generator)\ndef copy_sequence(input_file, output_file):\n '''Copy sequence files from staging area'''\n GZIP_HEADER = '\\x1f\\x8b'\n BZIP_HEADER = 'BZ'\n\n pmsg('Copying sequence files', input_file, output_file)\n # check if this is actually a gzipped file\n header = open(input_file).read(2)\n if header == GZIP_HEADER:\n input_file_handle = gzip.open(input_file, 'rb')\n elif header == BZIP_HEADER:\n input_file_handle = BZ2File(input_file, 'r')\n else:\n input_file_handle = open(input_file, 'rb')\n output_file_handle = gzip.open(output_file, 'wb')\n\n # check whether this is a illumina or sanger fastq file\n try:\n SeqIO.convert(input_file_handle, 'fastq-illumina', output_file_handle, 'fastq-sanger')\n except ValueError as e:\n # check if this is a quality score problem\n if e.args != ('Invalid character in quality string',):\n raise e\n input_file_handle.seek(0)\n output_file_handle.seek(0)\n output_file_handle.writelines(input_file_handle.readlines())\n finally:\n input_file_handle.close()\n output_file_handle.close()\n\n@follows(mkdir('sai'), mkdir('logs'))\n@transform(copy_sequence, regex(r'^fastq/(.+)_sequence\\.fastq\\.gz$'), r'sai/\\1.sai')\ndef fastq_to_sai(input_file, output_file):\n '''Convert FASTQ files to SAI files.'''\n cmd_dict = CMD_DICT.copy()\n cmd_dict['infile'] = input_file\n cmd_dict['outfile'] = output_file\n pmsg('Aligning sequences', cmd_dict['infile'], cmd_dict['outfile'])\n bwacmd = '%(bwa)s aln -t %(threads)s -f %(outfile)s %(reference)s %(infile)s'\n call(bwacmd, cmd_dict)\n\n# Merge paired ends to SAM\n@follows(mkdir('sam'))\n@transform(fastq_to_sai, regex(r'^sai/(\\w+)_s_(\\d)(_1)?\\.sai$'),\n inputs([r'sai/\\1_s_\\2*.sai', r'fastq/\\1_s_\\2*.fastq.gz']),\n r'sam/\\1_s_\\2.sam')\ndef make_sam(input_files, output_file):\n '''Convert SAI files and FASTQ files to SAM files.'''\n\n def saicmp(x, y):\n '''Compare function for moving sai files to front of list'''\n if x.endswith('sai') and not y.endswith('sai'):\n return - 1\n elif y.endswith('sai') and not x.endswith('sai'):\n return 1\n else:\n return cmp(x, y)\n\n cmd_dict = CMD_DICT.copy()\n assert type(input_files) is type([])\n pmsg('Generating SAM file', ', '.join(input_files), output_file)\n # sort input files\n input_files.sort(cmp=saicmp)\n # Run bwa to merge into SAM file\n cmd_dict['infiles'] = ' '.join(input_files)\n cmd_dict['outfile'] = output_file\n cmd_dict.update(read_group_re.match(input_files[-1]).groupdict())\n bwa_cmd = '%(bwa)s %(sam_type)s -i %(read_group)s -m %(sample)s -l %(read_group)s ' + \\\n '-p illumina -f %(outfile)s %(reference)s %(infiles)s'\n call(bwa_cmd, cmd_dict)\n\n # if this is single ended, then we need to sort and clip the sam file\n if cmd_dict['sam_type'] == 'samse':\n # sort sam file\n cmd_dict['infile'] = output_file\n cmd_dict['outfile'] = os.path.splitext(output_file)[0] + '.sorted.sam'\n pmsg('Sorting SAM file', cmd_dict['infile'], cmd_dict['outfile'])\n sam_cmd = '%(samtools)s view -hSu %(infile)s | ' + \\\n '%(samtools)s sort -o - %(outfile)s | ' + \\\n '%(samtools)s view -h -o %(outfile)s -'\n call(sam_cmd, cmd_dict)\n call('rm %(infile)s', cmd_dict, is_logged=False)\n # clip reads\n cmd_dict['infile'] = cmd_dict['outfile']\n cmd_dict['outfile'] = output_file\n pmsg('Clipping reads', cmd_dict['infile'], cmd_dict['outfile'])\n clip_cmd = '%(clip_se_reads)s -o %(outfile)s %(primers)s %(infile)s'\n call(clip_cmd, cmd_dict)\n call('rm %(infile)s', cmd_dict, is_logged=False)\n\n# Sort BAM file\n@follows(mkdir('sorted'))\n@transform(make_sam, regex(r'^sam/(.+)\\.sam'), r'sorted/\\1.sorted.bam')\ndef sort_bam(input_file, output_file):\n '''Sort BAM files by coordinate.'''\n cmd_dict = CMD_DICT.copy()\n cmd_dict['infile'] = input_file\n cmd_dict['outfile'] = output_file\n cmd_dict['outprefix'] = os.path.splitext(cmd_dict['outfile'])[0]\n pmsg('Cooridinate sorting BAM file', cmd_dict['infile'], cmd_dict['outfile'])\n sam_cmd = '%(samtools)s view -hSu %(infile)s | %(samtools)s sort - %(outprefix)s'\n call(sam_cmd, cmd_dict)\n\n# Remove duplicates\n@follows(mkdir('deduped'))\n@transform(sort_bam, regex(r'^sorted/(.+)\\.sorted\\.bam$'), r'deduped/\\1.deduped.bam')\ndef remove_duplicates(input_file, output_file):\n '''Remove duplicates from BAM file'''\n cmd_dict = CMD_DICT.copy()\n cmd_dict['infile'] = input_file\n cmd_dict['outfile'] = output_file\n if cmd_dict['sam_type'] == 'sampe':\n cmd_dict['metrics'] = output_file.rstrip('bam') + 'metrics'\n pmsg('Removing duplicates', input_file, output_file)\n sam_cmd = '%(samtools)s rmdup %(infile)s %(outfile)s'\n call(sam_cmd, cmd_dict)\n else:\n pmsg('Linking files', input_file, output_file)\n call('ln %(infile)s %(outfile)s', cmd_dict, is_logged=False)\n samtools_cmd = '%(samtools)s index %(outfile)s'\n call(samtools_cmd, cmd_dict, is_logged=False)\n\n@follows(remove_duplicates, mkdir('coverage'))\n@merge('deduped/*.bam', 'coverage/merged.coverage')\ndef calculate_coverage(input_files, output_file):\n '''Calculate coverage statistics'''\n cmd_dict = CMD_DICT.copy()\n cmd_dict['infiles'] = ' '.join([ '--input_file %s' % f for f in input_files ])\n cmd_dict['outfile'] = output_file\n pmsg('Coverage calculations', ', '.join(input_files), output_file)\n gatk_cmd = '%(gatk)s --analysis_type DepthOfCoverage ' + \\\n '--reference_sequence %(reference)s ' + \\\n '--intervals %(target_interval)s ' + \\\n '--minMappingQuality 10 ' + \\\n '--minBaseQuality 10 ' + \\\n '--omitDepthOutputAtEachBase ' + \\\n '%(infiles)s ' + \\\n '--out %(outfile)s'\n call(gatk_cmd, cmd_dict)\n\nstages_dict = {\n 'copy': copy_sequence,\n 'align': fastq_to_sai,\n 'sam': make_sam,\n 'sort': sort_bam,\n 'dedupe': remove_duplicates,\n 'coverage': calculate_coverage,\n 'default': calculate_coverage,\n}\n\n","sub_path":"nextgen_pipeline/pipelines/align_reads.py","file_name":"align_reads.py","file_ext":"py","file_size_in_byte":6969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535721574","text":"\"\"\"\nThis module performs unit tests on the nytimes article retriever class.\n\"\"\"\n# system import\nimport sys\nimport unittest\nimport pandas as pd\n\nsys.path.append('../libraries')\nsys.path.append('news_analyzer/libraries')\n\n\n# test imports\nimport configs\nimport nytimes_article_retriever as nytar\n\n\nclass TestNytimesArticleRetriever(unittest.TestCase):\n \"\"\" Usage: unit-test.\n\n python test_topic_modeling.py\n \"\"\"\n def setUp(self):\n # makes calls to API\n self.all_topics = nytar.get_nytimes_data()\n # makes calls to API\n self.some_topics = nytar.get_nytimes_data(['arts',\n 'automobiles',\n 'books'])\n self.all_topic_words = nytar.get_section_words(self.all_topics)\n self.some_topic_words = nytar.get_section_words(self.some_topics)\n self.get_all_topic_words = nytar.get_nytimes_topic_words()\n self.aggregated_data = nytar.aggregate_data()\n\n def test_get_nytimes_data(self):\n \"\"\" Test to check getting NYtimes data.\n \"\"\"\n # check return types\n self.assertTrue(isinstance(self.all_topics, pd.DataFrame))\n self.assertTrue(isinstance(self.some_topics, pd.DataFrame))\n # check length and shape of the return types\n # print(\"all topics:\")\n # print(len(self.all_topics))\n # self.assertTrue(len(self.all_topics) ==\n # len(configs.GUIDED_LDA_TOPICS))\n # self.assertTrue(len(self.some_topics) == 3)\n # self.assertTrue(self.all_topics.shape[1] == 2) # 2 columns of data\n\n def test_aggregate_data(self):\n \"\"\" Test to check process for aggregating data.\n \"\"\"\n # check return types\n self.assertTrue(isinstance(self.aggregated_data, pd.DataFrame))\n # check length and shape of the return types\n # print(len(self.aggregated_data))\n # print(len(configs.GUIDED_LDA_TOPICS))\n # self.assertTrue(len(self.aggregated_data) ==\n # len(configs.GUIDED_LDA_TOPICS))\n\n def test_get_section_words(self):\n \"\"\" Test to check getting NYTimes section words.\n \"\"\"\n # check return type\n self.assertTrue(isinstance(self.all_topic_words, list))\n self.assertTrue(isinstance(self.some_topic_words, list))\n\n # check dimensions\n # self.assertTrue(len(self.all_topic_words) ==\n # len(configs.GUIDED_LDA_TOPICS))\n # self.assertTrue(len(self.some_topic_words) == 3)\n\n def test_get_nytimes_topic_words(self):\n \"\"\" Test to check combined function for getting NYTimes data and\n extracting section words.\n \"\"\"\n # check return type\n self.assertTrue(isinstance(self.get_all_topic_words, list))\n # print(\"all topic words\")\n # print(len(self.get_all_topic_words))\n # print(len(self.all_topic_words))\n # self.assertTrue(len(self.get_all_topic_words) ==\n # len(self.all_topic_words))\n\n # check each category has at least 10 words\n min_length = 10\n for i in range(len(self.get_all_topic_words)):\n min_length = min(min_length, len(self.get_all_topic_words[i]))\n # check each value is unique\n self.assertTrue(len(self.get_all_topic_words[i]) ==\n len(set(self.get_all_topic_words[i])))\n # check first item is a category name\n self.assertTrue(self.get_all_topic_words[i][0] in\n configs.GUIDED_LDA_TOPICS)\n print(\"min_length:\", min_length)\n self.assertTrue(min_length >= 10)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"news_analyzer/tests/test_nytimes_article_retriever.py","file_name":"test_nytimes_article_retriever.py","file_ext":"py","file_size_in_byte":3715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350050817","text":"#!/usr/bin/python\nfrom ConfigUtils import getBaseConfig\nfrom LogUtils import getModuleLogger\nfrom StringUtils import isValidUrl, md5SumFile, randomString\nfrom urlparse import urlparse\nfrom ViperUtils import getTags, uploadToViper, isNewEntry\nimport json\nimport os\nimport requests\nimport sys\n\ncDir = os.path.dirname(os.path.realpath(__file__))\nrootDir = os.path.abspath(os.path.join(cDir, os.pardir))\nbaseConfig = getBaseConfig(rootDir)\nlogging = getModuleLogger(__name__)\n\ndef getMalShareDigest():\n try:\n payload = {'action': 'getlistraw', 'api_key': baseConfig.malShareApiKey }\n userAgent = {'User-agent': baseConfig.userAgent}\n\n logging.info(\"Fetching latest MalShare MD5 list.\")\n\n request = requests.get(baseConfig.malShareApi, params=payload, headers=userAgent)\n\n if request.status_code == 200:\n malList = []\n\n for line in request.content.split('\\n'):\n malList.append(line.strip())\n return malList\n\n else:\n logging.error(\"Problem connecting to MalShare. Status code:{0}. Please try again later.\".format(request.status_code))\n sys.exit(1)\n\n except Exception as e:\n logging.error(\"Problem connecting to MalShare. Please try again later.\")\n logging.exception(sys.exc_info())\n logging.exception(type(e))\n logging.exception(e.args)\n logging.exception(e)\n sys.exit(1)\n\ndef getMalShareList():\n try:\n payload = {'action': 'getsourcesraw', 'api_key': baseConfig.malShareApiKey }\n userAgent = {'User-agent': baseConfig.userAgent}\n\n logging.info(\"Fetching latest MalShare Source list.\")\n\n request = requests.get(baseConfig.malShareApi, params=payload, headers=userAgent)\n\n if request.status_code == 200:\n malList = []\n\n for line in request.content.split('\\n'):\n url = line.strip()\n if isValidUrl(url):\n malList.append(url)\n return malList\n \n else:\n logging.error(\"Problem connecting to MalShare. Status code:{0}. Please try again later.\".format(request.status_code))\n sys.exit(1)\n\n except Exception as e:\n logging.error(\"Problem connecting to MalShare. Please try again later.\")\n logging.exception(sys.exc_info())\n logging.exception(type(e))\n logging.exception(e.args)\n logging.exception(e)\n sys.exit(1)\n\ndef getMalShareSource(fileHash):\n try:\n payload = {'action': 'details', 'api_key': baseConfig.malShareApiKey, 'hash' : fileHash }\n userAgent = {'User-agent': baseConfig.userAgent}\n\n request = requests.get(baseConfig.malShareApi, params=payload, headers=userAgent)\n\n if request.status_code == 200:\n sources = json.loads(request.content)\n source = sources['SOURCES'][0]\n return source\n else:\n logging.error(\"Problem connecting to MalShare. Status code: {0}. Please try again later.\".format(request.status_code))\n sys.exit(1)\n\n except Exception as e:\n logging.error(\"Problem connecting to MalShare. Please try again later.\")\n logging.exception(sys.exc_info())\n logging.exception(type(e))\n logging.exception(e.args)\n logging.exception(e)\n sys.exit(1)\n\ndef getMalShareFile(fileHash):\n try:\n payload = {'action': 'getfile', 'api_key': baseConfig.malShareApiKey, 'hash' : fileHash }\n userAgent = {'User-agent': baseConfig.userAgent}\n\n request = requests.get(baseConfig.malShareApi, params=payload, headers=userAgent)\n\n if request.status_code == 200:\n response = request.content\n\n if \"Sample not found\" in response:\n logging.warning(\"Sample not found.\")\n return False\n if \"Account not activated\" in response:\n logging.error(\"Bad API key.\")\n sys.exit(1)\n if \"Over Request Limit\" in response:\n logging.error(\"Exceeded MalShare request quota. Please temporarily disable MalShare.\")\n sys.exit(1)\n\n tmpName = randomString(32)\n tmpFilePath = os.path.join(baseConfig.outputFolder, tmpName)\n open(tmpFilePath,\"wb\").write(response)\n logging.info(\"Saved as temporary file: {0}. Calculating MD5.\".format(tmpFilePath))\n\n fileMD5 = md5SumFile(tmpFilePath)\n filePath = os.path.join(baseConfig.outputFolder, fileMD5)\n os.rename(tmpFilePath, filePath)\n logging.info(\"Renamed as file: {0}. Checking Viper again.\".format(filePath))\n\n if isNewEntry(fileHash=fileMD5):\n url = getMalShareSource(fileHash)\n fileName = url.split('/')[-1]\n tags = getTags(fileMD5, url, \"malshare-spider\")\n uploadToViper(filePath, fileName, tags)\n\n if baseConfig.deleteOutput.lower() == \"yes\":\n logging.info(\"Removing file: {0}\".format(filePath))\n os.remove(filePath)\n\n return True\n\n else:\n logging.info(\"Removing file: {0}\".format(filePath))\n os.remove(filePath)\n return False\n\n else:\n logging.error(\"Problem connecting to MalShare. Status code: {0}. Please try again later.\".format(request.status_code))\n sys.exit(1)\n \n except Exception as e:\n logging.error(\"Problem connecting to MalShare. Please try again later.\")\n logging.exception(sys.exc_info())\n logging.exception(type(e))\n logging.exception(e.args)\n logging.exception(e)\n sys.exit(1)\n","sub_path":"util/MalShare.py","file_name":"MalShare.py","file_ext":"py","file_size_in_byte":5724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"423012442","text":"import os\nfrom xlrd import open_workbook\nimport datetime\nimport math\nfrom xlwt import Workbook\nimport collections\nfrom collections import defaultdict\nimport pandas as pd\n\ndef bld_output(sp_pa_audict, cdatein):\n rw = 1\n cl = 0\n\n for ia, va in sp_pa_audict.items():\n print(\"audict.items key: \", ia, \" audict.items value: \", va)\n rowkey = ia.split('.')\n print(\"rowkey: \", rowkey)\n prtcase = rowkey[0]\n prtrtdt = rowkey[1]\n print(\"prcase: \", prtcase, \" prcidt: \", prtrtdt)\n itmkeys = list(va.keys())\n itmvals = list(va.values())\n print(\"rw:\", rw)\n write_row_key(prtcase, prtrtdt, rw)\n lpx = 0\n rowval = []\n while lpx < len(va):\n prtkey = itmkeys[lpx]\n prtvals = itmvals[lpx]\n print(\"itmkey: \", prtkey, \" itmvals: \", prtvals, \" lpx:\", lpx)\n lpx = lpx + 1\n write_row_value(itmvals, itmkeys, rw, cdatein)\n ofst = lpx\n rw = rw + 1\n\n\ndef write_row_key(prtcase, prtrtdt, rw):\n\n sheet1.write(rw, 0, prtcase)\n sheet1.write(rw, 1, prtrtdt)\n\n\ndef write_row_value(rowval, itmkeys, rw, cdatein):\n idxe = 0\n print(\"cdatein: \", cdatein)\n for val in rowval:\n# sheet1.write(rw, idxe + 2, val)\n edate = pd.to_datetime(itmkeys[idxe])\n edate2 = pd.datetime.now()\n print(\"edate: \", edate, \" edate2: \", edate2)\n wcol = edate2 - edate\n wcol2 = wcol.days\n sheet1.write(rw, wcol2 + 1, val)\n idxe = idxe + 1\n\n\n\ndef dt_tbl():\n cdate = datetime.date.today()\n pycurdt = datetime.date.toordinal(cdate)\n cdate2 = pycurdt - 693594\n\n print(\"Today's Date is: \", cdate)\n print(\"Today's Date as ordinal value: \", cdate2)\n print(\"************** Start List *****************\")\n\n sheet1.write(0, 0, \"Case ID\")\n sheet1.write(0, 1, \"Routing Date\")\n\n for x in range(45, 0, -1):\n mdate = cdate2 - x\n dt = mdate\n mdate2 = cnvt_excel_dt(dt)\n print(\"value of mdate: \", mdate, \" display value: \", mdate2, \" ndx: \", x)\n smdate2 = str(mdate2)\n sheet1.write(0, x + 1, smdate2)\n return(cdate2)\n\n\ndef makehash():\n\n return collections.defaultdict(makehash)\n\n\ndef cnvt_excel_dt(dt):\n\n dateoffset = 693594\n return datetime.date.fromordinal(dateoffset + int(dt))\n\n\ndef write_dict1(dictKey, dictValue, dictKey2, dictValue2):\n\n sp_pa_audict[dictKey][dictKey2] = dictValue2\n\n\ndef proc_inpt(fileIn, cdatein):\n\n wb = open_workbook(fileIn, on_demand=True)\n\n sheetCnt = wb.nsheets\n\n print(\"Number of Worksheets: \", sheetCnt)\n\n for s in wb.sheets():\n print('Sheet Name: ', s.name)\n\n sheet = wb.sheet_by_index(0)\n\n rowCnt = sheet.nrows\n\n print(\"Value of Row Count: \", rowCnt)\n\n for row in range(1, sheet.nrows):\n tstrslt = \"\"\n rowVal = sheet.row_values(row)\n dt = rowVal[0]\n ciDate = cnvt_excel_dt(dt)\n tstrslt = math.isnan(float(rowVal[18]))\n if tstrslt is False:\n dt = rowVal[18]\n rtDate = cnvt_excel_dt(dt)\n else:\n print(\"Test Result is True:\", rowVal[18])\n rtDate = 0\n dtDiff = datetime.timedelta(cdatein - int(rowVal[18]))\n dictKey = str(int(rowVal[4])) + \".\" + str(rtDate)\n if row == 1:\n print(\"first time\")\n ciUpdate = \"CI_Updt_\" + str(ciDate)\n print(\"Check In date: \", ciUpdate)\n dictKey2 = str(ciDate)\n dictValue = str(rowVal[4]) + \".\" + str(rtDate)\n dictValue2 = str(rowVal[19])\n write_dict1(dictKey, dictValue, dictKey2, dictValue2)\n\n wb.release_resources()\n\n\nlstDir = \"C:/Users/e1ze4m0/Documents/Indivior Program/Indivior Hub/MS Excel/SP Status/Input/\"\n\nfl_list = os.listdir(lstDir)\n\nsp_pa_audict = defaultdict(dict)\n\nwbout = Workbook()\nsheet1 = wbout.add_sheet('SP Prior Auths 1', cell_overwrite_ok=True)\n\nfor x in fl_list:\n filein = lstDir + x\n print(filein, sep=\"\\n\")\n print(\"value of x: \", x)\n cdatein = dt_tbl()\n proc_inpt(filein, cdatein)\n bld_output(sp_pa_audict, cdatein)\n\n\n\nwbout.save('xlwt SP_PA1.xls')\n\nprint(\"delete dictionary\")\ndel sp_pa_audict\n\n\n","sub_path":"BuildIt.py","file_name":"BuildIt.py","file_ext":"py","file_size_in_byte":4159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262745951","text":"\"\"\"\nAssignment 4: Metaprogramming\n\nThe idea of this assignment is to get you used to some of the dynamic\nand functional features of Python and how they can be used to perform\nuseful metaprogramming tasks to make other development tasks easier.\n\"\"\"\n\nimport functools\nimport logging\nimport sys\n\ndef logcalls(prefix):\n \"\"\"A function decorator that logs the arguments and return value\n of the function whenever it is called.\n\n The output should be to sys.stderr in the format:\n \"{prefix}: {function name}({positional args}..., {keyword=args}...)\" \n and \n \"{prefix}: {function name} -> {return value}\"\n respectively for call and return.\n\n Look up functools.wraps and use it to make the function you return\n have the same documentation and name as the function passed in.\n\n This will be used like:\n @logcalls(\"test\")\n def f(arg):\n return arg\n\n (This is a more refined version of what I did in class)\n \"\"\"\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kws):\n if kws and args:\n kws_and_args = \", \"\n else:\n kws_and_args = \"\"\n\n #print formatted string explained above to stderr\n print(\"{}: {}({}{}{})\".format(prefix, func.__name__,\n \", \".join(repr(i) for i in args), kws_and_args,\n \", \".join(\"{}={}\".format(a, repr(b)) for a, b in kws.items()) ),\n file = sys.stderr)\n\n func_return_val = func(*args, **kws)\n print(\"{}: {} -> {}\".format(prefix, func.__name__, func_return_val), file = sys.stderr)\n return func_return_val\n return wrapper\n return decorator\n\n\ndef module_test(mod=None):\n \"\"\"Run all the test functions in the module mod.\n\n If the argument mod is not given you should test the module\n __main__. This is useful for easy testing of modules by using\n them as scripts. And it tests that you remember the early\n lectures.\n\n A test function is a function with a name that begins with \"test\".\n All the test functions take no arguments and throw an exception if\n the test fails.\n\n For each test, print a block to stderr in the following format:\n {test function name}: {either PASS or FAIL: {exception type name} {exception as a string}}\n {test function doc string}\n For example of a test is defined:\n def testA():\n '''Test A'''\n raise RuntimeError(\"Blah\")\n Your function should print:\n testA: FAIL: RuntimeError 'Blah'\n Test A\n \n Make sure you handle functions without doc strings without crashing\n (you can treat it as an empty doc string).\n \"\"\"\n if mod is None:\n \t#this code is in case mod is not given to us, the default value is none\n import __main__\n mod = __main__\n for func_name, vals in mod.__dict__.items():\n if func_name.startswith(\"test\"):\n try:\n vals()\n except Exception as e:\n result = \"FAIL: {} {}\".format(type(e).__name__, str(e))\n else:\n result = \"PASS\"\n \n print(\"{}: {}\".format(func_name, result), file=sys.stderr)\n if vals.__doc__ is None:\n print(\"\", file = sys.stderr)\n else: \n print(vals.__doc__, file = sys.stderr)\n \n","sub_path":"assignment4/assignment4.py","file_name":"assignment4.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"511460340","text":"# Use operating system dependant functionality\nimport os\n# Allow full utilisation of Flask framework\nfrom flask import Flask, render_template, redirect, request, url_for, session, flash\n# Allow database manipulation\nfrom flask_pymongo import PyMongo, pymongo\nfrom pymongo.collation import Collation\n# Allow working with _id fields\nfrom bson.objectid import ObjectId\n# Allow date and time manipulation\nfrom datetime import datetime, timedelta\n# For database querying\nfrom bson.son import SON\n\n# Initialise Flask\napp = Flask(__name__)\n# Connect to Database\napp.config[\"MONGO_DBNAME\"] = os.environ.get('MONGO_DBNAME')\napp.config[\"MONGO_URI\"] = os.environ.get('MONGO_URI')\n\n# Secret Key\napp.secret_key = os.environ.get('FLASK_SECRET_KEY')\n\n# Initialise PyMongo\nmongo = PyMongo(app)\n\n\"\"\" INDEX PAGE \"\"\"\n@app.route('/index')\n@app.route('/')\ndef index():\n \"\"\"\n This is the default route\n Render the home page\n Grab the current top 3 tracks by upvotes and display them on the home page\n \"\"\"\n # The below lines were run in order to create db indexes preventing duplicate youtube videos and genres from being added\n \n # mongo.db.tracks.create_index([('youtube_link', \n # pymongo.ASCENDING)], \n # unique=True)\n \n # mongo.db.genres.create_index([('genre', \n # pymongo.ASCENDING)], \n # unique=True, \n # collation=Collation(locale = 'en', strength = 2))\n\n # Clear any session variables the user may have \n # This ensures the user can go to get_tracks cleanly\n session.clear()\n \n # Get the tracks collection\n tracks = mongo.db.tracks.find()\n \n # Set the html title\n title = \"DesertIsland | Home\"\n \n # Render the template, pass through necessary values\n return render_template(\"index.html\", \n # Sort all tracks by upvotes descending, limit to 3 results\n tracks = tracks.sort('upvotes', pymongo.DESCENDING).limit(3),\n title = title\n )\n\"\"\" /INDEX PAGE \"\"\"\n\n\"\"\" ABOUT PAGE \"\"\"\n@app.route('/about')\ndef about():\n \"\"\"\n Render the About page\n \"\"\"\n # Set the html title\n title = \"DesertIsland | About\"\n \n # Render the template, pass through necessary values\n return render_template(\"about.html\", title = title)\n\"\"\" /ABOUT PAGE \"\"\"\n\n\"\"\" DATABASE STATS PAGE \"\"\"\n@app.route('/stats')\ndef stats():\n \"\"\"\n Returns the stats template, populated with statistical values for the current database\n \"\"\"\n # Get the tracks collection\n tracks_collection = mongo.db.tracks\n \n \"\"\" Total Number Of Tracks \"\"\"\n # Count the number of tracks in the collection\n tracks_count = tracks_collection.count()\n \"\"\" /Total Number Of Tracks \"\"\"\n \n \"\"\" Most Popular Decade By Number Of Tracks \"\"\"\n # Find the decade with the most number of tracks\n # First, create a dictionary containing the counts of the number of tracks in each decade\n decades_dict = { \n 'Pre 1950s': tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1000}}, \n {\"year\": {'$lt': 1950}}\n ]\n }).count(),\n 'The 1950s': tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1950}}, \n {\"year\": {'$lt': 1960}}\n ]\n }).count(),\n 'The 1960s': tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1960}}, \n {\"year\": {'$lt': 1970}}\n ]\n }).count(),\n 'The 1970s': tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1970}}, \n {\"year\": {'$lt': 1980}}\n ]\n }).count(),\n 'The 1980s': tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1980}}, \n {\"year\": {'$lt': 1990}}\n ]\n }).count(),\n 'The 1990s': tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1990}}, \n {\"year\": {'$lt': 2000}}\n ]\n }).count(),\n 'The 2000s': tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 2000}}, \n {\"year\": {'$lt': 2010}}\n ]\n }).count(),\n 'The 2010s': tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 2010}}, \n {\"year\": {'$lt': 2020}}\n ]\n }).count()\n }\n\n # Then get the max count, find the decade with the most tracks\n most_pop_decade = max(decades_dict, key=decades_dict.get)\n \"\"\" /Most Popular Decade By Number Of Tracks \"\"\"\n \n \"\"\" Most Frequent \"\"\"\n def most_freq(key_name):\n \"\"\"\n Function that can be used to find the most frequent values for a given key in the database\n \"\"\"\n # Establish a pipeline\n most_freq_pipeline = [\n # Sum the counts of each key name\n {\"$group\": {\"_id\": key_name, \"count\": {\"$sum\": 1}}},\n # Sort descending so highest is first\n {\"$sort\": SON([(\"count\", -1)])}\n ]\n \n # Convert the results of the pipeline into a list, extract the first value (the highest count)\n most_freq_list = list(tracks_collection.aggregate(most_freq_pipeline))[0]\n \n # Get the value from the resultant dictionary\n return most_freq_list['_id']\n \n # Call most_freq for artist\n most_freq_artist = most_freq('$artist')\n # And genre\n most_freq_genre = most_freq('$genre')\n \"\"\" /Most Frequent \"\"\"\n \n \"\"\" Sum Of Upvotes For All Tracks \"\"\"\n # First, get a list of all the upvote values\n all_upvotes_list = list(tracks_collection.find( { },\n { 'upvotes': 1, '_id' :0 }\n ))\n \n # Iterate through the list and sum the values\n all_upvotes = sum(item['upvotes'] for item in all_upvotes_list)\n \"\"\" /Sum Of Upvotes For All Tracks \"\"\"\n \n \"\"\" Most Popular Artist By Likes \"\"\"\n # Get a list of all the artists\n most_pop_artist = list(tracks_collection.aggregate([\n # Group by artist\n { '$group': { '_id': \"$artist\", \n # Sum the upvotes for each artist\n 'upvotes': { '$sum': '$upvotes' } } },\n # Sort descending\n { '$sort': { 'upvotes': -1 } }]))[0] # Grab the first item (the highest)\n \"\"\" /Most Popular Artist By Likes \"\"\"\n\n # Set the html title\n title = \"DesertIsland | Stats\"\n \n # Render the template, pass through necessary values\n return render_template(\"stats.html\", \n title = title, \n tracks_count = tracks_count, \n most_pop_decade = most_pop_decade, \n most_freq_artist = most_freq_artist,\n most_freq_genre = most_freq_genre,\n all_upvotes = all_upvotes,\n most_pop_artist = most_pop_artist)\n\"\"\" /DATABASE STATS \"\"\"\n\n\"\"\" GET_TRACKS \"\"\"\n@app.route('/get_tracks//', defaults = {'track_scroll_id': None}, methods = ['POST','GET'])\n@app.route('/get_tracks///', methods = ['POST','GET'])\ndef get_tracks(decade_filter, sorting_order, track_scroll_id):\n \"\"\"\n This function renders the tracks on tracks.html\n Tracks can be sorted and filtered by various criteria\n The filter and sort values are passed into the function from other functions which redirect to here\n \"\"\"\n # Get the tracks collection\n tracks_collection = mongo.db.tracks\n\n # hold_pagination will only ever be in session if the user has come from a url where it makes sense to keep the pagination of content \n # (e.g. they've clicked 'Next' in the list of tracks)\n # Pagination is held for next_tracks, prev_tracks, upvote_track and edit_track\n # In which case, ensure the pagination value currently in the session is used to show the user the correct tracks\n if 'hold_pagination' in session:\n pagination = session['pagination']\n # If hold_pagination does not exist, this means the user has come to tracks.html some other way, presumably by refreshing the page or clicking a nav link\n # This means the pagination should be set to 0 to ensure the user is seeing the first top 5 tracks\n else:\n session['pagination'] = 0\n pagination = session['pagination']\n \n # Delete the hold_pagination session.\n # If this session is needed again, it will be created by the appropriate function\n # For all other use cases it is redundant\n session.pop('hold_pagination', None)\n \n # # Pop the genre_edit_track_id session\n # # This stops the same track id from getting passed through to edit no matter which track the user chooses to edit\n # session.pop('genre_edit_track_id', None)\n \n # Determine the tracks to return based on the decade filter, the value of which is determined by the select box on tracks.html\n if decade_filter == \"pre1950\":\n tracks_decade = tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1000}}, \n {\"year\": {'$lt': 1950}}\n ]\n })\n \n # Set the decade filter text that is displayed as part of the tracks.html h1\n decade_filter_text = \"Pre-1950\"\n \n elif decade_filter == \"1950s\":\n tracks_decade = tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1950}}, \n {\"year\": {'$lt': 1960}}\n ]\n })\n \n decade_filter_text = \"1950s\"\n \n elif decade_filter == \"1960s\":\n tracks_decade = tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1960}}, \n {\"year\": {'$lt': 1970}}\n ]\n })\n \n decade_filter_text = \"1960s\"\n \n elif decade_filter == \"1970s\":\n tracks_decade = tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1970}}, \n {\"year\": {'$lt': 1980}}\n ]\n })\n \n decade_filter_text = \"1970s\"\n \n elif decade_filter == \"1980s\":\n tracks_decade = tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1980}}, \n {\"year\": {'$lt': 1990}}\n ]\n })\n \n decade_filter_text = \"1980s\"\n \n elif decade_filter == \"1990s\":\n tracks_decade = tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 1990}}, \n {\"year\": {'$lt': 2000}}\n ]\n })\n \n decade_filter_text = \"1990s\"\n \n elif decade_filter == \"2000s\":\n tracks_decade = tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 2000}}, \n {\"year\": {'$lt': 2010}}\n ]\n })\n \n decade_filter_text = \"2000s\"\n \n elif decade_filter == \"2010s\":\n tracks_decade = tracks_collection.find({\"$and\": [\n {\"year\": {'$gte': 2010}}, \n {\"year\": {'$lt': 2020}}\n ]\n })\n \n decade_filter_text = \"2010s\"\n \n # Else the decade filter is currently set to \"Show All\" \n else:\n tracks_decade = tracks_collection.find()\n \n decade_filter_text = \"All Decades\"\n \n # The sorting_order variable is used to determine how to sort the tracks\n # sorting_order = 1 means sort tracks by HIGHEST UPVOTES. This is the default sorting order\n # sorting_order = 2 means sort tracks by LOWEST UPVOTES first\n # sorting_order = 3 means sort tracks by date added to the database with the LATEST date first\n # sorting_order = 4 means sort tracks by date added to the databse with the OLDEST date first\n if sorting_order == 1:\n # Find all tracks within the tracks collection. Sort by upvotes descending, skip using the value of pagination and limit\n tracks = tracks_decade.sort(\n 'upvotes', pymongo.DESCENDING).skip(\n pagination).limit(5)\n \n # Set the text to display as part of the heading on tracks.html \n sorting_order_text = \"Most Popular\"\n \n elif sorting_order == 2:\n # Find all tracks within the tracks collection. Sort by upvotes ascending, skip using the value of pagination and limit\n tracks = tracks_decade.sort(\n 'upvotes', pymongo.ASCENDING).skip(\n pagination).limit(5)\n\n # Set the text to display as part of the heading on tracks.html \n sorting_order_text = \"Least Popular\"\n \n elif sorting_order == 3:\n # Find all tracks within the tracks collection. Sort by date_added_raw descending, skip using the value of pagination and limit\n tracks = tracks_decade.sort(\n 'date_added_raw', pymongo.DESCENDING).skip(\n pagination).limit(5)\n \n # Set the text to display as part of the heading on tracks.html \n sorting_order_text = \"Date Added (Newest)\"\n \n elif sorting_order == 4:\n # Find all tracks within the tracks collection. Sort by date_added_raw ascending, skip using the value of pagination and limit\n tracks = tracks_decade.sort(\n 'date_added_raw', pymongo.ASCENDING).skip(\n pagination).limit(5)\n \n # Set the text to display as part of the heading on tracks.html \n sorting_order_text = \"Date Added (Oldest)\"\n \n # Get the number of tracks as currently defined by the filtering\n # This is used within tracks.html to determine whether to show the 'next' button\n # It would not make sense to show the next button if there are no more tracks to view \n # Also determines whether to show a message if no tracks have been found for a particular filter\n tracks_count = tracks.count() \n \n # Set the html title\n title = \"DesertIsland | Charts\"\n\n # Render tracks.html\n # tracks is the list of tracks to be rendered\n # decade_filter ensures that only the tracks from the correct decade are displayed\n # decade_filter_text and sorting_order_text renders the correct subtitle for the page\n # sorting_order is how tracks are to be sorted (corresponding to the system in the if/else statement above)\n # pagination determines how many tracks are to be skipped. The user navigates through the pagination using the next and previous buttons on tracks.html\n # tracks_col_count determines whether to hide the next and previous buttons. If the user has reached the end of the list it doesn't make sense and would be confusing for them to be able to click 'Next'\n # track_scroll_id ensures the user is scrolled to the correct track when the page reloads after a Like\n # title is the html title\n return render_template(\"tracks.html\", \n tracks = tracks,\n decade_filter = decade_filter,\n decade_filter_text = decade_filter_text,\n sorting_order = sorting_order,\n sorting_order_text = sorting_order_text,\n pagination = pagination,\n tracks_count = tracks_count,\n track_scroll_id = track_scroll_id,\n title = title\n )\n\"\"\" /GET_TRACKS \"\"\" \n\n\"\"\" NEXT TRACKS \"\"\"\n@app.route('/next_tracks//')\ndef next_tracks(decade_filter, sorting_order):\n \"\"\"\n This function takes the user to the next 5 tracks, determined by the pagination the user is currently on, \n the sorting order they are currently using as well as the filtering options set\n \"\"\"\n # Set pagination. If the user clicks 'next', pagination is increased by 5\n session['pagination'] += 5\n session['hold_pagination'] = True\n \n # Render the template, pass through necessary values\n return redirect(url_for('get_tracks', decade_filter = decade_filter, sorting_order = sorting_order))\n\"\"\" /NEXT TRACKS \"\"\" \n\n\"\"\" PREV TRACKS \"\"\"\n@app.route('/prev_tracks//')\ndef prev_tracks(decade_filter, sorting_order):\n \"\"\"\n This function takes the user to the previous 5 tracks, determined by the pagination the user is currently on, \n the sorting order they are currently using as well as the filtering options set\n \"\"\"\n # Set pagination. If the user clicks 'previous', pagination is decreased by 5\n session['pagination'] -= 5\n session['hold_pagination'] = True\n \n # Render the template, pass through necessary values\n return redirect(url_for('get_tracks', decade_filter = decade_filter, sorting_order = sorting_order))\n\"\"\" /PREV TRACKS \"\"\"\n\n\"\"\" SORT TRACKS UPVOTES DESC \"\"\"\n@app.route('/sort_tracks_upvote_desc/')\ndef sort_tracks_upvote_desc(decade_filter):\n \"\"\"\n Change the sorting order to show tracks with HIGHEST upvotes first. This is the default sorting order\n \"\"\"\n # Render the template, pass through necessary values\n return redirect(url_for('get_tracks', sorting_order = 1, decade_filter = decade_filter))\n\"\"\" /SORT TRACKS UPVOTES DESC \"\"\"\n\n\"\"\" SORT TRACKS UPVOTES ASC \"\"\"\n@app.route('/sort_tracks_upvote_asc/')\ndef sort_tracks_upvote_asc(decade_filter):\n \"\"\"\n Change the sorting order to show tracks with LOWEST upvotes first\n \"\"\"\n # Render the template, pass through necessary values\n return redirect(url_for('get_tracks', sorting_order = 2, decade_filter = decade_filter))\n\"\"\" /SORT TRACKS UPVOTES ASC \"\"\"\n \n\"\"\" SORT TRACKS DATE_ADDED DESC \"\"\"\n@app.route('/sort_tracks_date_added_desc/')\ndef sort_tracks_date_added_desc(decade_filter):\n \"\"\"\n Change the sorting order to show NEWEST tracks by date added first\n \"\"\"\n # Render the template, pass through necessary values\n return redirect(url_for('get_tracks', sorting_order = 3, decade_filter = decade_filter))\n\"\"\" /SORT TRACKS DATE_ADDED DESC \"\"\"\n \n\"\"\" SORT TRACKS DATE_ADDED ASC \"\"\" \n@app.route('/sort_tracks_date_added_asc/')\ndef sort_tracks_date_added_asc(decade_filter):\n \"\"\"\n Change the sorting order to show OLDEST tracks by date added first\n \"\"\"\n # Render the template, pass through necessary values\n return redirect(url_for('get_tracks', sorting_order = 4, decade_filter = decade_filter))\n\"\"\" /SORT TRACKS DATE_ADDED ASC \"\"\"\n \n\"\"\" TRACK DETAIL PAGE \"\"\"\n@app.route('/track_detail///')\ndef track_detail(decade_filter, sorting_order, track_id):\n \"\"\"\n Render the detailed view for each track, displaying all database fields\n \"\"\"\n # Grab the track_id from what was passed through\n the_track = mongo.db.tracks.find_one({\"_id\": ObjectId(track_id)})\n \n # Format the page title\n title = \"DesertIsland | \" + the_track.get(\"artist\") + \" - \" + the_track.get('track_title')\n \n # Render the template, pass through necessary values\n return render_template(\"track-detail.html\", title = title, decade_filter = decade_filter, sorting_order = sorting_order, track = the_track)\n\"\"\" /TRACK DETAIL PAGE \"\"\"\n \n\"\"\" ADD TRACK PAGE \"\"\"\n# If the user inserts a new genre from the add_track page, ensure the newly inserted genre gets set as the value for the genre dropdown box\n# To do this, it gets passed through from insert_genre\n# By default, the user hasn't inserted a new genre\n@app.route('/add_track', defaults={'inserted_genre': None})\n@app.route('/add_track/')\ndef add_track(inserted_genre):\n \"\"\"\n Takes the user to add-track.html allowing them to add a new track to the database\n \"\"\"\n # Add a html title\n title = \"DesertIsland | Submit A Track\"\n \n # Render the template, pass through necessary values\n return render_template('add-track.html',\n title = title,\n genres=mongo.db.genres.find(),\n inserted_genre = inserted_genre)\n\"\"\" /ADD TRACK PAGE \"\"\"\n \n\"\"\" INSERT TRACK \"\"\"\n@app.route('/insert_track', methods=['POST']) # Because you're using POST here, you have to set that via methods\ndef insert_track():\n \"\"\"\n This function gets the data the user inputs to the form on add-track.html and turns it into a new document in the database\n \"\"\"\n # Format the timestamp that will be inserted into the record\n # The timestamp is a more user friendly version of the raw date object that is also created when a new document is created\n # The timestamp is what is displayed to the user, the raw date object is used in the backend, mainly for sorting\n \n # You can use jinja to do this\n timestamp = datetime.now().strftime('%d %B %Y %H:%M')\n # Get the tracks collection\n tracks = mongo.db.tracks\n\n # Try inserting the record using the fields from the form on add-track.html\n try:\n tracks.insert_one(\n {\n 'track_title': request.form.get('track_title'), # Access the tasks collection\n 'artist': request.form.get('artist'),\n 'youtube_link': request.form.get('youtube_link'),\n 'year': int(request.form.get('year')),\n 'genre': request.form.get('genre'),\n 'user_name': request.form.get('user_name'),\n 'description': request.form.get('description'),\n # Upvotes is set to 1 by default. This idea is borrowed from Reddit, in that a user who uploads a track would presumably want to upvote it as well\n 'upvotes': 1,\n # date_added is the human friendly date\n 'date_added': timestamp,\n # date_added_raw is the python friendly date\n 'date_added_raw': datetime.now()\n }\n )\n \n # Feedback to the user the track was successfully submitted\n flash('Track submitted successfully!', 'success')\n \n # Once submitted, redirect to the get_tracks function to view the collection using the default sorting order\n return redirect(url_for('get_tracks', \n sorting_order = 3, \n decade_filter = 'all'))\n \n # Handle an exception if a duplicate YouTube video attempts to get added to the db\n except pymongo.errors.DuplicateKeyError:\n # Feedback to the user something went wrong\n flash('A track already exists with that YouTube link. Try a different track.', 'error')\n \n # Clear the form and go back to add_track\n return redirect('add_track')\n\"\"\" /INSERT TRACK \"\"\" \n\n\"\"\" ADD GENRE PAGE \"\"\"\n# add_genre might not always need a track_id; track_id is only needed if the user is coming to add_genre from editing a track\n@app.route('/add_genre', defaults={'track_id': None})\n@app.route('/add_genre/')\ndef add_genre(track_id):\n \"\"\"\n Takes the user to add-genre.html, allowing them to add a new genre to the genre collection\n \"\"\"\n # Set the html title\n title = \"DesertIsland | Add A New Genre\"\n \n # Establish a session for track_id\n # This is needed in case the user tries to add a genre that already exists\n # When that page gets reloaded after the message telling the user that the genre is duplicated\n # and the user then successfully adds a non-duplicate genre\n # They will get taken to add-track instead of edit-track\n # The session makes sure they go back to edit-track if that's where they need to be\n if track_id:\n session['track_id'] = track_id\n \n # Render the template\n return render_template('add-genre.html', \n track_id = track_id,\n title = title)\n\"\"\" /ADD GENRE PAGE \"\"\"\n\n\"\"\" CANCEL ADD GENRE \"\"\"\n# Pass through track_id if needed, this is so the user goes back to the same track they were editing\n@app.route('/cancel_add_genre', defaults={'track_id': None})\n@app.route('/cancel_add_genre/')\ndef cancel_add_genre(track_id):\n \"\"\"\n Cancels adding a genre, adding nothing to the database\n Take the user back to either add_track or depending on where they were before going to add_genre\n \"\"\"\n # If track_id exists this means the user was editing a track\n if track_id:\n # Take them back to the track they were editing, pass through the required session variables \n return redirect(url_for('edit_track', track_id = track_id, decade_filter = session['decade_filter'], sorting_order = session['sorting_order']))\n # If track_id doesn't exist, the user must be adding a new track\n else:\n # Take them back to add_track\n return redirect(url_for('add_track'))\n\"\"\" /CANCEL ADD GENRE \"\"\"\n \n\"\"\" INSERT GENRE \"\"\"\n# If track_id hasn't been passed through, set a default of None\n@app.route('/insert_genre', defaults={'track_id': None}, methods=['POST']) \n@app.route('/insert_genre/', methods=['POST'])\ndef insert_genre(track_id):\n \"\"\"\n Insert a new genre into the database\n \"\"\"\n genres = mongo.db.genres\n \n inserted_genre = request.form.get('genre')\n \n try:\n genres.insert_one(\n {\n 'genre': inserted_genre\n }\n )\n \n # Feedback to the user the genre was successfully submitted\n flash('Genre added successfully!', 'success')\n \n # There are 2 places the user can be adding a genre from; adding a new track or editing an existing track\n # If track_id has a value, that means the user is editing a track\n if track_id:\n # Take them back to edit-track.html, to the track they were editing before they went to adding a new genre\n # Pass through the session variables that were established by edit_track()\n return redirect(url_for('edit_track', \n track_id = track_id, \n decade_filter = session['decade_filter'], \n sorting_order = session['sorting_order'],\n inserted_genre = inserted_genre))\n \n # track_id may be in session of the user has previously failed to add a genre\n # by attempting to add a duplicate genre\n # In this case, do the same thing as the if block above\n # but get the value for track_id from the session instead\n elif 'track_id' in session:\n return redirect(url_for('edit_track', \n track_id = session['track_id'], \n decade_filter = session['decade_filter'], \n sorting_order = session['sorting_order'],\n inserted_genre = inserted_genre))\n \n # Else the user is currently adding a new track since track_id doesn't exist\n else: \n # In which case, just take them back to add-track.html to allow them to continue adding a track\n return redirect(url_for('add_track',\n inserted_genre = inserted_genre))\n \n # Handle an exception if a duplicate genre attempts to get added to the db\n except pymongo.errors.DuplicateKeyError:\n # Feedback to the user something went wrong\n flash('That genre already exists', 'error')\n \n return redirect(url_for('add_genre'))\n \n\"\"\" /INSERT GENRE \"\"\"\n\n\"\"\" UPVOTE TRACK \"\"\"\n# Tracks can be upvoted from both the charts page and the track-detail page\n# This first route is for a charts page upvote\n@app.route('/upvote_track///', defaults={'track_detail': False}, methods=['POST'])\n# Second route is for a track-detail upvote\n@app.route('/upvote_track////', methods=['POST'])\ndef upvote_track(decade_filter, sorting_order, track_id, track_detail):\n \"\"\" \n Allows the user to upvote a track and saves the new upvote value\n \"\"\"\n tracks = mongo.db.tracks # Get the tracks collection\n \n tracks.update( # Update the collection\n {'_id': ObjectId(track_id)},\n # Increment the value of the upvote key by 1\n {'$inc': { 'upvotes': 1 }}\n )\n \n # Hold pagination, for if a user is upvoting from the charts page\n session['hold_pagination'] = True\n \n # If the user is upvoting from a track_detail page\n if track_detail:\n # Ensure the user stays on the same track-detail page\n return redirect(url_for('track_detail', \n decade_filter = decade_filter, \n sorting_order = sorting_order, \n track_id = track_id))\n \n # Else the user is upvoting from the charts page\n else:\n # Render tracks.html, pass through necessary values to ensure the same decade_filter and sorting_order is set\n # track_scroll_id is used to ensure the page doesn't scroll back to the top\n # when the user clicks upvote\n return redirect(url_for('get_tracks', \n decade_filter = decade_filter, \n sorting_order = sorting_order,\n track_scroll_id = track_id))\n\"\"\" /UPVOTE TRACK \"\"\"\n\n\"\"\" EDIT TRACK PAGE \"\"\"\n@app.route('/edit_track///', defaults={'inserted_genre': None})\n@app.route('/edit_track////')\ndef edit_track(sorting_order, decade_filter, track_id, inserted_genre):\n \"\"\"\n Determines which track the user wants to edit\n Then takes them to edit-track.html\n \"\"\"\n # Grab the track from what was passed through\n the_track = mongo.db.tracks.find_one({\"_id\": ObjectId(track_id)})\n # A list of all the genres is also needed in order to populate the edit form\n all_genres = mongo.db.genres.find()\n \n # Hold pagination, once the user has finished editing they want go back to the 5 tracks they were viewing\n session['hold_pagination'] = True\n \n # Establish sessions for genre_edit in case the user ends up adding a new genre. Create variables that need to be passed back into edit_track once the user has finished adding a genre\n # Session variables are used here because add_genre can be called from both add_track and edit_track\n # If add_genre is called from add_track, default values for sorting_order and decade_filter can be hardcoded and they don't need to be passed through from anywhere\n # Hence, the session variables here are used as \"standby\" variables\n session['sorting_order'] = sorting_order\n session['decade_filter'] = decade_filter\n \n title = \"DesertIsland | Edit Track \" + the_track.get(\"artist\") + \" - \" + the_track.get('track_title') \n \n # Render edit_track.html, pass through necessary variables\n return render_template('edit-track.html',\n title = title,\n decade_filter = decade_filter, \n sorting_order = sorting_order, \n track = the_track, \n genres = all_genres,\n inserted_genre = inserted_genre)\n\"\"\" /EDIT TRACK \"\"\" \n \n\"\"\" INSERT EDITED TRACK \"\"\"\n@app.route('/insert_edited_track///', methods=[\"POST\"])\ndef insert_edited_track(decade_filter, sorting_order, track_id):\n \"\"\"\n Takes the data the user fills out within the form in edit-track.html\n and saves the updated item to the database\n \"\"\"\n # Get the tracks collection\n tracks = mongo.db.tracks\n \n # In order for the edit to work properly, some values that the user should not be eligible to update (e.g. upvotes) need to be retrieved from the the database prior to update\n # If not, update will delete any old key/values that aren't explicitly passed through with the update\n # In order to do this, find() is used to grab a cursor of the track being edited\n old_values = tracks.find({\"_id\": ObjectId(track_id)})\n \n # Loop through the cursor and get the values the user shouldn't be able to change\n # Once tracks.update occurs, any values not specified within the update won't be added to the database\n # That would mean the track would lose its upvotes, date_added, date_added_raw and user_name\n for item in old_values:\n upvotes = item['upvotes']\n date_added = item['date_added']\n date_added_raw = item['date_added_raw']\n user_name = item['user_name']\n \n # Do the update\n tracks.update( {'_id': ObjectId(track_id)},\n {\n 'track_title': request.form.get('track_title'),\n 'artist': request.form.get('artist'),\n 'youtube_link': request.form.get('youtube_link'),\n 'year': int(request.form.get('year')),\n 'genre': request.form.get('genre'),\n 'description': request.form.get('description'),\n # These last four are the same values as what were created when the track was added to the database initially\n # Editing a user name is not an option. It's not desirable for users to steal someone's track upload!\n 'user_name': user_name,\n 'upvotes': upvotes,\n 'date_added': date_added,\n 'date_added_raw': date_added_raw\n })\n \n # Pop the genre_edit_track_id session, the user won't need it again unless they come to editing a track again\n session.pop('genre_edit_track_id', None)\n \n # Feedback to the user the track was successfully edited\n flash('Track edited successfully!', 'success')\n \n # Go back to get_tracks\n return redirect(url_for('get_tracks', \n decade_filter = decade_filter, \n sorting_order = sorting_order))\n\"\"\" /INSERT EDITED TRACK \"\"\" \n \n\"\"\" DELETE TRACK \"\"\"\n@app.route('/delete_track///')\ndef delete_track(decade_filter, sorting_order, track_id):\n \"\"\"\n Takes the user to the delete confirmation page\n \"\"\"\n # Hold pagination so the user is taken back to the same tracks they were viewing \n # (minus the one they just deleted) once they have confirmed deletion\n # This session is technically only needed if the user deletes a track from the charts page\n session['hold_pagination'] = True\n \n # Use ObjectId to parse the track_id in a format acceptable to mongo\n the_track = mongo.db.tracks.find_one({'_id': ObjectId(track_id)})\n \n print(the_track.get('track_title'))\n # # Format the page title\n title = \"DesertIsland | Confirm Deletion of \" + the_track.get('artist') + \" - \" + the_track.get('track_title')\n \n # Render the template\n return render_template('delete-confirm.html', \n track = the_track,\n decade_filter = decade_filter,\n sorting_order = sorting_order,\n title = title)\n \n # # Return the updated list of tracks\n # return redirect(url_for('confirm_delete_track', decade_filter = decade_filter, sorting_order = sorting_order, track_id = track_id))\n\"\"\" /DELETE TRACK \"\"\"\n\n\"\"\" CONFIRM DELETE TRACK \"\"\"\n@app.route('/confirm_delete_track///')\ndef confirm_delete_track(decade_filter, sorting_order, track_id):\n \"\"\"\n Deletes a track from the database\n Then takes the user back to the charts page\n \"\"\"\n # Use ObjectId to parse the track_id in a format acceptable to mongo\n mongo.db.tracks.remove({'_id': ObjectId(track_id)})\n \n # Feedback to the user\n flash('Track deleted!', 'success')\n \n # Go to the charts page\n return redirect(url_for('get_tracks', decade_filter = decade_filter, sorting_order = sorting_order))\n\"\"\" /CONFIRM DELETE TRACK \"\"\"\n\n\"\"\" INITIALISE APP \"\"\"\nif __name__ == '__main__':\n app.run(host=os.environ.get('IP'),\n port=int(os.environ.get('PORT')))\n\"\"\" /INITIALISE APP \"\"\"","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":36341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"3213154","text":"# test_pylint.py - Run pylint in errors-only mode.\n#\n# Copyright (C) 2010, Stefano Rivera \n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\n# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n# PERFORMANCE OF THIS SOFTWARE.\n\nimport subprocess\n\nimport setup\nfrom distro_info_test import unittest\n\nWHITELIST = []\n\nclass PylintTestCase(unittest.TestCase):\n def test_pylint(self):\n \"Test: Run pylint on Python source code\"\n files = ['distro_info.py']\n for script in setup.SCRIPTS:\n f = open(script, 'r')\n if 'python' in f.readline():\n files.append(script)\n f.close()\n cmd = ['pylint', '--rcfile=distro_info_test/pylint.conf', '-E',\n '--include-ids=y', '--'] + files\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, close_fds=True)\n\n out, err = process.communicate()\n if err != '':\n raise unittest.SkipTest('pylint crashed :/')\n\n filtered_out = []\n detected_in = ''\n # pylint: disable=E1103\n for line in out.splitlines():\n # pylint: enable=E1103\n if line.startswith('************* '):\n detected_in = line\n continue\n\n for reg_exp in WHITELIST:\n if reg_exp.search(line):\n break\n else:\n filtered_out.append(detected_in)\n filtered_out.append(line)\n\n self.assertEqual(filtered_out, [],\n \"pylint found errors.\\n\"\n \"Filtered Output:\\n\" + '\\n'.join(filtered_out))\n","sub_path":"usr/lib/python3/dist-packages/distro_info_test/test_pylint.py","file_name":"test_pylint.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69955577","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport os, sys, io\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom typing import List, Union, NoReturn\n\ndef manual_backward(lst_tensor: List[torch.Tensor], lst_gradient: List[Union[torch.Tensor, np.ndarray]]) -> NoReturn:\n assert len(lst_tensor) == len(lst_gradient), \"tensor and gradient length must be identical.\"\n lst_retain_graph = [True]*(len(lst_tensor)-1) + [False]\n for tensor, gradient, retain_graph in zip(lst_tensor, lst_gradient, lst_retain_graph):\n assert tensor.shape == gradient.shape, \"dimension size mismatch detected.\"\n if isinstance(gradient, torch.Tensor):\n v_grad = gradient\n elif isinstance(gradient, np.ndarray):\n v_grad = torch.from_numpy(gradient)\n else:\n raise TypeError(\"invalid gradient type detected.\")\n\n tensor.backward(gradient=v_grad, retain_graph=retain_graph)\n","sub_path":"model/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641163676","text":"import matplotlib.pyplot as plot\nimport numpy as np\nfrom calculadora_imaginarios import *\n\n\ndef finalMatrix(matrix):\n \"\"\"Función que halla la magnitud de una matriz de imaginarios\n (list 2D) -> list 2D\"\"\"\n row, column = len(matrix), len(matrix[0])\n for i in range(row):\n nRow = []\n for j in range(column):\n nRow.append([(modulo(matrix[i][j]) ** 2), 0])\n\n matrix[i] = nRow\n return matrix\n\n\ndef sistemaprobabilisticoquantico(matrix, vectIni, clicks):\n \"\"\"Función que simula un sistema probabilistico cuantico\n (list 2D, list 1D, int) -> list 2D\"\"\"\n if (clicks >= 0) and (type(clicks) is int):\n length = len(vectIni)\n copyMatrix = matrix[:]\n\n for x in range(clicks):\n matrix = multimatriz(matrix, copyMatrix)\n\n return finalMatrix(matrix)\n return -1\n\n\ndef sistemaprobabilistico(matrix, vectIni, clicks):\n \"\"\"Función que simula un sistema probabilistico clasico\n (list 2D, list 1D, int) -> list 1D\"\"\"\n if (clicks >= 0) and (type(clicks) is int):\n length = len(vectIni)\n for x in range(clicks):\n vectIni = accionmatrizvector(matrix, vectIni)\n return vectIni\n return -1\n\n\ndef canicasbooleanas(clicks, booleanMatrix, vectIni):\n \"\"\"Funcion que simula experimento de canicas con coeficientes booleanos\n (int, list 2D boolean, list 1D) -> list 1D\"\"\"\n if (clicks >= 0 and type(clicks) is int):\n for c in range(clicks):\n vectIni = accionvectormatrizboolean(booleanMatrix, vectIni)\n\n return vectIni\n\n\ndef multiplerendijaclasico(matrix, vectIni, clicks):\n \"\"\"Función que simula el experimento de multiples rendijas clasico\n (list 2D, list 1D, int) -> list 2D\"\"\"\n return sistemaprobabilistico(matrix, vectIni, clicks)\n\n\ndef multiplerendijacuantico(matrix, vectIni, clicks):\n \"\"\"Función que simula el experimento de multiples rendijas cuantico\n (list 2D, list 1D, int) -> list 2D\"\"\"\n return sistemaprobabilisticoquantico(matrix, vectIni, clicks)\n\n\ndef grafico(vector):\n \"\"\"Funcion que grafica un diagrama de barras que muestre las probabilidades de un vector de estados. La imagen puede\n guardarse en el computador.\n (list 1D) -> None\"\"\"\n data = len(vector)\n x = np.array([x for x in range(data)])\n y = np.array([round(vector[x][0] * 100, 2) for x in range(data)])\n\n plot.bar(x, y, color='b', align='center')\n plot.title('Probabilidades vector')\n plot.show()","sub_path":"classicalToQuantum.py","file_name":"classicalToQuantum.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"20107777","text":"import os\n\nfrom flask import (\n Flask,\n render_template,\n request,\n redirect,\n url_for,\n flash,\n)\nfrom flask_sqlalchemy import SQLAlchemy # 导入扩展类 SB bug\n\napp = Flask(__name__)\n\napp.config['SECRET_KEY'] = 'dev' # 等同于 app.secret_key = 'dev'\n\napp.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///\" + os.path.join(app.root_path, \"data.db\")\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # 关闭对模型修改的监控\n# 在扩展类实例化前加载配置\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model): # 表名将会是 user(自动生成,小写处理)\n id = db.Column(db.Integer, primary_key=True) # 主键\n name = db.Column(db.String(20)) # 名字\n\n\nclass Book(db.Model):\n id = db.Column(db.Integer, primary_key=True) # 主键\n title = db.Column(db.String(60)) # 书名\n type = db.Column(db.String(20)) # 类型\n\n\n@app.context_processor\ndef inject_user():\n user = User.query.first()\n return dict(user=user)\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n user = User.query.first()\n books = Book.query.all()\n return render_template(\"index.html\", user=user, books=books)\n\n\n\n@app.route(\"/book/add\", methods=[\"POST\"])\ndef add():\n # 获取表单数据\n title = request.form.get('title') # 传入表单对应输入字段的 name 值\n type = request.form.get('type')\n\n # 验证数据\n if not title or not type or len(type) > 4 or len(title) > 60:\n flash('Invalid input.') # 显示错误提示\n return redirect(url_for('index')) # 重定向回主页\n else:\n # 保存表单数据到数据库\n book = Book(title=title, type=type) # 创建记录\n db.session.add(book) # 添加到数据库会话\n db.session.commit() # 提交数据库会话\n flash('Item created.') # 显示成功创建的提示\n\n return redirect(url_for('index')) # 重定向回主页\n\n\n@app.route('/book/edit/', methods=['GET', 'POST'])\ndef edit(book_id):\n book = Book.query.get_or_404(book_id)\n if request.method == 'POST': # 处理编辑表单的提交请求\n title = request.form['title']\n type = request.form['type']\n if not title or not type or len(type) > 4 or len(title) > 60:\n flash('Invalid input.')\n return redirect(url_for('edit', book_id=book_id)) # 重定向回对应的编辑页面\n book.title = title # 更新\n book.type = type\n db.session.commit() # 提交数据库会话\n flash('Item updated.')\n return redirect(url_for('index')) # 重定向回主页\n return render_template('edit.html', book=book) # 传入被编辑的电影记录\n\n\n@app.route('/book/delete/', methods=['POST']) # 限定只接受 POST 请求\ndef delete(book_id):\n book = Book.query.get_or_404(book_id) # 获取电影记录\n db.session.delete(book) # 删除对应的记录\n db.session.commit() # 提交数据库会话\n flash('Item deleted.')\n return redirect(url_for('index')) # 重定向回主页\n\n\nif __name__ == '__main__':\n # debug 模式可以自动加载你对代码的变动, 所以不用重启程序\n # host 参数指定为 '0.0.0.0' 可以让别的机器访问你的代码\n config = dict(\n debug=True,\n host='0.0.0.0',\n port=2000,\n )\n app.run(**config)\n\n\"\"\"\nFlask 微框架\n 请求响应处理 Werkzeug\n 模板渲染 Jinja\n \n flask run 内置服务器运行 \n 比如,司马 \"from werkzeug.serving import run_simple\" \n \n \n \n app = Flask(__name__)\n 实例化 Flask 这个类,创建一个程序对象 app\n \n \n @app.route(\"/\") \n def hello(): \n return \"welcome to My ReadBookList\"\n \n 视图函数\n 解析 url\n 对应的处理函数\n \n 修改 url 规则\n 3 种\n \n 修改视图函数名\n url_for(\"hello\", name=1) /?name=2 \n \n\n\n模板渲染:\n {{ 变量|过滤器 }}\n \n render_template()\n \n\n \n静态文件:\n 生成静态文件 url\n 添加 Favicon\n \n\n数据库:\n Pychar有个小 bug\n \n模板优化:\n 自定义错误页面\n 模板上下文处理函数\n 模板继承 \n\n \n\n\"\"\"\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"616067530","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Driver for ecoli.py\n\nimport os, re, time, subprocess\n\niterModDiv = 1\n\ndirPathList = [\"/home/tomas/documenten/modelling/diatomas_symlink/results/as_low_bridging_seed2\"]\nfor d in dirPathList:\n print(time.strftime('%H:%M:%S ') + d)\n dAbs = d + \"/output\"\n fileList = [files for files in os.listdir(dAbs) if os.path.splitext(files)[-1]=='.mat']\n fileList.sort(reverse=True)\n for f in fileList:\n ###################\n # Optional: skip some files manually\n if int(re.match('g(\\d{4})r(\\d{4}).mat',f).group(2)) != 560:\n continue\n ###################\n print(time.strftime('%H:%M:%S ') + \"\\t\" + f)\n if not int(re.match('g(\\d{4})r(\\d{4}).mat',f).group(2))%iterModDiv == 0:\n # relaxation iteration (YYYY in filename gXXXXrYYYY.mat) % iterModulusDivider == 0\n continue\n fAbs = dAbs + \"/\" + f\n callStr = [\"blender\", \"--background\", \"--python\", \"as_nofil.py\", \"--\", fAbs] # Call string is with filename\n [stdout, _] = subprocess.Popen(callStr, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()\n stdout = stdout.decode()\n if 'Error' in stdout:\n print(\"#####################################\")\n print(stdout)\n print(\"#####################################\")\n","sub_path":"blender/asdriver_nofil.py","file_name":"asdriver_nofil.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"72566863","text":"import numpy as np\nimport pandas as pd\nimport random\n\n\na = []\nmatrix = []\n\nlocList = [\"Surpermarket\", \"Cafe\", \"Restaurant\", \"School\", \"Pharmacy\", \"Theatre\", \"Cinema\"]\n\nfor j in range(len(locList)):\n prob = 1\n a = []\n for i in range(len(locList)):\n if i != len(locList)-1:\n num = 0.16 * (i+1) * np.random.rand()\n indprob = num * prob\n a.append(indprob)\n prob = prob - indprob\n else:\n a.append(prob)\n matrix.append(a)\n\n# print(matrix)\nprobMatrix = pd.DataFrame(matrix, columns = locList, index = locList)\n# print(probMatrix)\nprobMatrix.to_csv(\"probMatrix.csv\")\n# print(probMatrix.loc[station].to_list())\n\nallRoute = []\nrouteLenth = 7\nfor j in range(3):\n for location in locList:\n station = location\n route = []\n route.append(station)\n for i in range(routeLenth-1):\n # print(station)\n probList = probMatrix.loc[station].to_list()\n station = np.random.choice(locList, 1, p=probList)[0]\n route.append(station)\n allRoute.append(route)\n\nroute = pd.DataFrame(allRoute)\nroute.to_csv(\"route.csv\")","sub_path":"generateRouteData.py","file_name":"generateRouteData.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41521854","text":"dx = [1, -1, 0, 0]\ndy = [0, 0, 1, -1]\nEND_OF_WORD = \"#\"\nimport collections\nclass Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n if not board or not board[0]: return []\n if not words: return []\n self.results = set()\n # 构建trie\n root = collections.defaultdict()\n for word in words:\n node = root \n for char in word:\n node = node.setdefault(char, collections.defaultdict())\n node[END_OF_WORD] = END_OF_WORD\n \n self.m, self.n = len(board), len(board[0])\n for i in range(self.m):\n for j in range(self.n):\n if board[i][j] in root:\n self.dfs(board, i, j, \"\", root)\n return list(self.results)\n\n def dfs(self, board, i, j, cur_word, cur_dict):\n cur_word += board[i][j]\n cur_dict = cur_dict[board[i][j]]\n if END_OF_WORD in cur_dict:\n self.results.add(cur_word)\n temp, board[i][j] = board[i][j], \"@\"\n for k in range(4):\n x, y = i + dx[k], j + dy[k]\n if 0 <= x < self.m and 0 <= y < self.n and board[x][y] != \"@\" and board[x][y] in cur_dict:\n self.dfs(board, x, y, cur_word, cur_dict)\n board[i][j] = temp","sub_path":"Week_07/单词搜索2.py","file_name":"单词搜索2.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"261812389","text":"import discord\nimport json\nimport os\nimport requests\nfrom datetime import datetime\nfrom discord.ext import commands, tasks\n\n\nclass Streaming(commands.Cog):\n \"\"\"\n Tools for streaming updates\n \"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n if \"TWITCH_CLIENT_ID\" not in os.environ:\n self.twitch_credentials = None\n return\n elif \"TWITCH_CLIENT_SECRET\" not in os.environ:\n self.twitch_credentials = None\n return\n\n self.twitch_credentials = self.refresh_twitch_credentials()\n self.current_stream = None\n self.message = None\n self.twitch_update.start()\n\n def refresh_twitch_credentials(self):\n \"\"\"\n Refreshes twitch credentials\n\n :return: New twitch credentials\n \"\"\"\n response = requests.post(\n url=\"https://id.twitch.tv/oauth2/token\",\n params={\n \"client_id\": os.environ[\"TWITCH_CLIENT_ID\"],\n \"client_secret\": os.environ[\"TWITCH_CLIENT_SECRET\"],\n \"grant_type\": \"client_credentials\"\n }\n )\n if response.status_code != 200:\n return None\n\n return json.loads(response.content)\n\n @tasks.loop(seconds=120)\n async def twitch_update(self):\n \"\"\"\n Checks for WPI Esports Twitch updates every 2 minutes\n \"\"\"\n twitch_data = json.loads(\n requests.get(\n \"https://api.twitch.tv/helix/streams?user_id=28043034\",\n headers={\n \"client-id\": os.environ[\"TWITCH_CLIENT_ID\"],\n \"Authorization\": f\"Bearer {self.twitch_credentials['access_token']}\"\n }\n ).content\n )[\"data\"]\n\n if len(twitch_data) > 0:\n twitch_data = twitch_data[0]\n await self.bot.change_presence(activity=discord.Streaming(\n name=twitch_data[\"title\"],\n url=\"https://www.twitch.tv/WPIEsports\",\n twitch_name=\"WPIEsports\"\n )\n )\n\n if self.current_stream is None:\n stream_channel = self.bot.get_guild(197532699999731712).get_channel(858354299196669983)\n self.current_stream = discord.Embed(\n title=twitch_data[\"title\"],\n colour=discord.Colour(0x6441a5),\n description=f\"Streaming {twitch_data['game_name']} for {twitch_data['viewer_count']} viewers\\n\"\n f\"[Watch Stream](https://www.twitch.tv/{twitch_data['user_name']})\",\n url=f\"https://www.twitch.tv/{twitch_data['user_name']}\",\n )\n self.current_stream.set_image(url=twitch_data[\"thumbnail_url\"].format(width=\"1920\", height=\"1080\"))\n\n user_data = json.loads(\n requests.get(\n \"https://api.twitch.tv/helix/users?id=28043034\",\n headers={\n \"client-id\": os.environ[\"TWITCH_CLIENT_ID\"],\n \"Authorization\": f\"Bearer {self.twitch_credentials['access_token']}\"\n }\n\n ).content\n )[\"data\"][0]\n\n self.current_stream.set_author(\n name=\"WPI Esports\",\n url=f\"https://www.twitch.tv/{twitch_data['user_name']}\",\n icon_url=user_data[\"profile_image_url\"]\n )\n self.current_stream.timestamp = datetime.utcnow()\n\n self.message = await stream_channel.send(\n \"WPI Esports is now streaming! Check it out <@&858347098691993630>\",\n embed=self.current_stream\n )\n else:\n # Update viewers / game / title / thumbnail\n self.current_stream.title = twitch_data[\"title\"]\n self.current_stream.description = f\"Streaming {twitch_data['game_name']} for \" \\\n f\"{twitch_data['viewer_count']} viewers\\n\" \\\n f\"[Watch Stream](https://www.twitch.tv/{twitch_data['user_name']})\"\n self.current_stream.set_image(url=twitch_data[\"thumbnail_url\"].format(width=\"1920\", height=\"1080\"))\n await self.message.edit(embed=self.current_stream)\n else:\n await self.bot.change_presence(activity=discord.Game(name=\"Valorant\", start=datetime.utcnow()))\n self.current_stream = None\n\n @twitch_update.before_loop\n async def before_twitch_update(self):\n \"\"\"\n Checks to see if credentials loaded properly, if not unloads the cog\n \"\"\"\n await self.bot.wait_until_ready()\n if self.twitch_credentials is None:\n print(\"Unloaded cog Streaming - are your twitch credentials setup properly?\")\n self.bot.unload_extension(\"cogs.Streaming\")\n self.twitch_update.cancel()\n\n\ndef setup(bot):\n bot.add_cog(Streaming(bot))\n","sub_path":"cogs/Streaming.py","file_name":"Streaming.py","file_ext":"py","file_size_in_byte":5055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"210164556","text":"import numpy as np\nimport pandas as pd\nimport xgboost as xgb\nimport datetime\nimport operator\nfrom sklearn.cross_validation import train_test_split\nfrom collections import Counter\nfrom nltk.corpus import stopwords\nimport matplotlib.pyplot as plt\nfrom pylab import plot, show, subplot, specgram, imshow, savefig\n\nimport math \nimport numpy as np\nimport tensorflow as tf\n\nnum_steps = 6001\nRS = 1234\n\nprint(\"Started\")\nnp.random.seed(RS)\ninput_folder = './data/'\n\n# data \ndf_train = pd.read_csv(input_folder + 'train.csv')\ndf_test = pd.read_csv(input_folder + 'test.csv')\nprint(\"Original data: X_train: {}, X_test: {}\".format(df_train.shape, df_test.shape))\n\nx_train_1 = pd.read_csv('xtrain.csv')\ndel x_train_1['Unnamed: 0']\nx_test_1 = pd.read_csv('xtest.csv')\ndel x_test_1['Unnamed: 0']\nprint(\"Feature set 1: X_train: {}, X_test: {}\".format(x_train_1.shape,x_test_1.shape))\n\nx_train_2 = pd.read_csv('xtrain_2.csv') \n#del x_train_2['Unnamed: 0'] \nx_test_2 = pd.read_csv('xtest_2.csv') \n#del x_test_2['Unnamed: 0']\nprint(\"Feature set 2: X_train: {}, X_test: {}\".format(x_train_2.shape, x_test_2.shape))\n\nx_train_3 = pd.read_csv('xtrain_3.csv') \nx_test_3 = pd.read_csv('xtest_3.csv') \nprint(\"Feature set 3: X_train: {}, X_test: {}\".format(x_train_3.shape, x_test_3.shape))\n\ny_train = df_train['is_duplicate'].values\n\nx_train = pd.concat([x_train_1,x_train_2,x_train_3],axis=1)\nx_test = pd.concat([x_test_1,x_test_2,x_test_3],axis=1)\nprint(\"Merge: X_train: {}, X_test: {}\".format(x_train.shape, x_test.shape))\n\nassert x_train.shape[0] == df_train.shape[0]\nassert x_test.shape[0] == df_test.shape[0]\n\n# resample \nif 0: # Now we oversample the negative class - on your own risk of overfitting!\n pos_train = x_train[y_train == 1]\n neg_train = x_train[y_train == 0]\n print(\"Oversampling started for proportion: {}\".format(len(pos_train) / (len(pos_train) + len(neg_train))))\n p = 0.165\n scale = ((len(pos_train) / (len(pos_train) + len(neg_train))) / p) - 1\n while scale > 1:\n neg_train = pd.concat([neg_train, neg_train])\n scale -=1\n neg_train = pd.concat([neg_train, neg_train[:int(scale * len(neg_train))]])\n print(\"Oversampling done, new proportion: {}\".format(len(pos_train) / (len(pos_train) + len(neg_train))))\n x_train = pd.concat([pos_train, neg_train])\n y_train = (np.zeros(len(pos_train)) + 1).tolist() + np.zeros(len(neg_train)).tolist()\n del pos_train, neg_train\n\n#NN \ndef create_nn3_model_and_run(graph,\n train_dataset,\n train_labels,\n valid_dataset,\n valid_labels,\n test_dataset,\n test_labels,\n beta,\n num_steps,\n hidden_size = 24, \n num_labels=2,batch_size = 30000):\n \n uniMax = 1/math.sqrt(hidden_size)\n \n with graph.as_default():\n # Input data. For the training data, we use a placeholder that will be fed\n # at run time with a training minibatch.\n tf_train_dataset = tf.cast(tf.placeholder(tf.float32,shape=(batch_size,train_dataset.shape[1])),tf.float32)\n tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\n\n tf_valid_labels = tf.cast(tf.constant(valid_labels),tf.float32)\n tf_valid_dataset = tf.cast(tf.constant(valid_dataset),tf.float32)\n tf_test_dataset = tf.cast(tf.constant(test_dataset),tf.float32)\n \n # Hidden 1\n weights_1 = tf.cast(tf.Variable(tf.random_uniform([train_dataset.shape[1], hidden_size], minval=-uniMax, maxval=uniMax),name='weights_1'),tf.float32)\n biases_1 = tf.cast(tf.Variable(tf.random_uniform([hidden_size],minval=-uniMax, maxval=uniMax),name='biases_1'),tf.float32)\n hidden_1 = tf.nn.relu(tf.matmul(tf_train_dataset, weights_1) + biases_1)\n \n # Hidden 2\n weights_2 = tf.cast(tf.Variable(tf.random_uniform([hidden_size, hidden_size], minval=-uniMax, maxval=uniMax),name='weights_2'),tf.float32)\n biases_2 = tf.cast(tf.Variable(tf.random_uniform([hidden_size],minval=-uniMax, maxval=uniMax),name='biases_2'),tf.float32)\n hidden_2 = tf.nn.relu(tf.matmul(hidden_1, weights_2) + biases_2)\n \n # Hidden 3\n weights_3 = tf.cast(tf.Variable(tf.random_uniform([hidden_size, hidden_size], minval=-uniMax, maxval=uniMax),name='weights_3'),tf.float32)\n biases_3 = tf.cast(tf.Variable(tf.random_uniform([hidden_size],minval=-uniMax, maxval=uniMax),name='biases_3'),tf.float32)\n hidden_3 = tf.nn.relu(tf.matmul(hidden_2, weights_3) + biases_3)\n\n # Softmax \n weights_4 = tf.cast(tf.Variable(tf.random_uniform([hidden_size, num_labels],minval=-uniMax, maxval=uniMax), name='weights_4'),tf.float32)\n biases_4 = tf.cast(tf.Variable(tf.random_uniform([num_labels],minval=-uniMax, maxval=uniMax),name='biases_4'),tf.float32)\n logits = tf.matmul(hidden_3, weights_4) + biases_4\n\n # \n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=tf_train_labels) )+(1/batch_size)*beta*(tf.nn.l2_loss(weights_1)+tf.nn.l2_loss(weights_2)+tf.nn.l2_loss(weights_3)+tf.nn.l2_loss(weights_4))\n\n\n # Predictions for the training, validation, and test data.\n train_prediction = tf.nn.softmax(logits)\n \n valid_logits = tf.matmul(tf.nn.relu(tf.matmul(tf.nn.relu(tf.matmul(tf.nn.relu(tf.matmul(tf_valid_dataset, weights_1) + biases_1), weights_2) + biases_2),\n weights_3)+biases_3),weights_4)+biases_4\n\n valid_prediction = tf.nn.softmax(valid_logits)\n\n\n test_prediction = tf.nn.softmax(\n tf.matmul(tf.nn.relu(tf.matmul(tf.nn.relu(tf.matmul(tf.nn.relu(tf.matmul(tf_test_dataset, weights_1) + biases_1), weights_2) + biases_2),\n weights_3)+biases_3),weights_4)+biases_4)\n\n loss_valid = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=valid_logits, labels=tf_valid_labels) )+(1/batch_size)*beta*(tf.nn.l2_loss(weights_1)+tf.nn.l2_loss(weights_2)+tf.nn.l2_loss(weights_3)+tf.nn.l2_loss(weights_4))\n\n # Optimizer.\n #global_step = tf.Variable(0) # count the number of steps taken.\n #learning_rate = tf.train.exponential_decay(0.5, global_step, 100000, 0.96, staircase=True)\n #optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)\n optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)\n\n\n test_accuracy = 0\n with tf.Session(graph=graph) as session, tf.device('/gpu:0'):\n# with tf.Session(graph=graph) as session:\n tf.global_variables_initializer().run()\n print(\"Initialized\")\n for step in range(num_steps):\n \n offset = (step * batch_size) % (train_labels.shape[0] - batch_size)\n \n # Generate a minibatch.\n batch_data = train_dataset[offset:(offset + batch_size)]\n batch_labels = train_labels[offset:(offset + batch_size)]\n \n feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\n# _, l = session.run([optimizer, loss], feed_dict=feed_dict)\n \n if (step % 500 == 0): \n _, l,trp,xvp,tep = session.run([optimizer, loss,train_prediction,valid_prediction,test_prediction], feed_dict=feed_dict) \n print(\"Minibatch loss at step %d: %f\" % (step, l))\n print(\"Minibatch valid loss at step %d: %f\" % (step, loss_valid.eval(feed_dict=feed_dict)))\n print(\"Minibatch accuracy: %f\" % accuracy(trp, batch_labels))\n print(trp[0:5])\n print(logits.eval(feed_dict=feed_dict))\n print(weights_1.eval(feed_dict=feed_dict))\n #print(weights_2.eval(feed_dict=feed_dict))\n #print(weights_3.eval(feed_dict=feed_dict))\n print(\"Validation accuracy: %f\" % accuracy(xvp, valid_labels))\n test_accuracy = accuracy(tep, test_labels)\n print(\"Test accuracy: %f\" % test_accuracy)\n print(\"\")\n else:\n _, l = session.run([optimizer, loss], feed_dict=feed_dict) \n return test_accuracy\n\n\nprint(\"Will train NN3 for {} rounds, RandomSeed: {}\".format(num_steps, RS))\nx_train = x_train.fillna(value=0)\nx_test = x_test.fillna(value=0)\n\nx, X_val, ytrain, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=RS)\ny_val = np.array(y_val)\nytrain = np.array(ytrain)\n\ndef reformat(labels,num_labels):\n labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)\n return labels\n\ny_val = reformat(y_val,2)\nytrain = reformat(ytrain,2)\n\nprint(\"*ytrain*\")\nprint(ytrain[0:5])\nprint(\"*y_val*\")\nprint(y_val[0:5])\n\n\n\ndef accuracy(predictions, labels):\n return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))\n / predictions.shape[0])\n\nprint(\"Training data: X_train: {}, Y_train: {}, X_test: {}\".format(x_train.shape, len(y_train), x_test.shape))\nbetas = [0, 0.001,0.01,0.1,1,10]\ntest_accuracy = np.zeros(len(betas))\ni = 0\nfor beta in betas:\n print(\"\\n>>>>>>>>>> Beta: %f%%\" % beta)\n graph = tf.Graph()\n test_accuracy[i] = create_nn3_model_and_run(graph,\n x.as_matrix(),\n ytrain,\n X_val.as_matrix(),\n y_val,\n X_val.as_matrix(),\n y_val,\n beta,\n num_steps)\n \n i = i +1\n\n\n\n# preds = clf.predict(xgb.DMatrix(x_test))\n\n# print(\"Writing output...\")\n# sub = pd.DataFrame()\n# sub['test_id'] = df_test['test_id']\n# sub['is_duplicate'] = preds\n# sub.to_csv(\"xgb_feat_seed_3{}_n{}.csv\".format(RS, ROUNDS), index=False)\n\nprint(\"Done.\")\n","sub_path":"competitions/quora-question-pairs/nn3.py","file_name":"nn3.py","file_ext":"py","file_size_in_byte":9705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405656445","text":"\nfrom .db import User, Transaction\nfrom .error import ModelError\n\ndef deposit(user, data):\n txn = Transaction({\n 'source': 'Paypal',\n 'destination': user._id,\n 'amount': data['credit'],\n 'notes': 'fake',\n })\n user.transactions.append(txn)\n txn.save()\n user.save()\n return txn\n","sub_path":"api-engine/engine/models/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"573043842","text":"from formatprobe.formats import images\n\n#>>> PIL.open('test/data/pgm').format\n#'PPM'\n#>>> PIL.open('test/data/pbm').format\n#'PPM'\n#>>> PIL.open('test/data/ppm').format\n#'PPM'\n\nclass Ppm( images.Image ):\n def probe(self, filename, parent_results):\n \"\"\"Determine if the file is in ppm format.\"\"\"\n if images.check_image_type( filename, ['PPM'] ):\n parent_results['class'] = 'ppm'\n parent_results['ext'] = 'ppm'\n return parent_results\n","sub_path":"formatprobe/formats/ppm.py","file_name":"ppm.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"438061958","text":"\n\n#calss header\nclass _SIGNPOST():\n\tdef __init__(self,): \n\t\tself.name = \"SIGNPOST\"\n\t\tself.definitions = [u'to show the direction of something on a signpost: ', u'to show clearly how something is going to develop: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_signpost.py","file_name":"_signpost.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"18402939","text":"from pyzabbix import ZabbixMetric, ZabbixSender\nfrom os.path import exists\n\n\nconf_pathes = ['c:\\Program Files\\Zabbix Agent\\zabbix_agentd.conf', 'c:\\zabbix\\zabbix_agentd.conf', 'd:\\Zabbix Agent\\zabbix_agentd.conf', 'zabbix_agentd.conf']\n\n\ndef send(result, msg, trap):\n report = ''\n for path in conf_pathes:\n if exists(path):\n with open(path) as f:\n for line in f.readlines():\n if '#' in line:\n continue\n elif 'Hostname' in line:\n hostname = line[line.find('=')+1:].strip()\n break\n break\n else:\n return 'Error: not found zabbix conf-path'\n if not isinstance(msg, list):\n report = msg\n else:\n if result == 'FAILED' or result == 'BALANCE FAILED' or result == 'WARNING':\n for m in msg:\n if 'REQUEST' == m[0] or 'DATA' == m[0] or 'DEBUG' == m[0]:\n continue\n if report:\n report = f'{report}\\n{m[1]}'\n else:\n report = m[1]\n else:\t\t\t\t\t\t\t\t\t\n for m in msg:\n if 'WARNING' == m[0]:\n if report:\n report = f'{report}\\n{m[1]}'\n else:\n report = m[1]\n packet = [ZabbixMetric(hostname, trap, report)]\n result = ZabbixSender(use_config=path).send(packet)\n if result.failed != 0:\n error = f'Zabbix-sender: Error sending {msg}'\n return error","sub_path":"zabbix_sender.py","file_name":"zabbix_sender.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29628211","text":"#!/usr/bin/env python3\n\n\nfrom sklearn import datasets\n\nfrom pmf_estimation_multivariate import pmf_multivariate\nfrom pmf_estimation_feature import pmf_feature\nfrom pmf_joint import pmf_joint\n\nfrom entropy import entropy\nfrom mutual_info import mutual_information\n\n\niris = datasets.load_iris()\ndata_matrix, class_vector = iris.data, iris.target\ndata_matrix_int = (10*data_matrix[:, 0:4]).astype(int) # Discretization of samples as integers\n\n# Computation of joint p.m.f. and unique rows inside the discrete matrix\nunique_rows, pmf = pmf_multivariate(data_matrix_int)\n\n# Computation of p.m.f. of each feature and unique elements inside each feature\nunique_rows_0, pmf_0 = pmf_feature(data_matrix_int, 0)\nunique_rows_1, pmf_1 = pmf_feature(data_matrix_int, 1)\nunique_rows_2, pmf_2 = pmf_feature(data_matrix_int, 2)\nunique_rows_3, pmf_3 = pmf_feature(data_matrix_int, 3)\n\nprint('The p.m.f. of the Sepal Length feature is:\\n',\n pmf_0,\n '\\ncorresponding to the unique values of the feature:\\n',\n unique_rows_0)\n\nprint('\\nThe p.m.f. of the Sepal Width feature is:\\n',\n pmf_1,\n '\\ncorresponding to the unique values of the feature:\\n',\n unique_rows_1)\n\nprint('\\nThe p.m.f. of the Petal Length feature is:\\n',\n pmf_2,\n '\\ncorresponding to the unique values of the feature:\\n',\n unique_rows_2)\n\nprint('\\nThe p.m.f. of the Petal Width feature is:\\n',\n pmf_3,\n '\\ncorresponding to the unique values of the feature:\\n',\n unique_rows_3)\n\nprint('\\nThe joint p.m.f. of the Iris dataset is:\\n',\n pmf,\n '\\ncorresponding to the unique rows:\\n',\n unique_rows)\n\n# Computation of entropies of each feature\nprint('\\nThe entropy of the Sepal Length feature is: ', entropy(pmf_0))\nprint('\\nThe entropy of the Sepal Width feature is: ', entropy(pmf_1))\nprint('\\nThe entropy of the Petal Length feature is: ', entropy(pmf_2))\nprint('\\nThe entropy of the Petal Width feature is: ', entropy(pmf_3))\n\n# Computation of joint entropy\nprint('\\nThe joint entropy of the the Iris dataset is: ', entropy(pmf))\n\n# Computation of joint p.m.f. and unique rows inside the discrete matrix, of all the possible pairs of features\nunique_rows_0_1, pmf_0_1 = pmf_joint(data_matrix_int, 0, 1)\nunique_rows_0_2, pmf_0_2 = pmf_joint(data_matrix_int, 0, 2)\nunique_rows_0_3, pmf_0_3 = pmf_joint(data_matrix_int, 0, 3)\nunique_rows_1_2, pmf_1_2 = pmf_joint(data_matrix_int, 1, 2)\nunique_rows_1_3, pmf_1_3 = pmf_joint(data_matrix_int, 1, 3)\nunique_rows_2_3, pmf_2_3 = pmf_joint(data_matrix_int, 2, 3)\n\nprint('\\nThe mutual information of the Sepal Length and Sepal Width features is: ',\n mutual_information(pmf_0_1, unique_rows_0_1, pmf_0, unique_rows_0, pmf_1, unique_rows_1))\nprint('\\nThe mutual information of the Sepal Length and Petal Length features is: ',\n mutual_information(pmf_0_2, unique_rows_0_2, pmf_0, unique_rows_0, pmf_2, unique_rows_2))\nprint('\\nThe mutual information of the Sepal Length and Petal Width features is: ',\n mutual_information(pmf_0_3, unique_rows_0_3, pmf_0, unique_rows_0, pmf_3, unique_rows_3))\nprint('\\nThe mutual information of the Sepal Width and Petal Length features is: ',\n mutual_information(pmf_1_2, unique_rows_1_2, pmf_1, unique_rows_1, pmf_2, unique_rows_2))\nprint('\\nThe mutual information of the Sepal Width and Petal Width features is: ',\n mutual_information(pmf_1_3, unique_rows_1_3, pmf_1, unique_rows_1, pmf_3, unique_rows_3))\nprint('\\nThe mutual information of the Petal Length and Petal Width features is: ',\n mutual_information(pmf_2_3, unique_rows_2_3, pmf_2, unique_rows_2, pmf_3, unique_rows_3))\n\n\n\n","sub_path":"Iris_pmf.py","file_name":"Iris_pmf.py","file_ext":"py","file_size_in_byte":3611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"88388550","text":"def divideSum(N, digit):\n if digit == 0:\n if N < 20 and N % 2 == 0: return N // 2\n else : return -1\n \n msd = N // (10 ** digit + 1)\n\n tmp = []\n for i in range(msd - 1, msd + 1):\n if i >= 10:\n tmp.append(-1)\n break\n result = divideSum(N - i * (10 ** digit + 1), digit - 1)\n if result != -1:\n tmp.append(i * (10 ** digit) + result)\n\n minValue = N\n for t in tmp:\n if t != -1 and t < minValue: minValue = t\n\n if minValue == N: minValue = -1\n\n return minValue\n \ndef solution(N):\n digit = len(str(N)) - 1\n \n answer = divideSum(N, digit)\n if answer == -1:\n return 0\n else :\n return answer\n\nif __name__ == '__main__':\n N = int(input())\n\n print(solution(N))","sub_path":"1~10000/2231/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"198234923","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\n\nfrom www.transforms import pad_from_trint\n\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n sys.exit(\"usage: ./{} transcript.srt\".format(sys.argv[0]))\n\n transcript = []\n try:\n with open(sys.argv[1], 'r') as file:\n transcript = file.read()\n except IOError as err:\n sys.exit(\"Transcript not readable: {}\").format(err)\n\n print(pad_from_trint(transcript))\n","sub_path":"pad_from_trint.py","file_name":"pad_from_trint.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"620504241","text":"import time, pytest\nimport sys,os\nsys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib')))\nfrom clsCommon import Common\nimport clsTestService\nfrom localSettings import *\nimport localSettings\nfrom utilityTestFunc import *\nimport enums\nfrom selenium.webdriver.common.keys import Keys\n\nclass Test:\n \n #================================================================================================================================\n # @Author: Inbar Willman\n # Test Name : Quiz - Analytics - Export quiz answers - Allow multiple attempts is disabled\n # Test description:\n # Go to editor page and create quiz with all type of questions with no option to retake -> Login with 3 different users and answer the quiz - > Login as admin\n # Go to analytics page -> quiz users tab -> click on export to csv -> Verify that correct users data is displayed\n #================================================================================================================================\n testNum = \"5159\"\n \n supported_platforms = clsTestService.updatePlatforms(testNum)\n \n status = \"Fail\"\n timeout_accured = \"False\"\n driver = None\n common = None\n # Test variables\n description = \"Description\" \n tags = \"Tags,\"\n \n questionNumber1 = ['00:10', enums.QuizQuestionType.Multiple, 'question #1 Title', 'question #1 option #1', 'question #1 option #2', 'question #1 option #3', 'question #1 option #4'] \n questionNumber2 = ['00:15', enums.QuizQuestionType.TRUE_FALSE, 'Question Title for True and False', 'True text', 'False text']\n questionNumber3 = ['00:20', enums.QuizQuestionType.OPEN_QUESTION, 'Question Title for Open-Q'] \n questionNumber4 = ['00:25', enums.QuizQuestionType.REFLECTION, 'Question Title for Reflection Point'] \n dictQuestions = {'1':questionNumber1,'2':questionNumber2,'3':questionNumber3,'4':questionNumber4} \n \n #UserIDs\n userId1 = 'ivq_automation_user_1'\n userId2 = 'ivq_automation_user_2'\n userId3 = 'ivq_automation_user_3'\n \n userNameUser1 = 'QA Member 1'\n userNameUser2 = 'QA Member 2'\n userNameUser3 = 'QA Member 3'\n \n userPass = '123456' \n \n # Questions title\n quizQuestionNumber1 = \"question #1 Title\"\n quizQuestionNumber2 = \"Question Title for True and False\"\n quizQuestionNumber3 = \"Question Title for Open-Q\"\n quizQuestionNumber4 = \"Question Title for Reflection Point\"\n \n # User 1 answer\n user1answerQuestionNumber1 = \"question #1 option #1\"\n user1answerQuestionNumber2 = \"True text\"\n user1answerQuestionNumber3 = \"Open-Q answer QA_Member_1 \"\n \n # User 2 answer\n user2answerQuestionNumber1 = \"question #1 option #1\"\n user2answerQuestionNumber2 = \"False text\"\n user2answerQuestionNumber3 = \"Open-Q answer QA_Member_2\"\n \n # User 3 answer\n user3answerQuestionNumber1 = \"question #1 option #2\"\n user3answerQuestionNumber2 = \"True text\"\n user3answerQuestionNumber3 = \"Open-Q answer QA_Member_3\"\n \n user1AnswersDict ={quizQuestionNumber1:user1answerQuestionNumber1, quizQuestionNumber2:user1answerQuestionNumber2, quizQuestionNumber3:user1answerQuestionNumber3}\n user2AnswersDict ={quizQuestionNumber1:user2answerQuestionNumber1, quizQuestionNumber2:user2answerQuestionNumber2, quizQuestionNumber3:user2answerQuestionNumber3}\n user3AnswersDict ={quizQuestionNumber1:user3answerQuestionNumber1, quizQuestionNumber2:user3answerQuestionNumber2, quizQuestionNumber3:user3answerQuestionNumber3}\n\n #run test as different instances on all the supported platforms\n @pytest.fixture(scope='module',params=supported_platforms)\n def driverFix(self,request):\n return request.param\n \n def test_01(self,driverFix,env):\n\n try:\n logStartTest(self, driverFix)\n ############################# TEST SETUP ###############################\n #capture test start time\n self.startTime = time.time()\n #initialize all the basic vars and start playing\n self,self.driver = clsTestService.initializeAndLoginAsUser(self, driverFix)\n self.common = Common(self.driver)\n self.entryName = clsTestService.addGuidToString(\"Quiz - Analytics - Export quiz questions\", self.testNum)\n self.quizEntryName = clsTestService.addGuidToString(\"Quiz - Analytics - Export quiz questions - Quiz\", self.testNum) \n self.entryPageURL = None\n \n self.filePathEntry = localSettings.LOCAL_SETTINGS_MEDIA_PATH + r'\\videos\\QR_30_sec_new.mp4'\n \n self.filePathQuizUsers = localSettings.LOCAL_SETTINGS_JENKINS_NODE_MEDIA_PATH + '/templates/quiz_users_5159.csv'\n #self.filePathQuizUsers = localSettings.LOCAL_SETTINGS_MEDIA_PATH + '/templates/quiz_users_5159.csv'\n self.filePathExoprtedQuizUsers = localSettings.LOCAL_SETTINGS_JENKINS_NODE_SHARED_DOWNLOAD + \"/quiz_users.csv\"\n \n # Next line is for local running \n #self.filePathExoprtedQuizUsers = 'C:\\\\Users\\\\inbar.willman\\\\eclipse-workspace\\\\kms-automation\\\\web\\\\temp\\\\downloads\\\\quiz_users.csv' \n\n ######################### TEST STEPS - MAIN FLOW #######################\n writeToLog(\"INFO\",\"Step 1: Going to upload entry\") \n if self.common.upload.uploadEntry(self.filePathEntry, self.entryName, self.description, self.tags) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 1: FAILED to upload entry\")\n return\n \n self.common.base.get_body_element().send_keys(Keys.PAGE_DOWN)\n \n writeToLog(\"INFO\",\"Step 2: Going to to navigate to entry page\") \n if self.common.upload.navigateToEntryPageFromUploadPage(self.entryName) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 2: FAILED to navigate entry page\")\n return\n \n writeToLog(\"INFO\",\"Step 3: Going to to wait until media end upload process\") \n if self.common.entryPage.waitTillMediaIsBeingProcessed() == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 3: FAILED to wait until media end upload process\")\n return\n \n writeToLog(\"INFO\",\"Step 4 : Going to create a new Quiz for the \" + self.entryName + \" entry\") \n if self.common.kea.quizCreation(self.entryName, self.dictQuestions, timeout=35) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 4 : FAILED to create a new Quiz for the \" + self.entryName + \" entry\") \n return\n \n self.common.base.switch_to_default_content()\n \n writeToLog(\"INFO\",\"Step 5: Going to get entry page URL\")\n self.entryPageURL = self.common.base.driver.current_url\n \n writeToLog(\"INFO\",\"Step 6: Going to publish entry to unlisted\")\n if self.common.myMedia.publishSingleEntryToUnlistedOrPrivate(self.quizEntryName, enums.ChannelPrivacyType.UNLISTED, publishFrom=enums.Location.MY_MEDIA) == False:\n writeToLog(\"INFO\",\"Step 6: FAILED failed to publish entry to unlisted\")\n return \n \n writeToLog(\"INFO\",\"Step 7 : Going to logout as quiz owner\") \n if self.common.login.logOutOfKMS() == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 7 : FAILED to logout as quiz owner\") \n return \n \n writeToLog(\"INFO\",\"Step 8 : Going to login as \" + self.userNameUser1) \n if self.common.login.loginToKMS(self.userId1, self.userPass) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 8 : FAILED to login as \" + self.userNameUser1) \n return \n \n writeToLog(\"INFO\",\"Step 9: Going to navigate to entry page (by link)\")\n if self.common.base.navigate(self.entryPageURL) == False:\n writeToLog(\"INFO\",\"Step 9: FAILED to navigate to entry page link\")\n return \n \n writeToLog(\"INFO\",\"Step 10 : Going to answer quiz as \" + self.userNameUser1) \n if self.common.player.answerQuiz(self.user1AnswersDict, skipWelcomeScreen=True, submitQuiz=True, location=enums.Location.ENTRY_PAGE, timeOut=3, showScore=False) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 10 : FAILED to answer quiz as \" + self.userNameUser1) \n return \n \n self.common.base.switch_to_default_content()\n \n writeToLog(\"INFO\",\"Step 11 : Going to logout as \" + self.userNameUser1) \n if self.common.login.logOutOfKMS() == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 11 : FAILED to logout as \" + self.userNameUser1) \n return \n \n writeToLog(\"INFO\",\"Step 12 : Going to login as \" + self.userNameUser2) \n if self.common.login.loginToKMS(self.userId2, self.userPass) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 12 : FAILED to login as \" + self.userNameUser2) \n return \n \n writeToLog(\"INFO\",\"Step 13: Going to navigate to entry page (by link)\")\n if self.common.base.navigate(self.entryPageURL) == False:\n writeToLog(\"INFO\",\"Step 13: FAILED to navigate to entry page link\")\n return \n \n writeToLog(\"INFO\",\"Step 14 : Going to answer quiz as \" + self.userNameUser2) \n if self.common.player.answerQuiz(self.user2AnswersDict, skipWelcomeScreen=True, submitQuiz=True, location=enums.Location.ENTRY_PAGE, timeOut=3, showScore=False) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 14 : FAILED to answer quiz as \" + self.userNameUser2) \n return \n \n self.common.base.switch_to_default_content()\n \n writeToLog(\"INFO\",\"Step 15 : Going to logout as \" + self.userNameUser2) \n if self.common.login.logOutOfKMS() == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 15 : FAILED to logout as \" + self.userNameUser2) \n return \n \n writeToLog(\"INFO\",\"Step 16 : Going to login as \" + self.userNameUser3) \n if self.common.login.loginToKMS(self.userId3, self.userPass) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 16 : FAILED to login as \" + self.userNameUser3) \n return \n \n writeToLog(\"INFO\",\"Step 17: Going to navigate to entry page (by link)\")\n if self.common.base.navigate(self.entryPageURL) == False:\n writeToLog(\"INFO\",\"Step 17: FAILED to navigate to entry page link\")\n return \n \n writeToLog(\"INFO\",\"Step 18 : Going to answer quiz as \" + self.userNameUser3) \n if self.common.player.answerQuiz(self.user3AnswersDict, skipWelcomeScreen=True, submitQuiz=True, location=enums.Location.ENTRY_PAGE, timeOut=3, showScore=False) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 18 : FAILED to answer quiz as \" + self.userNameUser3) \n return \n \n self.common.base.switch_to_default_content()\n \n writeToLog(\"INFO\",\"Step 19 : Going to logout as \" + self.userNameUser3) \n if self.common.login.logOutOfKMS() == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 19 : FAILED to logout as \" + self.userNameUser3) \n return \n \n writeToLog(\"INFO\",\"Step 20 : Going to login as quiz owner\") \n if self.common.loginAsUser() == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 20 : FAILED to login as quiz owner\") \n return \n \n writeToLog(\"INFO\",\"Step 21 : Going to export question csv file\") \n if self.common.quizAnalytics.exportCsvFileQuizAnalyticsPage(enums.quizAnalytics.QUIZ_USERS, self.quizEntryName, True) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 21 : FAILED to export question csv file\") \n return\n \n sleep(10)\n \n writeToLog(\"INFO\",\"Step 22 : Going to verify that quiz questions csv files is download correctly\") \n if self.common.compareBetweenTwoCsvFiles(self.filePathExoprtedQuizUsers, self.filePathQuizUsers) == False:\n self.status = \"Fail\"\n writeToLog(\"INFO\",\"Step 22 : FAILED to verify that quiz questions csv files is download correctly\") \n return \n\n ##################################################################\n self.status = \"Pass\"\n writeToLog(\"INFO\",\"TEST PASSED: Verify quiz answers csv file was done successfully\")\n # if an exception happened we need to handle it and fail the test \n except Exception as inst:\n self.status = clsTestService.handleException(self,inst,self.startTime)\n ########################### TEST TEARDOWN ########################### \n def teardown_method(self,method):\n try:\n self.common.handleTestFail(self.status)\n writeToLog(\"INFO\",\"**************** Starting: teardown_method ****************\")\n self.common.myMedia.deleteEntriesFromMyMedia([self.entryName, self.quizEntryName])\n writeToLog(\"INFO\",\"**************** Ended: teardown_method *******************\")\n except:\n pass \n clsTestService.basicTearDown(self)\n #write to log we finished the test\n logFinishedTest(self,self.startTime)\n assert (self.status == \"Pass\") \n\n pytest.main('test_' + testNum + '.py --tb=line')","sub_path":"web/tests/kea/Quiz/test_5159.py","file_name":"test_5159.py","file_ext":"py","file_size_in_byte":14546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"52783759","text":"from datetime import datetime\nimport time\n\nimport googlemaps\n\n#required for using google api\ngmaps = googlemaps.Client(key='AIzaSyChyx38fw6qtO12-FC99wEyK3u9gcgcXj8')\n\n\n\ndef GetAllDistance_Canteen(origins, destinations):\n \n matrix_distance = gmaps.distance_matrix(origins, destinations, mode = 'walking')\n return_list = []\n \n for key in matrix_distance['rows'][0]['elements']:\n tmpObj = [key['distance']['text'],key['duration']['text']]\n return_list.append(tmpObj) #it's a loop, must use append not insert as the first matrix dist will end up as the very last element.\n return return_list\n","sub_path":"ntufoodbot/distance_matrix_gmaps.py","file_name":"distance_matrix_gmaps.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"83639053","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport icekit.validators\nimport django.utils.timezone\nimport fluent_contents.extensions\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('icekit_plugins_image', '0008_auto_20160920_2114'),\n ('icekit', '0006_auto_20150911_0744'),\n ('fluent_pages', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Author',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)),\n ('publishing_is_draft', models.BooleanField(db_index=True, editable=False, default=True)),\n ('publishing_modified_at', models.DateTimeField(editable=False, default=django.utils.timezone.now)),\n ('publishing_published_at', models.DateTimeField(editable=False, null=True)),\n ('given_name', models.CharField(max_length=255)),\n ('family_name', models.CharField(blank=True, max_length=255)),\n ('slug', models.SlugField(max_length=255)),\n ('url', models.CharField(blank=True, validators=[icekit.validators.RelativeURLValidator()], max_length=255, help_text='The URL for the authors website.')),\n ('introduction', fluent_contents.extensions.PluginHtmlField(verbose_name='introduction', help_text='An introduction about the author used on list pages.')),\n ('portrait', models.ForeignKey(blank=True, to='icekit_plugins_image.Image', null=True)),\n ('publishing_linked', models.OneToOneField(to='icekit_authors.Author', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='publishing_draft', editable=False)),\n ],\n options={\n 'ordering': ('family_name', 'given_name'),\n },\n ),\n migrations.CreateModel(\n name='AuthorListing',\n fields=[\n ('urlnode_ptr', models.OneToOneField(to='fluent_pages.UrlNode', primary_key=True, auto_created=True, parent_link=True, serialize=False)),\n ('publishing_is_draft', models.BooleanField(db_index=True, editable=False, default=True)),\n ('publishing_modified_at', models.DateTimeField(editable=False, default=django.utils.timezone.now)),\n ('publishing_published_at', models.DateTimeField(editable=False, null=True)),\n ('layout', models.ForeignKey(blank=True, to='icekit.Layout', null=True, related_name='icekit_authors_authorlisting_related')),\n ('publishing_linked', models.OneToOneField(to='icekit_authors.AuthorListing', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='publishing_draft', editable=False)),\n ],\n options={\n 'verbose_name': 'Author listing',\n 'db_table': 'pagetype_icekit_authors_authorlisting',\n },\n bases=('fluent_pages.htmlpage', models.Model),\n ),\n ]\n","sub_path":"icekit/page_types/author/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"325010188","text":"\n\nfrom xai.brain.wordbase.nouns._westerner import _WESTERNER\n\n#calss header\nclass _WESTERNERS(_WESTERNER, ):\n\tdef __init__(self,): \n\t\t_WESTERNER.__init__(self)\n\t\tself.name = \"WESTERNERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"westerner\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_westerners.py","file_name":"_westerners.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"66636851","text":"from bs4 import BeautifulSoup as bs\nimport requests\n\n\ndef get_html(url):\n response = requests.get(url)\n assert response.status_code == 200\n return response\n\n\ndef get_url_count(html):\n soup = bs(html.text, 'html.parser')\n map_url_list = soup.find_all('loc')\n return len(map_url_list)\n\n\ndef parser(html):\n soup = bs(html.text, 'html.parser')\n map_url_list = soup.find_all('loc')\n count = 0\n for url in map_url_list:\n count += get_url_count(get_html(url.text))\n return count\n\n\ndef main():\n MAIN_URL = 'https://master.shop/sitemap.xml'\n count = parser(get_html(MAIN_URL))\n print(count)\n\n\nif __name__ == '__main__':\n main()","sub_path":"checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"88848912","text":"import matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.transforms as mtransforms\nimport numpy as np\nfrom pathlib import Path\n\nimport torch\nfrom model import Model\nimport argparse\nfrom dataloader import Dataloader\nfrom checkpoints import Checkpoints\nfrom train import Trainer\nfrom pathlib import Path\nimport utils\nimport plugins\nfrom torch.autograd import Variable\nimport numpy as np\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\n\n\nclass Namespace:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass Minirun():\n def __init__(self, nrun=-1):\n self.args = Namespace(\n cuda=True,\n ndf=8,\n nef=8,\n wkld=0.01,\n gbweight=100,\n nlatent=9, \n nechannels=6,\n ngchannels=1,\n resume=\"\",\n save=\"mini-save\",\n loader_train=\"h5py\",\n loader_test=\"h5py\",\n dataset_test=None,\n dataset_train=\"filelist\",\n split_test=0.0,\n split_train=1.0,\n filename_test=\"./data/data.txt\",\n filename_train=\"./data/data.txt\",\n batch_size=64,\n resolution_high=512,\n resolution_wide=512,\n nthreads=32,\n images=\"mini-save/images\",\n pre_name=\"save\",\n )\n latest_save = sorted(list(Path(\"results\").iterdir()))[nrun]\n self.rundate = latest_save.name\n latest_save = latest_save.joinpath(\"Save\")\n latest_save = {\"netG\": latest_save}\n self.args.resume = latest_save\n checkpoints = Checkpoints(self.args)\n\n # Create model\n models = Model(self.args)\n self.model, self.criterion = models.setup(checkpoints)\n\n # Data loading\n self.dataloader = Dataloader(self.args)\n self.loader = self.dataloader.create(flag=\"Test\")\n print(\"\\t\\tBatches:\\t\", len(self.loader))\n\n self.resolution_high = self.args.resolution_high\n self.resolution_wide = self.args.resolution_wide\n self.batch_size = self.args.batch_size\n self.ngchannels = self.args.ngchannels\n self.nechannels = self.args.nechannels\n self.nlatent = self.args.nlatent\n self.composition = torch.FloatTensor(self.batch_size, self.ngchannels, self.resolution_high, self.resolution_wide)\n self.metadata = torch.FloatTensor(self.batch_size, self.nechannels, self.resolution_high, self.resolution_wide)\n\n if self.args.cuda:\n self.composition = self.composition.cuda()\n self.metadata = self.metadata.cuda()\n\n self.composition = Variable(self.composition)\n self.metadata = Variable(self.metadata)\n\n self.imgio = plugins.ImageIO(self.args.images, self.args.pre_name)\n\n def date(self):\n return self.rundate\n\n def getmetadata(self):\n args = self.args\n #args.dataset_train = 'metalist'\n args.dataset_train = 'metadata'\n args.loader_train = 'h5pymeta'\n dataloader = Dataloader(args)\n loader = dataloader.create(flag=\"Test\")\n data_iter = iter(loader)\n i = 0\n input_metadata = []\n while i < len(loader):\n i += 1\n composition, metadata = data_iter.next()\n input_composition.append(data[\"composition\"])\n input_metadata.append(data[\"metadata\"])\n return input_metadata\n\n def mini(self, return_data=True):\n data_iter = iter(self.loader)\n self.model[\"netG\"].eval()\n i = 0\n generated_data = []\n input_data = []\n mydata = []\n while i < len(self.loader):\n i += 1\n composition, metadata = data_iter.next()\n for aa in metadata:\n mydata.append(aa)\n with open('minirun_metadata.txt', \"w\") as f:\n f.write(str(mydata[42]))\n #h1 = [1, 2, 3, 4]\n #for index in h1:\n # f.write(str(mydata[index-1]))\n composition = composition.float()\n batch_size = composition.size(0)\n self.composition.data.resize_(composition.size()).copy_(composition)\n self.metadata.data.resize_(metadata.size()).copy_(metadata)\n\n self.model[\"netG\"].zero_grad()\n\n # run the actual models\n output = self.model[\"netG\"].forward(self.metadata)\n batch_gen = output.data.cpu()\n generated_data.append(batch_gen)\n input_data.append(composition)\n gen_data = torch.cat(generated_data, 0)\n input_data = torch.cat(input_data, 0)\n #print (gen_data.size())\n #print (input_data.size())\n \n #ypred = np.array(gen_data[0])\n #ytest = np.array(input_data[0])\n #ypred = pd.DataFrame([ypred])\n #ytest = pd.DataFrame([ytest])\n print ('----------------------------------------------------')\n #lpred = []\n #for i in ypred:\n # for j in i:\n # for k in j:\n # lpred.append(k)\n # \n #lpred = np.asarray(lpred)\n #ypred = pd.DataFrame([lpred])\n #print (ypred)\n #print ('----------------------------------------------------')\n #ltest = []\n #for i in ytest:\n # for j in i:\n # for k in j:\n # ltest.append(k)\n #ltest = np.asarray(ltest)\n #ytest = ltest\n #print (ytest)\n #print (ytest[0])\n \n # Area fraction calculation for generated image from machine\n values = gen_data[42]\n positive_composition = 0\n negative_composition = 0\n ymodel = []\n for values1 in np.nditer(values):\n if values1 >= 0:\n temp = 1\n else:\n temp = 0\n ymodel.append(temp)\n \n #matrix_percentage = (positive_composition * 100) / 262144\n #ppt_percentage = (negative_composition * 100) / 262144\n #print ('Area fraction analysis for machine generated data')\n #print (matrix_percentage)\n #print (ppt_percentage)\n\n # Area fraction calculation for input image from phase field code\n values = input_data[42]\n positive_composition = 0\n negative_composition = 0\n ytest = []\n\n for values1 in np.nditer(values):\n if values1 >= 0:\n temp = 1\n else:\n temp = 0\n ytest.append(temp)\n\n print ('****************************************************')\n print (ytest)\n print (type(ytest))\n print ('****************************************************')\n print (ymodel)\n print (type(ymodel))\n print ('****************************************************')\n \n fpr, tpr, thresholds = metrics.roc_curve(ytest, ymodel)\n plt.figure(figsize = (12, 10))\n plt.plot(fpr, tpr)\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.0])\n plt.xlabel('False positive rate')\n plt.ylabel('True positive rate')\n plt.show()\n plt.savefig('roc_curve.png')\n\n #matrix_percentage = (positive_composition * 100) / 262144\n #ppt_percentage = (negative_composition * 100) / 262144\n #print ('Area fraction analysis for input data from phase field simulation')\n #print (matrix_percentage)\n #print (ppt_percentage)\n\n \n #with open('gen_data.txt', 'w') as f:\n # f.write(str(gen_data[:1]))\n\n #with open('input_data.txt', 'w') as f:\n # f.write(str(input_data[:1]))\n\n if return_data:\n return gen_data, input_data\n else:\n self.imgio.update({\"input\": input_data, \"sample\": gen_data})\n #self.imgio.save(0, style='magnitude')\n self.imgio.save(0)\n\n accuracy = round(accuracy_score(ytest, ymodel) * 100, 2)\n print (accuracy)\n\nif __name__ == \"__main__\":\n mini = Minirun()\n mini.mini(False)\n","sub_path":"Final_Project/scripts/stat_minirun.py","file_name":"stat_minirun.py","file_ext":"py","file_size_in_byte":8084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"42423466","text":"from __future__ import print_function\r\nfrom sklearn.metrics import classification_report\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom random import sample, randint\r\nimport os\r\nbatch_size = 1000\r\nnum_classes = 10\r\nepochs = 30\r\n\r\n# input image dimensions\r\nimg_rows, img_cols = 32, 32\r\nchannels=3\r\nclass_names = [\"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\", \"dog\", \"frog\", \"horse\", \"ship\", \"truck\"]\r\n\r\n\r\n# the data, split between train and test sets\r\n(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()\r\n\r\nif keras.backend.image_data_format() == 'channels_first':\r\n x_train = x_train.reshape(x_train.shape[0], channels, img_rows, img_cols)\r\n x_test = x_test.reshape(x_test.shape[0], channels, img_rows, img_cols)\r\n input_shape = (channels, img_rows, img_cols)\r\nelse:\r\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, channels)\r\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, channels)\r\n input_shape = (img_rows, img_cols, channels)\r\n\r\nx_train = x_train.astype('float32')\r\nx_test = x_test.astype('float32')\r\nx_train /= 255\r\nx_test /= 255\r\nprint('x_train shape:', x_train.shape)\r\nprint(x_train.shape[0], 'train samples')\r\nprint(x_test.shape[0], 'test samples')\r\n# convert class vectors to binary class matrices\r\ny_train = keras.utils.to_categorical(y_train, num_classes)\r\ny_test = keras.utils.to_categorical(y_test, num_classes)\r\n\r\ndef draw_sample(X, y, rows=4, cols=4, imfile=None, fontsize=12):\r\n for i in range(0, rows*cols):\r\n n=randint(0,x_train.shape[0]-1000)\r\n plt.subplot(rows, cols, i+1)\r\n img = X[n+i].reshape(input_shape)\r\n if not (img.ndim == 2 or img.ndim == 3 and img.shape[-1] in [3, 4]):\r\n img=img.reshape(img_rows,img_cols)\r\n plt.imshow(img, cmap='gray' if channels==1 else \"gnuplot\")\r\n plt.title(\"{}\".format(class_names[np.argmax(y[n+i])]), fontsize=fontsize)\r\n plt.axis('off')\r\n plt.subplots_adjust(wspace=0.6, hspace=0.01)\r\n\r\ndraw_sample(x_train, y_train, 3, 5)\r\nplt.show()\r\nos.system(\"pause\")\r\n\r\nmodel = keras.Sequential(name=\"CIFAR_CNN\")\r\nmodel.add(keras.layers.Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape, padding=\"same\", kernel_constraint=keras.constraints.max_norm(3.)))\r\nmodel.add(keras.layers.Conv2D(64, (3, 3), activation='relu'))\r\nmodel.add(keras.layers.MaxPooling2D(pool_size=(2, 2)))\r\nmodel.add(keras.layers.Dropout(0.25))\r\n\r\nmodel.add(keras.layers.Flatten())\r\nmodel.add(keras.layers.Dense(512, activation='relu'))\r\nmodel.add(keras.layers.Dense(256, activation='relu'))\r\nmodel.add(keras.layers.Dense(128, activation='relu'))\r\nmodel.add(keras.layers.Dropout(0.5))\r\nmodel.add(keras.layers.Dense(num_classes, activation='softmax'))\r\n\r\nmodel.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])\r\nmodel.summary()\r\n\r\n\r\nos.system(\"pause\")\r\n\r\nH=model.fit(x_train, y_train,\r\n batch_size=batch_size,\r\n epochs=epochs,\r\n verbose=1,\r\n validation_data=(x_test, y_test))\r\n\r\nscore = model.evaluate(x_test, y_test, verbose=0)\r\nprint('Test loss:', score[0])\r\nprint('Test accuracy:', score[1])\r\n\r\npredictions = model.predict(x_test)\r\n# show a nicely formatted classification report\r\nprint(\"[INFO] evaluating network...\")\r\nprint(classification_report(y_test.argmax(axis=1), predictions.argmax(axis=1),\r\n target_names=class_names))\r\n\r\n# plot the training loss and accuracy\r\nN = epochs\r\nplt.style.use(\"ggplot\")\r\nplt.figure()\r\nplt.plot(np.arange(0, N), H.history[\"loss\"], label=\"train_loss\")\r\nplt.plot(np.arange(0, N), H.history[\"val_loss\"], label=\"val_loss\")\r\nplt.plot(np.arange(0, N), H.history[\"accuracy\"], label=\"train_acc\")\r\nplt.plot(np.arange(0, N), H.history[\"val_accuracy\"], label=\"val_acc\")\r\nplt.title(\"Training Loss and Accuracy on Dataset\")\r\nplt.xlabel(\"Epoch #\")\r\nplt.ylabel(\"Loss/Accuracy\")\r\nplt.legend(loc=\"lower left\")\r\nplt.show()\r\n\r\ndef plot_image(i, predictions_array, true_label, img):\r\n prediction, true_label, img = predictions_array[i], true_label[i], img[i]\r\n plt.grid(False)\r\n plt.xticks([])\r\n plt.yticks([])\r\n if not (img.ndim == 2 or img.ndim == 3 and img.shape[-1] in [3, 4]):\r\n img=img.reshape(img_rows,img_cols)\r\n plt.imshow(img, cmap=plt.cm.binary)\r\n predicted_label = np.argmax(prediction)\r\n true_label=np.argmax(true_label)\r\n if predicted_label == true_label:\r\n color = 'blue'\r\n else:\r\n color = 'red'\r\n\r\n plt.xlabel(\"{} {:2.0f}% ({})\".format(class_names[predicted_label],\r\n 100 * np.max(prediction),\r\n class_names[true_label]),\r\n color=color)\r\n\r\n\r\ndef plot_value_array(i, predictions_array, true_label):\r\n prediction, true_label = predictions_array[i], true_label[i]\r\n plt.grid(False)\r\n plt.xticks(range(10))\r\n plt.yticks([])\r\n thisplot = plt.bar(range(10), prediction, color=\"#777777\")\r\n plt.ylim([0, 1])\r\n predicted_label = np.argmax(prediction)\r\n true_label = np.argmax(true_label)\r\n thisplot[predicted_label].set_color('red')\r\n thisplot[true_label].set_color('blue')\r\n\r\n\r\n# Plot the first X test images, their predicted labels, and the true labels.\r\n# Color correct predictions in blue and incorrect predictions in red.\r\nnum_rows = 5\r\nnum_cols = 3\r\nnum_images = num_rows * num_cols\r\nplt.figure(figsize=(2 * 2 * num_cols, 2 * num_rows))\r\nindex=0\r\nfor i in sample(range(x_test.shape[0]), num_images):\r\n plt.subplot(num_rows, 2 * num_cols, 2 * index + 1)\r\n plot_image(i, predictions, y_test, x_test)\r\n plt.subplot(num_rows, 2 * num_cols, 2 * index + 2)\r\n plot_value_array(i, predictions, y_test)\r\n index+=1\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\n\r\n\r\n","sub_path":"PythonSource/CIFAR_CNN.py","file_name":"CIFAR_CNN.py","file_ext":"py","file_size_in_byte":5803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251080103","text":"# -*- coding: utf-8 -*-\r\n'''\r\npyplr.plr\r\n=========\r\n\r\nTools for designing pupillometry protocols.\r\n\r\n@author: jtm\r\n\r\n'''\r\n\r\nimport sys\r\nif sys.platform.startswith('win'):\r\n from winsound import Beep\r\n import tkinter as tk\r\n from tkinter import simpledialog\r\n \r\nimport os\r\nimport os.path as op\r\nfrom subprocess import Popen\r\n\r\ndef input_subject_id():\r\n return input('Please enter subject ID: ')\r\n\r\ndef input_subject_id_gui():\r\n ROOT = tk.Tk()\r\n ROOT.withdraw()\r\n return simpledialog.askstring(title='PyPlr Protocol',\r\n prompt='Enter Subject ID: ')\r\n\r\ndef subject_dir(subject_id):\r\n subj_dir = op.join(os.getcwd(), subject_id)\r\n if not op.isdir(subj_dir):\r\n os.mkdir(subj_dir)\r\n return subj_dir\r\n\r\ndef new_record_id(subject_dir):\r\n recording_id = 0\r\n for base, dirs, files in os.walk(subject_dir):\r\n if 'rec' + str(recording_id).zfill(3) == op.basename(base):\r\n recording_id += 1\r\n return 'rec' + str(recording_id).zfill(3)\r\n\r\ndef record_dir(subj_dir):\r\n record_id = new_record_id(subj_dir)\r\n rec_dir = op.join(subj_dir, record_id)\r\n if not op.isdir(subj_dir):\r\n os.mkdir(subj_dir)\r\n if not op.isdir(rec_dir):\r\n os.mkdir(rec_dir)\r\n return rec_dir\r\n\r\ndef open_folder(folder):\r\n Popen(r'explorer /select,{}'.format(folder))\r\n \r\ndef beep_sound():\r\n if sys.platform=='darwin':\r\n print('\\a')\r\n elif sys.platform.startswith('win'):\r\n Beep(440, 200)\r\n \r\n ","sub_path":"build/lib/pyplr/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"424360692","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport requests\nimport json\nfrom bs4 import BeautifulSoup\nimport csv\nimport threading\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\nurl = r\"http://www.80s.tw\"\nde = r\"/movie/list\"\nlists = []\n\ndef getMovieinfo(url):\n movie_info = {}\n resp = requests.get(url)\n soup = BeautifulSoup(resp.content,'html.parser')\n name = soup.find(\"h1\",class_=\"font14w\").get_text()\n movie_info[u\"影片名称\"]=name\n info_list = soup.find(\"div\",class_=\"info\")\n infos = info_list.find(\"div\",class_=\"clearfix\").find_all(\"span\",class_=\"span_block\")\n for info in infos:\n pool = info.find(\"span\").get_text()\n a_list = info.select(\"a\")\n if not a_list:\n ot =info.get_text().encode(\"utf-8\")\n lot = ot.split(\":\")\n movie_info[lot[0].decode(\"utf-8\")]=lot[1].decode(\"utf-8\")\n continue\n a_info = \"\"\n for a in a_list:\n a_info+=a.get_text()+\",\"\n movie_info[pool] = a_info.rstrip(\",\")\n movie_info[u\"种子链接\"] = soup.find(\"span\",class_=\"xunlei dlbutton1\").find('a')['href']\n lists.append(movie_info)\n\ndef getMovielist(page):\n resp = requests.get(url+de+page)\n soup = BeautifulSoup(resp.content,'html.parser')\n h3l = soup.find_all(\"h3\",class_=\"h3\")\n for h3 in h3l:\n hrel = h3.find('a')['href']\n t = threading.Thread(target=getMovieinfo,args=(url+hrel,))\n t.start()\n\ndef ouput():\n FIELDS = [u\"影片名称\",u\"语言\",u\"类型\",u\"上映日期\",u\"地区\",u\"片长\",u\"种子链接\",u\"更新日期\",u\"导演\"]\n csvfile = file('movieinfo.csv', 'wb+')\n writer = csv.writer(csvfile)\n writer.writerow(FIELDS)\n info_list=[]\n for info in lists:\n try:\n infos = (info[u\"影片名称\"],info[u\"语言:\"],info[u\"类型:\"],info[u\"上映日期\"],info.get(u\"地区:\"),info[u\"片长\"],info[u\"种子链接\"],info[u\"更新日期\"],info[u\"导演:\"])\n info_list.append(infos)\n except KeyError:\n continue\n writer.writerows(info_list)\n csvfile.close()\n\ndef main():\n for page in range(1,6):\n getMovielist(\"/-----p%d\" %page)\n ouput()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"y80s.py","file_name":"y80s.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"653307599","text":"import pandas as pd\ndef bse_nse(company):\n if \".BO\" not in company and \".NS\" not in company:\n return \"No Analysis\"\n else:\n if \".BO\" in company:\n upated_name=company.split(\".\")[0]\n dataset=pd.read_csv(\"../StockWeb/StockWeb_F/Equity.csv\")\n dt=dataset.groupby(\"Group\").groups\n group=(dataset[dataset['Security Id']==upated_name][\"Group\"]).values[0]\n indexy=(dataset[dataset['Security Id']==upated_name].index).values[0]\n l=[]\n start=list(dt[group]).index(indexy)+1\n end=list(dt[group]).index(indexy)+6\n if start>=len(list(dt[group])):\n start=False\n else:\n start=list(dt[group]).index(indexy)+1\n if end>=len(list(dt[group])):\n end=len(list(dt[group]))\n else:\n end=list(dt[group]).index(indexy)+6\n if start==False:\n return \"No Recommender\"\n else:\n for i in range(start,end):\n l.append((dataset[dataset.index==list(dt[group])[i]][\"Security Id\"]).values[0]+\".BO\")\n return l\n else:\n dataset=pd.read_excel(\"NSE.xlsx\")\n updated_name=company.split(\".\")[0]\n index=dataset[dataset['Symbol']==updated_name][\"Sr. No.\"]\n start=0\n end=0\n if ((index+1).values[0])>len(dataset):\n start=False\n else:\n start=((index+1).values[0])\n if ((index+6).values[0])>len(dataset):\n end=len(dataset)+1\n else:\n end=((index+6).values[0])\n l=[]\n if start==False:\n return \"No Recommender\"\n else:\n for i in range(start,end):\n l.append((dataset[dataset[\"Sr. No.\"]==i][\"Symbol\"]).values[0]+\".NS\")\n return l","sub_path":"Backend/BSE_NSE_groupby.py","file_name":"BSE_NSE_groupby.py","file_ext":"py","file_size_in_byte":1927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"387839411","text":"#!/usr/local/bin/python3.4\n# -*-coding:Utf-8 -*\nimport os\nimport pickle\n\ndef store_in_file(player_name, file):\n\t\"\"\"Fonction qui permet de récupérer l'objet envoyé en paramètre dans un fichier. Elle vérifie l'existence du fichier et l'existence de l'objet et agit en conséquence\"\"\"\n\t\n\tos.chdir(\"/Users/steph/Documents/workspace/python/le_pendu\")\n\t#Verification de l'existence du fichier. S'il n'existe pas, il est crée avec le nouvel utilisateur. \n\ttry: \n\t\twith open(file, 'rb') as fichier:\n \t\t\tmon_depickler = pickle.Unpickler(fichier)\n \t\t\tuser_list = mon_depickler.load()\n \t\t\tprint(user_list) #debug\n\t\t\n\texcept FileNotFoundError: \n\t\tuser_list=dict()\n\t\tuser_list[player_name] = 0\n\t\t\n\t\twith open(file, 'wb') as fichier:\n\t\t\tmon_pickler = pickle.Pickler(fichier)\n\t\t\tmon_pickler.dump(user_list)\n\t\t\t\n\t#Vérification de l'existence del'utilisateur\n\ttry:\n\t\tprint(\"L'utilisateur {} est déja enregistré, il a {} points\".format(player_name, user_list[player_name]))\n\t\t\n\texcept KeyError: # S'il n'existe pas, on l'ajoute à la liste\n\t\tuser_list[player_name] = 0\n\t\tprint(\"L'utilisateur {} n'existe pas, il sera inséré dans la liste\".format(player_name))\n\n\t\twith open(file, 'wb') as fichier:\n\t\t\tmon_pickler = pickle.Pickler(fichier)\n\t\t\tmon_pickler.dump(user_list)\n\t\t\t\ndef store_score_for_player(player_name, nb_try, file):\n\twith open(file, 'rb') as fichier:\n \t\t\tmon_depickler = pickle.Unpickler(fichier)\n \t\t\tuser_list = mon_depickler.load()\n \t\t\t\n \t\t\tuser_list[player_name] = user_list[player_name] + nb_try\n \t\t\tprint(user_list) #debug\n\n\twith open(file, 'wb') as fichier:\n\t\t\tmon_pickler = pickle.Pickler(fichier)\n\t\t\tmon_pickler.dump(user_list)\n \t\t\t\n\ndef choose_in_dico(dico, key): \n\t\"\"\"Fonction qui renvoie la valeur correspondant à la clé indiquée en parametre\"\"\"\n\treturn dico[key]\n\t\ndef the_game(nb_try, word, player_name):\n\t\"\"\" TBD\"\"\"\n\tfounded_letter = list()\n\ttaille_mot=len(word)\n\tgamer_word=list()\n\ti = 0\n\tprint(founded_letter, taille_mot,gamer_word, i)\t\n\t### A des fins de présentation, au début, on stocke le mot au format caché dans une liste \n\t\n\twhile i0 and word != \"\".join(gamer_word) : \n\t\tlettre=input(\"Choisissez une lettre s'il vous plait :\") \n\t\tfounded_letter.append(lettre)\n\t\tprint(founded_letter) #debug\n\t\tprint(lettre) #debug\n\t\t\n\t\t### Si la lettre est incluse dans le mot, pas de retrait de point\n\t\tcurrent_word=list(word)\n\t\tif list(lettre) == [letter for letter in list(current_word) if letter==lettre]:\n\t\t\tnb_try+=0\n\t\telse:\n\t\t\tnb_try+=-1\n\t\t\n\t\tprint(nb_try) #debug\t\t\t\n\t\t# Affichage du mot en cours\n\t\tif len(founded_letter)>0 : \n\t\t\tfor j, lettre in enumerate(word) : \n\t\t\t\tfor elt in founded_letter:\n\t\t\t\t\tif lettre==elt:\n\t\t\t\t\t\tgamer_word[j]=lettre\n\t\tprint(\"\".join(gamer_word)) #debug\n\t# Fin du game\n\tif word == \"\".join(gamer_word) :\n\t\tprint(\"Bravo, {} vous avez trouvé : \".format(player_name))\n\t\tprint(\"\".join(gamer_word))\n\t\tprint(\"Il vous reste {0} essai(s).\".format(nb_try))\n\telse: \n\t\tprint(\"Désolé, vous avez perdu, vous n'avez plus d'essai\")\n\treturn nb_try\n\t\t","sub_path":"python/previous_attempt/python_2014/le_pendu/fonctions.py","file_name":"fonctions.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"396807207","text":"import turtle\nablak = turtle.Screen()\nSanyi = turtle.Turtle()\nablak.bgcolor(\"lightgreen\")\nSanyi.shape(\"turtle\")\nSanyi.color(\"blue\")\nSanyi.pencolor(\"blue\")\n\nSanyi.stamp\n\nfor ora in range(12):\n \n Sanyi.pendown()\n Sanyi.stamp\n Sanyi.penup()\n Sanyi.forward(60)\n Sanyi.pendown\n Sanyi.forward(20)\n Sanyi.penup()\n Sanyi.forward(20)\n Sanyi.stamp\n Sanyi.backward(100)\n Sanyi.right(30)\n Sanyi.pendown()\n Sanyi.stamp\n\nablak.mainloop()","sub_path":"Rózsahegyi Ákos/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"195551574","text":"import sys\nimport json\nfrom collections import Counter\nimport numpy as np\n\n\ndef load_daily_data(sample_dir, day_id):\n\tout_file_user = sample_dir + 'week_user_' + str(day_id) + '.npy'\n\tout_file_label = sample_dir + 'week_label_' + str(day_id) + '.npy'\n\tout_file_creator = sample_dir + 'week_creator_' + str(day_id) + '.npy'\n\tusers = np.load(out_file_user, allow_pickle=True)\n\tlabels = np.load(out_file_label, allow_pickle=True)\n\tcreators = np.load(out_file_creator, allow_pickle=True)\n\treturn users, labels, creators\n\n\ndef gini(array):\n\t\"\"\"Calculate the Gini coefficient of a numpy array.\"\"\"\n\tarray = array.flatten()\n\tif np.amin(array) < 0:\n\t\tarray -= np.amin(array)\n\tarray += 0.0000001\n\tarray = np.sort(array)\n\tindex = np.arange(1, array.shape[0] + 1)\n\tn = array.shape[0]\n\treturn ((np.sum((2 * index - n - 1) * array)) / (n * np.sum(array)))\n\n\ndef gini_calculate(hit):\n\thit_all = {}\n\tfor i in range(3, day_count):\n\t\tday_id = str(i)\n\t\thit_all[day_id] = []\n\t\tfor j in range(3, i + 1):\n\t\t\tu_day_id = str(j)\n\t\t\thit_all[day_id].extend(hit[u_day_id])\n\n\tgini_index = []\n\tfor i in range(3, day_count):\n\t\tday_id = str(i)\n\t\tu_counter = dict(Counter(hit_all[day_id]))\n\t\ta = np.array(list(u_counter.values()), dtype=np.float64)\n\t\tif sum(a) == 0:\n\t\t\tcontinue\n\t\tgini_index.append(gini(a))\n\t# print(gini(a))\n\treturn gini_index\n\n\ndef result_printing(results):\n\t# from the 3rd day\n\tacc_list = results[\"acc\"][1:]\n\tauc_list = results[\"auc\"][1:]\n\tf1_list = results[\"f1\"][1:]\n\tprecision_list = results[\"precision\"][1:]\n\trecall_list = results[\"recall\"][1:]\n\n\tavgs = {\"acc\": 0, \"auc\": 0, \"f1\": 0, \"precision\": 0, \"recall\": 0}\n\tfor i in range(len(acc_list)):\n\t\tprint(\n\t\t\ti + 3,\n\t\t\tacc_list[i],\n\t\t\tauc_list[i],\n\t\t\tf1_list[i],\n\t\t\tprecision_list[i],\n\t\t\trecall_list[i])\n\tavgs[\"acc\"] = np.array(acc_list).mean(axis=0)\n\tavgs[\"auc\"] = np.array(auc_list).mean(axis=0)\n\tavgs[\"f1\"] = np.array(f1_list).mean(axis=0)\n\tavgs[\"precision\"] = np.array(precision_list).mean(axis=0)\n\tavgs[\"recall\"] = np.array(recall_list).mean(axis=0)\n\tprint(\"average acc:\", avgs[\"acc\"])\n\tprint(\"average auc:\", avgs[\"auc\"])\n\tprint(\"average f1:\", avgs[\"f1\"])\n\tprint(\"average precision:\", avgs[\"precision\"])\n\tprint(\"average recall:\", avgs[\"recall\"])\n\treturn avgs\n\n\ndef main():\n\tf = open(name)\n\td = json.loads(f.read())\n\tprint(\"test:\")\n\tfor key in d[\"avg_test\"]:\n\t\tprint(key, d[\"avg_test\"][key])\n\n\tpred_creator_hit = {}\n\ttrue_creator_hit = {}\n\n\tpred_user_hit = {}\n\ttrue_user_hit = {}\n\tuser_count = []\n\tfor i in range(3, day_count):\n\t\tday_id = str(i)\n\t\tusers, labels, creators = load_daily_data('sean/processed_feed/', day_id)\n\t\tpred_creator_hit[day_id] = []\n\t\ttrue_creator_hit[day_id] = []\n\n\t\tpred_user_hit[day_id] = []\n\t\ttrue_user_hit[day_id] = []\n\t\tfor j in range(len(d[\"prediction\"][day_id])):\n\t\t\tif d[\"prediction\"][day_id][j][0] > 0.5:\n\t\t\t\tpred_creator_hit[day_id].append(creators[j])\n\t\t\t\tpred_user_hit[day_id].append(users[j][0])\n\t\t\tif labels[j][0] > 0.5:\n\t\t\t\ttrue_creator_hit[day_id].append(creators[j])\n\t\t\t\ttrue_user_hit[day_id].append(users[j][0])\n\t\t\t\tuser_count.append(users[j][0])\n\t\t\"\"\"\n\t\tprint \"pred\"\n\t\tdict_u_counter = dict(Counter(pred_user_hit[day_id]))\n\t\tprint OrderedDict(sorted(dict_u_counter.items()))\n\n\t\tprint \"true\"\n\t\tdict_u_counter = dict(Counter(true_user_hit[day_id]))\n\t\tprint OrderedDict(sorted(dict_u_counter.items()))\n\t\tprint\n\t\t\"\"\"\n\n\tprint(\"###############################creator#########################\")\n\tpred_creator_gini_index = gini_calculate(pred_creator_hit)\n\tprint(\"predict_gini:\", np.mean(pred_creator_gini_index))\n\tprint(\"user count:\", len(dict(Counter(user_count))))\n\t\"\"\"\n\ttrue_creator_gini_index = gini_calculate(true_creator_hit)\n\tprint \"true_gini:\", np.mean(true_creator_gini_index)\n\n\tprint \"###############################user############################\"\n\tpred_user_gini_index = gini_calculate(pred_user_hit)\n\tprint \"predict_gini:\", np.mean(pred_user_gini_index)\n\n\ttrue_user_gini_index = gini_calculate(true_user_hit)\n\tprint \"true_gini:\", np.mean(true_user_gini_index)\n\n\t\"\"\"\n\t# result_printing(d[\"test\"])\n\tprint(d[\"param\"])\n\n\nif __name__ == '__main__':\n\tname = sys.argv[1]\n\tday_count = int(sys.argv[2])\n\tmain()\n\n\n","sub_path":"dataset/steemit/es/printing_1.py","file_name":"printing_1.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29500694","text":"#In an N by N square grid, each cell is either empty (0) or blocked (1).\n\n#A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that:\n\n#Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner)\n#C_1 is at location (0, 0) (ie. has value grid[0][0])\n#C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1])\n#If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0).\n#Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.\n\n\n\n#Example 1:\n\n#Input: [[0,1],[1,0]]\n\n\n#Output: 2\n\n#Example 2:\n\n#Input: [[0,0,0],[1,1,0],[1,1,0]]\n\n\n#Output: 4\n\n\n\n#Note:\n\n#1 <= grid.length == grid[0].length <= 100\n#grid[r][c] is 0 or 1\n\nfrom typing import List\nfrom collections import deque\nclass Solution:\n def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:\n if grid[0][0] or grid[-1][-1]:\n return -1\n\n row, col = len(grid), len(grid[0])\n directions = [(1, 0), (1, -1), (1, 1), (0, 1), (0, -1), (0, 0), (-1, 0), (-1, -1), (-1, 1)]\n queue = deque([(0, 0, 1)])\n\n while queue:\n i, j, steps = queue.popleft()\n if i == row - 1 and j == col - 1:\n return steps\n\n for di, dj in directions:\n ni, nj = i+di, j+dj\n if 0 <= ni < row and 0 <= nj < col and not grid[ni][nj]:\n grid[ni][nj] = 1\n queue.append((ni, nj, steps+1))\n return -1\n","sub_path":"python_code/1091_Shortest_Path_in_Binary_Matrix.py","file_name":"1091_Shortest_Path_in_Binary_Matrix.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349972229","text":"import sys\n\nmax_student_count = int(sys.stdin.readline())\n\nscores = []\nfor line in sys.stdin:\n subject_scores = list(map(int, line.strip().split()[-3:]))\n if any(x < 40 for x in subject_scores):\n continue\n scores.append(sum(subject_scores))\n\nif len(scores) <= max_student_count:\n print(0)\nelse:\n scores = sorted(scores, reverse=True)\n max_insufficient_score = scores[max_student_count]\n if scores[0] == max_insufficient_score:\n print(1)\n else:\n for i in range(max_student_count, -1, -1):\n if scores[i] > max_insufficient_score:\n break\n print(scores[i])\n","sub_path":"2018_hse_python_seminars/contest_08/W_score.py","file_name":"W_score.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"322047291","text":"from bs4 import BeautifulSoup\nimport LineConfig\nimport re\nimport requests\nimport sqlite3\nimport datetime\nimport traceback\n\n\ndef check_price():\n try:\n # 取得分析價格\n coolpc_url = 'https://www.coolpc.com.tw/evaluate.php'\n cool = requests.get(coolpc_url)\n soup = BeautifulSoup(cool.text, \"lxml\") # 指定 lxml 作為解析器\n\n # 兩種方式都可以\n # mx_name = soup.find('option',text=re.compile('(?=.*(MX500))(?=.*(500G))',re.I)).text\n mx_name = soup.find('option', text=lambda text: text and all(x in text for x in ['MX500', '500G'])).text\n mx_name_split = mx_name[mx_name.rfind('$') + 1:]\n mx_price = int(re.match(r'\\d+', mx_name_split).group(0))\n\n # 儲存資料\n conn = sqlite3.connect('CoolpcMX500.db')\n\n # 查詢db過往價格,若無資料則新增該筆資訊\n mx500_data = conn.execute(\"SELECT * FROM MX500;\").fetchall()\n today = str(datetime.datetime.now().date())\n if len(mx500_data) == 0:\n sql = str.format('Insert into MX500 (ID,Logdate,Price) values(1,\\'{0}\\',{1})', today, mx_price)\n conn.execute(sql)\n conn.commit()\n conn.close()\n else:\n oldprice = int(mx500_data[0][2])\n olddate = mx500_data[0][1]\n if oldprice != mx_price:\n sql = str.format('Update MX500 set Logdate = \\'{0}\\', Price = {1} where ID=1', today, mx_price)\n conn.execute(sql)\n conn.commit()\n conn.close()\n send_notify(oldprice, olddate, mx_price)\n except Exception as e:\n exception_notify(str(e), traceback.format_exc())\n\n\ndef send_notify(oldprice, olddate, newprice):\n wave = ''\n if (newprice - oldprice) > 0:\n wave = '+$' + str(newprice - oldprice)\n elif (newprice - oldprice) < 0:\n wave = '-$' + str(abs(newprice - oldprice))\n\n # 若有波動,則發送lINE訊息通知\n if wave:\n notify_msg = str.format('\\n\\n ‼️今日價格發生波動 ({0})‼️\\n', wave)\n notify_msg += str.format('\\n上次價格({0}) ${1}', olddate, oldprice)\n notify_msg += str.format('\\n今日價格 ${0}\\n', newprice)\n headers = {\"Authorization\": \"Bearer \" + LineConfig.LINE_NOTIFY_TOKEN}\n params = {\"message\": notify_msg}\n requests.post(LineConfig.LINE_NOTIFY_URL, headers=headers, params=params)\n\n\ndef exception_notify(error_msg, detail=''):\n headers = {\"Authorization\": \"Bearer \" + LineConfig.LINE_NOTIFY_TOKEN}\n params = {\"message\": 'Error ! 運行失敗,原因 : ' + error_msg + '\\n詳細原因:\\n' + detail}\n requests.post(LineConfig.LINE_NOTIFY_URL, headers=headers, params=params)\n\n\ndef exception_notify(error_msg, detail=''):\n headers = {\"Authorization\": \"Bearer \" + LineConfig.LINE_NOTIFY_TOKEN}\n params = {\"message\": 'Error ! 運行失敗,原因 : ' + error_msg + '\\n詳細原因:\\n' + detail}\n requests.post(LineConfig.LINE_NOTIFY_URL, headers=headers, params=params)\n\n\nif __name__ == '__main__':\n check_price()\n","sub_path":"CoolpcMX500Notify.py","file_name":"CoolpcMX500Notify.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529335525","text":"import numpy as np\nimport geatpy as ea\nclass MyProblem(ea.Problem): # Inherited from Problem class.\n def __init__(self, M): # M is the number of objects.\n name = 'DTLZ1' # Problem's name.\n maxormins = [1] * M # All objects are need to be minimized.\n Dim = M + 4 # Set the dimension of decision variables.\n varTypes = [0] * Dim # Set the types of decision variables. 0 means continuous while 1 means discrete.\n lb = [0] * Dim # The lower bound of each decision variable.\n ub = [1] * Dim # The upper bound of each decision variable.\n lbin = [1] * Dim # Whether the lower boundary is included.\n ubin = [1] * Dim # Whether the upper boundary is included.\n # Call the superclass's constructor to complete the instantiation\n ea.Problem.__init__(self, name, M, maxormins, Dim, varTypes, lb, ub, lbin, ubin)\n def aimFunc(self, pop): # Write the aim function here, pop is an object of Population class.\n Vars = pop.Phen # Get the decision variables\n XM = Vars[:,(self.M-1):]\n g = np.array([100 * (self.Dim - self.M + 1 + np.sum(((XM - 0.5)**2 - np.cos(20 * np.pi * (XM - 0.5))), 1))]).T\n ones_metrix = np.ones((Vars.shape[0], 1))\n pop.ObjV = 0.5 * np.fliplr(np.cumprod(np.hstack([ones_metrix, Vars[:,:self.M-1]]), 1)) * np.hstack([ones_metrix, 1 - Vars[:, range(self.M - 2, -1, -1)]]) * np.tile(1 + g, (1, self.M))\n def calReferObjV(self): # Calculate the theoretic global optimal solution here.\n uniformPoint, ans = ea.crtup(self.M, 10000) # create 10000 uniform points.\n realBestObjV = uniformPoint / 2\n return realBestObjV","sub_path":"GA/myproblem.py","file_name":"myproblem.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"148142066","text":"import socket\nHOST= '127.0.0.1'\nPORT= 65432\ns= socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nconn_param= (HOST, PORT)\ns.bind(conn_param)\ns.listen()\nconn, adr= s.accept()\nprint('Connected by', adr)\nwhile True:\n data= conn.recv(1024)\n if not data:\n break\n conn.sendall(data)\n\ns.close()","sub_path":"https.py","file_name":"https.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50776101","text":"import pymysql\n\n# 定义仓库\nrepository = dict()\n# 定义采购药材清单对象\nshop_list = []\nname_id = dict()\ncurrent_list = []\n\n\n# 定义一个函数来初始化药材\ndef init_repository():\n db = pymysql.connect(\"localhost\", \"root\", \"1234\", \"tcmshop\")\n # db = pymysql.connect(\"localhost\", \"root\", \"123456\", \"tcmshop\")\n cursor = db.cursor()\n sql = \"select * from tcm_table\"\n try:\n # 执行SQL语句\n cursor.execute(sql)\n # 获取所有记录列表\n results = cursor.fetchall()\n for row in results:\n id = row[0]\n name = row[1]\n information = row[2]\n priceperkilo = row[3]\n picurl = row[4]\n # 打印结果\n # print(\"id=%s,name=%s,information=%s,price=%s,picurl=%s\" % (id, name, information, priceperkilo, picurl))\n repository[id] = (id, name, priceperkilo)\n name_id[name] = id\n except:\n print(\"Error: unable to fetch data\")\n db.close()\n\n\ndef show_goods():\n print(\"欢迎来到智能中药房\")\n print('中草药清单:')\n print(\"%13s%40s%10s\" % (\"编号\", \"名称\", \"单价\"))\n # 遍历repository的所有value来显示商品清单\n for goods in repository.values():\n print(\"%15s%40s%12s\" % goods)\n\n\n# 显示采购药材清单,就是遍历代表药材清单的list列表\n\n\ndef make_list():\n sum = 0.0\n the_list = []\n print(shop_list)\n for i, item in enumerate(shop_list):\n id = i + 1\n code = item[0]\n name = repository[code][1]\n price = repository[code][2]\n price = round(price, 2)\n number = float(item[1])\n number = round(number, 2)\n amount = price * number\n amount = round(amount, 2)\n sum = sum + amount\n sum = round(sum, 2)\n line = \"%-4s|%8s|%15s|%8s|%6s|%8s\" % \\\n (id, code, name, price, number, amount)\n the_list.append(line)\n the_list.append(\"sum: %8s\" % sum)\n return the_list\n\n\ndef show_list():\n print(\"=\" * 100)\n # 如果清单不为空的时候,输出清单的内容\n if not shop_list:\n print(\"还未购买中药材\")\n else:\n title = \"%-5s|%15s|%40s|%10s|%4s|%10s\" % \\\n (\"ID\", \"编号\", \"名称\", \"单价\", \"重量\", \"小计\")\n print(title)\n print(\"-\" * 100)\n # 记录总计的价钱\n sum = 0.0\n # 遍历代表药材清单的list列表\n for i, item in enumerate(shop_list):\n # 转换id为索引加1\n id = i + 1\n # 获取该购物项的第1个元素:编号\n code = item[0]\n # 获取编号读取中药信息,再获取中药的名称\n name = repository[code][1]\n # 获取编号读取中药信息,再获取中药的单价\n price = repository[code][2]\n # 获取该购物项的第2个元素:药材重量\n number = float(item[1])\n # 小计\n amount = price * number\n # 计算总计\n sum = sum + amount\n line = \"%-5s|%17s|%40s|%12s|%6s|%12s\" % \\\n (id, code, name, price, number, amount)\n print(line)\n print(\"-\" * 100)\n print(\" 总计: \", sum)\n print(\"=\" * 100)\n\n\ndef make_web_list():\n the_list = []\n sum = 0.0\n for i, item in enumerate(shop_list):\n id = i + 1\n code = item[0]\n name = repository[code][1]\n price = repository[code][2]\n price = round(price, 2)\n number = float(item[1])\n number = round(number, 3)\n amount = price * number\n amount = round(amount, 2)\n sum = sum + amount\n sum = round(sum, 2)\n # the_list[i].extend([name, price, amount])\n the_list.append([name, price, number, amount])\n if len(current_list) > 0 and current_list[0][0] == '1000':\n the_list.append(['1000', 0, 0, 0])\n return the_list, sum\n\n\ndef make_web_new():\n the_list = []\n if len(current_list) == 0:\n print('no new chinese medicine')\n return []\n else:\n if current_list[0][0] == '1000':\n the_list.append(['1000', 0, current_list[0][1], 0])\n return the_list\n for i in range(len(current_list)):\n code = current_list[i][0]\n name = repository[code][1]\n price = repository[code][2]\n price = round(price, 2)\n weight = float(current_list[0][1])\n weight = round(weight, 3)\n amount = round(price * weight, 2)\n the_list.append([name, price, weight, amount])\n return the_list\n\n\n# 添加购买中药,就是向代表用户采购药材清单的list列表中添加一项。\ndef add():\n code = input(\"请输入中药编号:\\n\")\n # 没有找到对应的中药,条码错误\n if code not in repository:\n print(\"编号错误,请重新输入\")\n return\n # 根据条码找中药\n goods = repository[code]\n # 等待输入数量\n number = input(\"请输入重量:\\n\")\n # 把中药和购买数量封装成list后加入购物清单\n shop_list.append([code, number])\n\n\ndef add_medicine(id, weight):\n # goods = repository[id]\n # weight = weight\n changed = 0\n for i in range(len(shop_list)):\n if shop_list[i][0] == id:\n edit_weight(id, i, weight)\n changed = 1\n if changed == 0:\n shop_list.append([id, weight])\n # if len(current_list) != 0:\n # current_list.pop(0)\n # current_list.append([id, weight])\n # # print(shop_list)\n\n\ndef add_empty(weight):\n if len(current_list) != 0:\n current_list.pop(0)\n current_list.append(['1000', weight])\n\n\ndef remove_empty(weight):\n if len(current_list) != 0:\n current_list.pop(0)\n current_list.append(['1000', weight])\n\n\ndef edit_weight(id, i, weight):\n oldweight = float(shop_list[i][1])\n shop_list[i][1] = oldweight + float(weight)\n if shop_list[i][1] < 0.02:\n del shop_list[i]\n # if len(current_list) != 0:\n # current_list.pop(0)\n # current_list.append([id, weight])\n\n\ndef remove_medicine(id, weight):\n changed = 0\n # print('shoplist:', shop_list)\n for i in range(len(shop_list)):\n if shop_list[i][0] == id:\n changed = 1\n shop_list[i][1] = float(shop_list[i][1]) + float(weight)\n # if len(current_list) != 0:\n # current_list.pop(0)\n # current_list.append([id, weight])\n if shop_list[i][1] < 0.02:\n del shop_list[i]\n break\n\n if changed == 0:\n print(\"remove error\")\n\n\ndef edit_kind(id, true_kind_id):\n if len(current_list) > 0:\n weight = current_list[0][1]\n else:\n weight = 0\n if id == '1000':\n if weight > 0:\n add_medicine(true_kind_id, weight)\n else:\n remove_medicine(true_kind_id, weight)\n else:\n remove_medicine(id, -weight)\n add_medicine(true_kind_id, weight)\n if len(current_list) != 0:\n for i in range(len(current_list)):\n if id == current_list[i][0]:\n current_list[i] = [true_kind_id, weight]\n break\n new_list = list(set([i[0] for i in current_list]))\n copy_current_list = [i for i in current_list]\n while len(current_list) > 0:\n del current_list[0]\n print('copy_current_list:', copy_current_list)\n for i in range(len(new_list)):\n current_list.append([new_list[i], sum([j[1] for j in copy_current_list if j[0] == new_list[i]])])\n print('current_list.append:', current_list[i])\n\n # if len(current_list) != 0:\n # current_list.pop(0)\n # current_list.append([true_kind_id, weight])\n\n\ndef clear_shoplist():\n while len(shop_list) != 0:\n del shop_list[0]\n while len(current_list) != 0:\n current_list.pop()\n\n\n# 修改购买中药的数量,就是修改代表用户采购药材清单的list列表的元素\ndef edit():\n id = input(\"请输入要修改的采购药材明细项的ID:\\n\")\n # id减1得到购物明细项的索引\n index = int(id) - 1\n # 根据索引获取某个购物明细项\n item = shop_list[index]\n # 提示输入新的购买数量\n number = input(\"请输入新的重量:\\n\")\n # 修改item里面的number\n item[1] = number\n\n\ndef store_order(orderlist):\n id = orderlist[0]\n data = orderlist[1]\n status = orderlist[2]\n price = orderlist[3]\n weight = orderlist[4]\n info = orderlist[5]\n db = pymysql.connect(\"localhost\", \"root\", \"1234\", \"tcmshop\")\n cursor = db.cursor()\n sql = \"insert into order_info(orderid, orderdate, status, price, weights, info) values (%s, %s, %s, %s, %s, %s)\"\n try:\n # 执行SQL语句\n cursor.execute(sql, (id, data, status, price, weight, info))\n # 获取所有记录列表\n # results = cursor.fetchall()\n db.commit() # 提交数据\n cursor.close()\n except:\n print(\"Error: unable to store data\")\n db.close()\n\n\n# 删除购买的中药明细项,就是删除代表用户采购药材清单的list列表的一个元素。\ndef delete():\n id = input(\"请输入要删除采购药材明细项的ID: \")\n index = int(id) - 1\n # 直接根据索引从清单里面删除掉采购药材明细项\n del shop_list[index]\n\n\ndef getshoplist():\n the_list = []\n for i, item in enumerate(shop_list):\n id = item[0]\n # name = repository[code][1]\n # weight = float(item[1])\n the_list.append(id)\n return the_list\n\n\ndef add_list(the_list, weight):\n per_weight = round(float(weight) / len(the_list), 3)\n while len(current_list) != 0:\n current_list.pop(0)\n for i in range(len(the_list)):\n add_medicine(the_list[i], per_weight)\n current_list.append([the_list[i], per_weight])\n\n\ndef remove_list(the_list, weight):\n per_weight = round(float(weight) / len(the_list), 3)\n while len(current_list) != 0:\n current_list.pop(0)\n for i in range(len(the_list)):\n remove_medicine(the_list[i], per_weight)\n current_list.append([the_list[i], per_weight])\n\n\n# cmd_dict = {'a': add, 'e': edit, 'd': delete, 'p': payment, 's': show_goods}\n\n# 显示清单和操作命令提示\nif __name__ == '__main__':\n # init_repository()\n # show_goods()\n # while True:\n # show_list()\n # # show_command()\n # order_info(orderid, orderdate, status, price, weights, info)\n list = ['10001', '20210601', 'success', '58.88', '12.3', 'aiye:7.5']\n # store_order(list)\n","sub_path":"dataprocessing.py","file_name":"dataprocessing.py","file_ext":"py","file_size_in_byte":10616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350625438","text":"from django.conf.urls import url, include\nfrom rest_framework import routers\nfrom rest_framework.authtoken.views import obtain_auth_token\n\nfrom grandchallenge.api.views import (\n ResultViewSet, SubmissionViewSet, JobViewSet, MethodViewSet\n)\n\napp_name = 'api'\n\nrouter = routers.DefaultRouter()\nrouter.register(r'results', ResultViewSet)\nrouter.register(r'submissions', SubmissionViewSet)\nrouter.register(r'jobs', JobViewSet)\nrouter.register(r'methods', MethodViewSet)\nurlpatterns = [\n # Do not namespace the router.urls without updating the view names in\n # evaluation.serializers\n url(r'^v1/', include(router.urls)),\n url(r'^authtoken/', obtain_auth_token, name='obtain-auth-token'),\n url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),\n]\n","sub_path":"app/grandchallenge/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248164101","text":"import dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\n\n#--\ndef PosterSection(title, color, children=[], height=None):\n style = {\"padding-bottom\":\"25px\"}\n if height: style[\"height\"] = height\n layout = dbc.Row(\n dbc.Card([\n dbc.Card([\n html.H4(title,style={\"color\":\"white\",\"text-align\":\"center\",\"font-size\":\"66px\"}),\n ],style={\"background\":color,\"padding\":\"20px\"}),\n dbc.Card(dbc.Container(children,fluid=True),style={\"padding\":\"20px\"})],\n body=True),style=style)\n return layout\n\n#--\ndef PosterColumn(sections):\n layout = dbc.Col(\n dbc.Card(\n sections,\n body=True,\n style={\"padding\":\"45px\"}))\n return layout\n\n#--\ndef Header(title, authors, institutions, logo, banner_color):\n layout = dbc.Card(\n dbc.Row(\n [dbc.Col([dbc.Row(html.Img(src=logo, style={'height':'3.5in', \"width\":\"3.5in\",\"padding-left\":\"100px\"}))],width=1.5),\n dbc.Col([dbc.Row(html.Img(src=\"logo1.png\", style={'height':'1.75in', \"width\":\"5in\",\"padding-left\":\"50px\"})),\n dbc.Row(html.Img(src=\"logo2.png\", style={'height':'1.75in', \"width\":\"5in\", \"padding-left\":\"50px\"}))],width=1.5),\n dbc.Col([\n dbc.Row(dbc.Container(title,fluid=True)),\n dbc.Row(dbc.Container(authors,fluid=True)),\n dbc.Row(dbc.Container(institutions,fluid=True)),\n ],style={\"padding-top\":\"25px\"}),\n dbc.Col(html.Img(src=\"qrcode.png\", style={'height':'4in', \"width\":\"4in\"}),style={\"display\":\"flex\",\"justify-content\":\"flex-end\",\"padding-right\":\"80px\"},width=1.5)],\n style={'height':'4in', \"width\":\"42in\"},justify=\"center\"),\n style={\"background\": banner_color},\n body=True)\n return layout\n\n#-\ndef Poster(title, authors, institutions, logo, columns, bg_color, banner_color):\n layout = html.Div(\n dbc.Col([\n dbc.Row(Header(title, authors, institutions, logo, banner_color), style={\"padding\":\"15px\"}),\n dbc.DropdownMenuItem(divider=True),\n dbc.Row(columns)], style={\"height\": \"32in\"}),\n style={\"background\": bg_color, \"height\": \"36in\", \"width\": \"42in\"})\n\n return layout\n\n#-\nclass iPoster:\n\n #--\n def __init__(self, title, authors_dict, logo, banner_color=\"#0033cc\", text_color=\"white\"):\n self.poster_title = title\n self.authors = authors_dict\n self.logo= logo\n self.bg_color = \"#e6eeff\"\n self.banner_color = banner_color\n self.text_color = text_color\n self.sects = []\n self.cols = []\n self.figure_counter = 0\n\n #--\n def _header_components(self):\n index_dict = dict([(x[1], x[0]+1) for x in enumerate(set(reversed(list(self.authors.values()))))])\n print(index_dict)\n authors = []\n for a in self.authors:\n authors += [a]\n authors += [html.Sup(index_dict[self.authors[a]])]\n authors += [\", \"]\n authors = authors[:-1]\n insts = []\n for s in index_dict:\n insts += [html.Sup(index_dict[s])]\n insts += [s]\n insts += [\", \"]\n insts = insts[:-1]\n title = html.H1(self.poster_title, style={\"text-align\":\"center\",\"font-size\":\"89px\",\"color\":self.text_color})\n authors = html.H2(authors,style={\"text-align\":\"center\",\"font-size\":\"59px\",\"color\":self.text_color})\n institutions = html.H3(insts, style={\"text-align\":\"center\",\"font-size\":\"48px\",\"color\":self.text_color})\n return title, authors, institutions\n\n #--\n def add_section(self, title, text=None, img=None, plot=None, color=\"#0033cc\", height=None, children=[]):\n childs = []\n if text: childs.append(html.P(text, style={\"font-size\":\"34px\"}))\n if img:\n childs.append(html.Img(src=img[\"filename\"], style={\"height\":img[\"height\"], \"width\":img[\"width\"]}))\n self.figure_counter += 1\n childs.append(html.P(\"Figure {}. \".format(self.figure_counter), style={\"font-size\":\"28px\", \"font-weight\":\"bold\"}))\n childs.append(html.P(img[\"caption\"], style={\"font-size\":\"28px\"}))\n if plot:\n childs.append(dcc.Graph(figure=plot[\"fig\"]))\n self.figure_counter += 1\n childs.append(html.P(\"Figure {}. \".format(self.figure_counter), style={\"font-size\":\"28px\", \"font-weight\":\"bold\"}))\n childs.append(html.P(plot[\"caption\"], style={\"font-size\":\"28px\"}))\n\n childs += children\n self.sects.append(PosterSection(title, color, childs, height=height))\n\n #--\n def next_column(self):\n if len(self.sects) > 0:\n self.cols.append(PosterColumn(self.sects))\n self.sects = []\n\n #--\n def compile(self):\n title, authors, institutions = self._header_components()\n return Poster(title, authors, institutions, self.logo, self.cols, self.bg_color, self.banner_color)\n","sub_path":"iposter/iposter.py","file_name":"iposter.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"251727231","text":"from django.shortcuts import render,HttpResponse,redirect\nfrom app01.models import *\n\n# Create your views here.\n\ndef teacher(req):\n teacher_obj = Teacher.objects.all()\n return render(req,'teacher.html',locals())\n\ndef add_teacher(req):\n if req.method == 'GET':\n return render(req,'add_teacher.html')\n if req.method =='POST':\n name = req.POST.get('name',None)\n age = req.POST.get('age',None)\n if name and age:\n Teacher.objects.create(name=name,age=age)\n return redirect('/teacher/')\n else:\n return HttpResponse('缺少字段,返回重试!')\n\n\ndef edit_teacher(req):\n\n if req.method == 'GET':\n tid = req.GET.get('id', None)\n if tid:\n print(tid)\n teacher_obj = Teacher.objects.filter(id=tid).first()\n return render(req,'edit_teacher.html',locals())\n else:\n return redirect('/teacher/')\n elif req.method == 'POST':\n tid = req.POST.get('tid', None)\n tname = req.POST.get('tname')\n tage = req.POST.get('tage')\n # print(tid,tname,tage)\n teacher_obj = Teacher.objects.filter(id=tid)\n # print(teacher_obj)\n teacher_obj.update(name=tname, age=tage)\n return redirect('/teacher/')\n else:\n return HttpResponse('请求错误,返回重试!')\n\ndef del_teacher(req):\n if req.method == 'GET':\n\n tid = req.GET['id']\n if tid:\n Teacher.objects.filter(id=tid).delete()\n return redirect('/teacher/')\n else:\n return redirect('/teacher/')\n elif req.method == 'POST':\n return HttpResponse('Not Suppost!')\n else:\n return redirect('/teacher/')\n\ndef ajax_delteacher(req):\n \n tid = req.GET.get('tid',None)\n if tid:\n msg = '成功'\n try:\n Teacher.objects.filter(id=tid).delete()\n except Exception as e:\n msg = str(e)\n return HttpResponse(msg)\n else:\n return HttpResponse(\"么有tid!\")\n\n\n","sub_path":"day20/django_exercise/app01/views/teacher.py","file_name":"teacher.py","file_ext":"py","file_size_in_byte":2030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"340936493","text":"import socket\nimport threading\n\n\ndef send_message(client):\n global file_path\n while True :\n message = input()\n if(message.startswith(\"/send\")):\n client.send(message.encode())\n file_path = message[6:]\n send_file_event.set()\n else:\n client.send(message.encode())\n\n\ndef recv_message(client):\n global file_name\n while True:\n try:\n message = client.recv(4096)\n if str(message.decode()).startswith(\"/send\"):\n file_name = str(message.decode()[6:]).split('/')[-1]\n raise Exception(\"file received\")\n else:\n print(message.decode('utf-8'))\n except:\n recv_file_event.set()\n\n\ndef send_file(client2):\n while True:\n send_file_event.wait()\n print(\"sending file -> \", file_path)\n f = open(file_path, 'rb')\n data = f.read(4096)\n while (data):\n client2.send(data)\n data = f.read(4096)\n client2.send(\"end\".encode())\n f.close()\n print(\"file sent!\")\n send_file_event.clear()\n\n\ndef recv_file(client2):\n while True:\n recv_file_event.wait()\n print(\"receving file <- \", file_name)\n with open(file_name, 'wb') as q:\n while True:\n data = client2.recv(4096)\n if data.endswith(b'end'):\n q.write(data[:-3])\n break\n q.write(data)\n q.close()\n print(\"file received\")\n recv_file_event.clear()\n\n\ns = socket.socket()\ns2 = socket.socket()\n\nhost = \"172.18.218.33\"\nport = 55565\nport2 = 55566\n\ns.bind((host, port))\ns.listen(5)\ns2.bind((host, port2))\ns2.listen(5)\nclient, addr = s.accept()\nclient2, addr2 = s2.accept()\n\nprint(\"connected to movahed: \", client)\nprint(\"connected to file movahed: \", client2)\n\nsend_file_event = threading.Event()\nrecv_file_event = threading.Event()\n\nrecv_thread = threading.Thread(name=\"recv\", target=recv_message, args=(client,))\nsend_thread = threading.Thread(name=\"send\", target=send_message, args=(client,))\nfile_send_thread = threading.Thread(name=\"filesend\", target=send_file, args=(client2,))\nfile_recv_thread = threading.Thread(name=\"filerecv\", target=recv_file, args=(client2,))\n\nprint(\"starting threads\")\nsend_thread.start()\nrecv_thread.start()\nfile_send_thread.start()\nfile_recv_thread.start()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"35897104","text":"#! /usr/bin/env python\n\nimport os\nimport sys\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy import units as u\nimport time\nfrom nrm_analysis.fringefitting.LG_Model import NRM_Model\nfrom nrm_analysis.misctools import utils # AS LG++\nfrom nrm_analysis.misctools.utils import amisim2mirage\nfrom nrm_analysis import nrm_core, InstrumentData\n\n\nhome = os.path.expanduser('~')\ndatadir = home+\"/gitsrc/ImPlaneIA/notebooks/implaneia_tests/\"\ntr = \"perfect_wpistons_mir\"\ntest_tar = datadir + tr + \".fits\"\noversample=3\nfilt=\"F430M\"\n\nmirexample = os.path.expanduser('~') + \\\n \"/ImplaneIA/notebooks/simulatedpsfs/\" + \\\n \"jw00793001001_01101_00001_nis_cal.fits\" \nmirexample = os.path.expanduser('~') + \\\n \"/gitsrc/ImPlaneIA/example_data/example_niriss/\" + \\\n \"jw00793001001_01101_00001_nis_cal.fits\"\n\n\n\"\"\"\nF480M A0V:\n Total of PSF is: 0.14983928265312782\n Peak pixel is: 0.0023813565623978152\n Central pixel fraction is: 0.015892738674614215\nF430M_A0V:\n Total of PSF is: 0.15029221331182707\n Peak pixel is: 0.0029221329659187313\n Central pixel fraction is: 0.01944300973102229\nF380M_A0V\n Total of PSF is: 0.15064757333183165\n Peak pixel is: 0.0035334896463460517\n Central pixel fraction is: 0.023455337302797623\nF377W_A0V:\n Total of PSF is: 0.1515569249392621\n Peak pixel is: 0.005893341903346654\n Central pixel fraction is: 0.038885335696197766\n\"\"\"\ndef verify_pistons(arg):\n\n \"\"\"\n Create simulated data with pistons,\n 1. analyze the data by calling fit_image\n Do not use fringefitter since the data is perfecrly centered (the if loop).\n Check if input and output pistons match.\n \n 2. analyze the data by calling fit_image via fringefitter\n Fringefitter finds the bestcenter and makes model with bestcenter.\n Since the data is perfecrly centered fringefitter should not affect output pistons.\n Check if input and output pistons match.\n \"\"\"\n \n jw = NRM_Model(mask='jwst',holeshape=\"hex\")\n pixelscale_as=0.0656\n arcsec2rad = u.arcsec.to(u.rad)\n\n jw.set_pixelscale(pixelscale_as*arcsec2rad)\n\n np.random.seed(100)\n\n #lambda/14 ~ 80% strehl ratio\n phi = np.random.normal(0,1.0, 7) / 14.0 # waves\n print(\"phi\", phi, \"varphi\", phi.var(), \"waves\")\n phi = phi - phi.mean()\n\n print(\"phi_nb stdev/w\", phi.std())\n print(\"phi_nb stdev/r\", phi.std()*2*np.pi)\n print(\"phi_nb mean/r\", phi.mean()*2*np.pi)\n pistons = phi *4.3e-6 #OR\n\n print(\"/=====input pistons/m=======/\\n\",pistons)\n print(\"/=====input pistons/r=======/\\n\",pistons*(2*np.pi)/4.3e-6)\n\n jw.set_pistons(pistons)\n jw.simulate(fov=81, bandpass=4.3e-6, over=oversample)\n fits.PrimaryHDU(data=jw.psf).writeto(\"implaneia_tests/perfect_wpistons.fits\",overwrite=True)\n\n if arg == (\"no_fringefitter\"):\n \n jw.make_model(fov=81, bandpass=4.3e-6, over=oversample)\n jw.fit_image(jw.psf, modelin=jw.model)\n\n pos = np.get_printoptions()\n np.set_printoptions(precision=4, formatter={'float': lambda x: '{:+.4e}'.format(x)},\n linewidth=80)\n print(\"Residual/psfpeak array center:\", jw.psf.shape)\n print((jw.residual/jw.psf.max())[36:-36,36:-36])\n np.set_printoptions(pos)\n\n fits.PrimaryHDU(data=jw.residual).writeto(\"residual_pistons_no_ff.fits\",overwrite=True)\n #return jw\n #print(\"output pistons/r\",jw.fringepistons)\n #print(\"output pistons/w\",jw.fringepistons/(2*np.pi))\n #print(\"output pistons/m\",jw.fringepistons*4.3e-6/(2*np.pi))\n #print(\"input pistons/m \",jw.phi) \n \n \n \n elif arg == (\"use_fringefitter\"):\n \n fits.PrimaryHDU(data=jw.psf).writeto(datadir+\"/perfect_wpistons.fits\",overwrite=True)\n \n amisim2mirage( datadir, (\"perfect_wpistons\",), mirexample, filt)\n\n niriss = InstrumentData.NIRISS(filt)\n ff_t = nrm_core.FringeFitter(niriss, datadir=datadir, savedir=datadir, \n oversample=oversample, interactive=False)\n print(test_tar)\n ff_t.fit_fringes(test_tar)\n\n print(\"Residual:\")\n #print(ff_t.nrm.residual)\n print(\"Residual/psfpeak array center:\", ff_t.nrm.reference.shape)\n pos = np.get_printoptions()\n np.set_printoptions(precision=3, formatter={'float': lambda x: '{:+.3e}'.format(x)},\n linewidth=80)\n print((ff_t.nrm.residual/jw.psf.max())[36:-36,36:-36])\n np.set_printoptions(pos)\n\n fits.PrimaryHDU(data=ff_t.nrm.residual).writeto(datadir+\\\n \"/residual_pistons_with_ff.fits\",overwrite=True)\n \n utils.compare_pistons(jw.phi*2*np.pi/4.3e-6, ff_t.nrm.fringepistons, str=\"ff_t\")\n\n #print(\"output pistons/r\",ff_t.nrm.fringepistons)\n #print(\"output pistons/w\",ff_t.nrm.fringepistons/(2*np.pi))\n #print(\"output pistons/m\",ff_t.nrm.fringepistons*4.3e-6/(2*np.pi))\n #print(\"input pistons/m \",jw.phi) \n \n\nif __name__ == \"__main__\":\n\n \n #verify_pistons(\"no_fringefitter\")\n verify_pistons(\"use_fringefitter\")\n","sub_path":"scripts/verify_pistons.py","file_name":"verify_pistons.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"331071063","text":"import pathlib\n\nfrom sklearn.model_selection import train_test_split\n\nfrom . import Dataset\n\n__all__ = [\n 'sklearn_train_test_split',\n 'sklearn_transform',\n]\n\n\ndef sklearn_train_test_split(ds_dict, **split_opts):\n \"\"\"Transformer Function: performs a train/test split.\n\n for each `dset` in ds_dict, this transformer creates two new\n datasets: {dset.name}_test and {dset.name}_train\n\n Parameters\n ----------\n ds_dict:\n input datasets\n **split_opts:\n Remaining options will be passed to `train_test_split`\n\n \"\"\"\n new_ds = {}\n for ds_name, dset in ds_dict.items():\n\n for kind in ['train', 'test']:\n dset_name = f\"{dset_name}_{kind}\"\n dset_meta = {**dset.metadata, 'split':kind, 'split_opts':split_opts}\n new_ds[dset_name] = Dataset(dataset_name=dset_name, metadata=dset_meta)\n X_train, X_test, y_train, y_test = train_test_split(dset.data, dset.target, **split_opts)\n\n new_ds[f'{dset_name}_train'].data = X_train\n new_ds[f'{dset_name}_train'].target = y_train\n new_ds[f'{dset_name}_test'].data = X_test\n new_ds[f'{dset_name}_test'].target = y_test\n return new_ds\n\ndef sklearn_transform(ds_dict, transformer_name, transformer_opts=None, subselect_column=None, **opts):\n \"\"\"\n Wrapper for any 1:1 (data in to data out) sklearn style transformer. Will run the .fit_transform\n method of the transformer on dset.data. If subselect_column is not None, it will treat the data\n like a dataframe and will subselect dset.data[subselect_column] to run the transformer on.\n\n Parameters\n ----------\n ds_dictet:\n Datasets upon which to apply transforms\n transformer_name: string\n sklearn style transformer with a .fit_transform method avaible via sklearn_transformers.\n transformer_opts: dict\n options to pass on to the transformer\n subselect_column: string\n column name for dset.data to run the transformer on\n return_whole: boolean\n return the whole dataframe with a new column named \"transformed\"\n **opts:\n options to pass on to the fit_transform method\n\n Returns\n -------\n Datasets whose data are the result of the transformer.fit_transform\n \"\"\"\n new_dsdict = {}\n for ds_name, dset in ds_dict.items():\n if transformer_name in sklearn_transformers():\n transformer = sklearn_transformers(keys_only=False).get(transformer_name)(**transformer_opts)\n else:\n raise ValueError(f\"Invalid transformer name: {transformer_name}. See sklearn_transformers for available names.\")\n if subselect_column:\n new_data = transformer.fit_transform(dset.data[subselect_column], **opts)\n else:\n new_data = transformer.fit_transform(dset.data, **opts)\n\n new_dsname = f\"{dset.name}_{transformer.__class__.__name__}\"\n new_dsdict[new_dsname] = Dataset(dataset_name=new_dsname, metadata=dset.metadata, data=new_data)\n return new_dsdict\n","sub_path":"{{ cookiecutter.repo_name }}/{{ cookiecutter.module_name }}/data/transformer_functions.py","file_name":"transformer_functions.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"510350501","text":"import mysql.connector\nfrom difflib import get_close_matches\n\ncon = mysql.connector.connect(\nuser = \"ardit700_student\",\npassword = \"ardit700_student\",\nhost = \"108.167.140.122\",\ndatabase = \"ardit700_pm1database\"\n)\n\ncursor = con.cursor()\n\n#word=input(\"Enter the word: \")\n\nquery = cursor.execute(\"SELECT Definition FROM Dictionary\") # WHERE Expression = '%s'\" % word)\nresults = cursor.fetchall()\ndata = dict(results)\nprint(results)\n\ndef translate(w):\n w = w.lower()\n if w in data: \n return data[w]\n elif w.title() in data:\n return data[w.title()]\n elif w.upper() in data: #in case user enters words like USA or NATO\n return data[w.upper()]\n elif len(get_close_matches(w, data.keys())) > 0:\n yn = input(\"Did you mean %s instead? Enter Y if yes, or N if no: \" % get_close_matches(w, data.keys())[0])\n if yn == \"Y\":\n return data[get_close_matches(w, data.keys())[0]]\n elif yn == \"N\":\n return \"The word doesn't exist. Please double check it.\"\n else: \n return \"We didn't understand your entry.\"\n\n else:\n return \"The word doesn't exist. Please double check it.\"\n\nword = input(\"Enter word: \")\n\noutput = translate(word)\n\nif type(output) == list:\n for item in output:\n print(item)\nelse:\n print(output)","sub_path":"Exercise_Python_MySql/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"324357260","text":"from pyspark import SparkContext\nfrom pyspark.mllib.feature import HashingTF\nfrom pyspark.mllib.feature import IDF\nfrom pyspark.mllib.linalg import Vectors\nimport math\nimport codecs\n\nhashingTF = HashingTF(1000000)\n\nclass word:\n\tdef __init__(self, w, idf):\n\t\tself.w = w\n\t\tself.idf = idf\n\tdef __repr__(self):\n\t\treturn repr((self.w, self.idf))\t\n\ndef hashing(word):\t\n\treturn hashingTF.indexOf(word)\n\n#ghi ra file theo ding dang \"idf hash\" dung de tao khong gian vector\ndef writeIdfHash(lst):\t\n\tidf_hash = codecs.open(\"output/idf_hash.txt\", \"wb\", \"utf-8\")\n\tarrayWords = []\n\tfor x in lst:\n\t\tw = word(hashing(x[1]), x[0])\n\t\tarrayWords.append(w)\n\tarrayWordsSort = sorted(arrayWords, key=lambda w:w.w)\n\tfor x in arrayWordsSort:\n\t\tidf_hash.write(\"%.4f %d\\n\" % (x.idf, x.w))\n\tidf_hash.close()\n\n\n#ghi ra file theo dinh dang idf : word : hash dung de theo doi\ndef writeIdfWordHash(lst):\t \n\tidf_word_hash = codecs.open(\"output/idf_word_hash.txt\", \"wb\", \"utf-8\")\n\tfor x in lst:\n\t\tidf_word_hash.write(\"%.4f : %s : %d \\n\" % (x[0], x[1], hashing(x[1]))) \n\tidf_word_hash.close()\n\ndef tf(x):\n\tspl = x.split(' ')\n\treturn set(spl)\n\nsc = SparkContext()\ndocs = sc.textFile(\"hdfs://localhost:8020/reishi/crawler\")\n\nnum = docs.count()\nprint(num)\n#docsCollect = docs.collect()\n#for x in docsCollect:\n#\tprint(x);\n\nwordcounts = docs\\\n\t.map(lambda x: x.replace(',', ' ').replace('.', ' ').replace('-', ' ').lower())\\\n\t.map(lambda x: x.split(':'))\\\n\t.flatMap(lambda x: set(x[1].split(' ')))\\\n\t.map(lambda x: (x, 1))\\\n\t.reduceByKey(lambda a, b:b+a)\\\n\t.filter(lambda x: x[1] > (0.001 * num))\\\n\t.map(lambda x: (math.log(num/(float(x[1])), 2), x[0])).sortByKey(True)\n\t\n\t#.reduceByKey(lambda x, y:math.log(num/(y+1), 2))\\\n\t#.map(lambda x:(x[1], x[0])).sortByKey(False)\n\nlst = wordcounts.take(1000000)\n\nwriteIdfHash(lst)\nwriteIdfWordHash(lst)","sub_path":"reishi_batch/pyspark/idf_manual.py","file_name":"idf_manual.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"127829419","text":"import sqlite3\nimport os\nimport sys\nimport config\n\nclass Connection(object):\n def __init__(self, tests=False):\n if tests:\n db_file = config.get('database_tests')\n else:\n db_file = config.get('database')\n \n file = './%s' % db_file\n \n try:\n self.conn = sqlite3.connect(file)\n \n if self.conn is None:\n print('Connection is closed')\n except Exception as err:\n print('Connection failed.: %s' % err)\n \n def close(self):\n if self.conn:\n self.conn.close()\n \n def cursor(self):\n return self.conn.cursor()\n \n def commit(self):\n self.conn.commit()\n self.cursor().close()","sub_path":"app/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"104407349","text":"from keras.datasets import imdb\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import *\nfrom keras.layers import *\nimport numpy as np\nimport os\n\ntop_words = 10000\n(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=top_words)\n\ntemp_word_to_idx = imdb.get_word_index()\nidx_to_word = {}\nword_to_idx = {}\n\nfor key, value in imdb.get_word_index().items():\n\tword_to_idx[key] = value+3\n\nfor key, value in word_to_idx.items():\n\tidx_to_word[value] = key\n\nidx_to_word[0] = ''\nidx_to_word[1] = ''\nidx_to_word[2] = ''\n\nreview = \"\"\nfor token in x_train[0]:\n\treview = review + idx_to_word[token] + \" \"\n\nprint(\"Sample Review \" + review)\n\nfor i in range(x_train.shape[0]):\n\tx_train[i] = np.asarray(x_train[i])\n\nfor i in range(x_test.shape[0]):\n\tx_test[i] = np.asarray(x_test[i])\n\nx_train_pad = pad_sequences(x_train, maxlen=600,\n padding='pre', truncating='pre')\n\nx_test_pad = pad_sequences(x_test, maxlen=600,\n padding='pre', truncating='pre')\n\nembeddings_index = {}\nf = open(os.path.join('Glove_embedding/glove.6B.100d.txt'))\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\nf.close()\n\nembedding_matrix = np.zeros((len(word_to_idx) + 1, 100))\nfor word, i in word_to_idx.items():\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n\ninput = Input(shape = (600,))\nembedding_layer = Embedding(len(word_to_idx)+1, 100, weights = [embedding_matrix], input_length = 600, \n\t\t\t\t\t\t\ttrainable = False)\nGRU_1 = GRU(units = 16, name = \"GRU_1\", return_sequences = True)\nGRU_2 = GRU(units = 8, name = \"GRU_2\", return_sequences = True)\nGRU_3 = GRU(units = 4, name = \"GRU_3\", return_sequences = False)\ndense_1 = Dense(units = 1, activation = 'sigmoid', name = \"DENSE\")\n\nfirst_layer = embedding_layer(input)\nsecond_layer = GRU_1(first_layer)\nthird_layer = GRU_2(second_layer)\nfourth_layer = GRU_3(third_layer)\nfifth_layer = dense_1(fourth_layer)\n\nmodel = Model(input, fifth_layer)\nmodel.compile('adam', 'binary_crossentropy', metrics = ['accuracy'])\nmodel.fit(x_train_pad, y_train, epochs = 50, batch_size = 128, verbose = 1, validation_data = (x_test_pad, y_test))\n\nmodel.evaluate(x_test, y_test, verbose = 0)\n\n","sub_path":"IMDB/imdb.py","file_name":"imdb.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"197463404","text":"# python select io多路复用测试代码\n# 1. 简单的使用select来进行客户端多连接\n\nimport select\nimport socket\nimport time\n\n# select 把socket放入 select中,然后每当有一个连接过来,把连接conn放入select模型里面去\nport = 19864\nip = \"127.0.0.1\"\nss = socket.socket()\nss.bind((ip, port))\nss.listen(10)\nread_list = [ss]\nwrite_list = []\nmsg_list = dict()\nwhile 1:\n rlist, wlist, xlist = select.select(read_list, write_list, [], 1)\n for i in rlist:\n if i is ss:\n # 如果ss准备就绪,那么说明ss就可以接受连接了,当ss接受到连接\n # 那么把连接返回readlist\n conn, addr = i.accept()\n read_list.append(conn)\n # 如果不是socket对象,那么就是conn连接对象了,如果是conn连接对象,那么就代表有\n # 读入数据的变化,对应recv方法\n else:\n try:\n data = i.recv(1024)\n # 如果接受不到数据了 则说明连接已经关闭了\n if not data:\n print('connecting close')\n read_list.remove(i)\n break\n # 我们去发送数据,但是我们要把conn准备好了再去发送\n # 所以首先把数据存在一个dict中msg_list,然后再等他准备好的时候\n # 再去发送\n msg_list[i] = [data]\n if i not in write_list:\n write_list.append(i)\n except Exception:\n read_list.remove(i)\n\n for j in wlist:\n # 把对应各自的消息取出来\n msg = msg_list[j].pop()\n try:\n j.send(msg)\n # 回复完成后,一定要将outputs中该socket对象移除\n write_list.remove(j)\n except Exception:\n # 如果报错就所以连接或者已经断开了,那么我们就把他移出出去\n write_list.remove(j)\n","sub_path":"rimi_linux_mysql/tcp_ip_socket/Io_test/io_select_test/server2.py","file_name":"server2.py","file_ext":"py","file_size_in_byte":1960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"34832669","text":"import json\n\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_api.serializers import *\nfrom rest_api.models import *\n\n\n# Create your views here.\n\n@api_view(['GET'])\ndef get_tag(request, id):\n try:\n tag = Tag.objects.get(id=id)\n except Tag.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = TagSerializer(tag)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_tags(request):\n tags = Tag.objects.filter(is_popular=True)\n if 'is_popular' in request.GET:\n is_popular = eval(request.GET['is_popular'].capitalize())\n tags = tags.filter(is_popular=is_popular)\n if 'num' in request.GET:\n num = int(request.GET['num'])\n tags = tags[:num]\n serializer = TagSerializer(tags, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_article(request):\n try:\n if 'id' in request.GET:\n id = int(request.GET['id'])\n article = Article.objects.get(id=id)\n article.times_viewed += 1\n article.save()\n elif 'name' in request.GET:\n article = Article.objects.get(name=request.GET['name'])\n else:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n except Article.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = ArticleReadSerializer(article)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_articles(request):\n articles = Article.objects.filter(name__iregex=r'\\b.*[a-zA-Z]+.*\\b')\n if 'max_price' in request.GET:\n articles = articles.filter(total_price__lte=request.GET['max_price'])\n if 'min_price' in request.GET:\n articles = articles.filter(total_price__gte=request.GET['min_price'])\n if 'tags' in request.GET:\n tags = request.GET['tags'].split(',') # Tag filter example: ws/articles?tags=New,Blizzard\n articles = articles.filter(tag__name__in=tags).distinct()\n if 'seller' in request.GET:\n articles = articles.filter(seller_id=request.GET['seller'])\n if 'buyer' in request.GET:\n articles = articles.filter(buyer=request.GET['buyer'])\n if 'is_sold' in request.GET:\n is_sold = eval(request.GET['is_sold'].capitalize())\n articles = articles.filter(is_sold=is_sold)\n if 'shop_cart' in request.GET:\n print(articles)\n articles = articles.filter(shop_cart__in=[int(request.GET['shop_cart'])])\n print(articles)\n if 'saved' in request.GET:\n articles = articles.filter(saved__in=[int(request.GET['saved'])])\n if 'name' in request.GET:\n articles = articles.filter(name__contains=request.GET['name'])\n if 'times_viewed' in request.GET:\n articles = articles.order_by('-times_viewed')\n if 'condition' in request.GET:\n articles = articles.filter(items_in_article__condition=request.GET['condition']).distinct()\n if 'type' in request.GET:\n if request.GET['type'] == 'games':\n articles = [a for a in articles if Game.objects.filter(pertaining_article=a.id).exists()]\n elif request.GET['type'] == 'consoles':\n articles = [a for a in articles if Console.objects.filter(pertaining_article=a.id).exists()]\n if 'platform' in request.GET:\n articles = [a for a in articles if Game.objects.filter(\n pertaining_article=a.id, platform=request.GET['platform']).exists()]\n if 'num' in request.GET:\n num = int(request.GET['num'])\n articles = articles[:num]\n serializer = ArticleReadSerializer(articles, many=True)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef create_article(request):\n serializer = ArticleSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['PUT'])\ndef update_article(request):\n id = request.data['id']\n try:\n article = Article.objects.get(id=id)\n except Article.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = ArticleSerializer(article, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['DELETE'])\ndef delete_article(request, id):\n try:\n article = Article.objects.get(id=id)\n except Article.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n article.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n@api_view(['GET'])\ndef get_user(request):\n id = int(request.GET['id'])\n try:\n user = User.objects.get(id=id)\n except User.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = UserSerializer(user)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_users(request):\n users = User.objects.all()\n if 'num' in request.GET:\n num = int(request.GET['num'])\n users = users[:num]\n serializer = UserSerializer(users, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_profile(request):\n userid = int(request.GET['userid'])\n try:\n profile = UserProfile.objects.get(user_id=userid)\n except UserProfile.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = UserProfileReadSerializer(profile)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_profiles(request):\n profiles = UserProfile.objects.all()\n if 'num' in request.GET:\n num = int(request.GET['num'])\n profiles = profiles[:num]\n serializer = UserProfileReadSerializer(profiles, many=True)\n return Response(serializer.data)\n\n\n@api_view(['PUT'])\ndef update_profile(request):\n data = json.loads(request.data['data'])\n id = data['user']\n try:\n profile = UserProfile.objects.get(user_id=id)\n except UserProfile.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n if 'file' in request.data:\n data['avatar'] = request.data['file']\n serializer = UserProfileSerializer(profile, data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET'])\ndef get_item(request):\n id = int(request.GET['id'])\n try:\n item = Item.objects.get(id=id)\n except Item.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = ItemSerializer(item)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_items(request):\n items = Item.objects.all()\n if 'pertaining_article' in request.GET:\n items = items.filter(pertaining_article=request.GET['pertaining_article'])\n if 'num' in request.GET:\n num = int(request.GET['num'])\n items = items[:num]\n serializer = ItemSerializer(items, many=True)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_game(request):\n id = int(request.GET['id'])\n try:\n game = Game.objects.get(id=id)\n except Game.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = GameSerializer(game)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_games(request):\n games = Game.objects.all()\n if 'pertaining_article' in request.GET:\n games = games.filter(pertaining_article=request.GET['pertaining_article'])\n if 'num' in request.GET:\n num = int(request.GET['num'])\n games = games[:num]\n serializer = GameSerializer(games, many=True)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef create_game(request):\n data = json.loads(request.data['data'])\n if 'file' not in request.data:\n serializer = GameSerializer(data=data)\n serializer.is_valid()\n errors = {'image': [\"This field may not be null!\"]}\n errors.update(serializer.errors)\n return Response(errors, status=status.HTTP_400_BAD_REQUEST)\n data['image'] = request.data['file']\n serializer = GameSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['PUT'])\ndef update_game(request):\n data = json.loads(request.data['data'])\n id = data['id']\n try:\n game = Game.objects.get(id=id)\n except Game.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n if 'file' in request.data:\n data['image'] = request.data['file']\n serializer = GameSerializer(game, data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['DELETE'])\ndef delete_game(request, id):\n try:\n game = Game.objects.get(id=id)\n except Game.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n game.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n@api_view(['GET'])\ndef get_console(request):\n id = int(request.GET['id'])\n try:\n console = Console.objects.get(id=id)\n except Console.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = ConsoleSerializer(console)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_consoles(request):\n consoles = Console.objects.all()\n if 'pertaining_article' in request.GET:\n consoles = consoles.filter(pertaining_article=request.GET['pertaining_article'])\n if 'num' in request.GET:\n num = int(request.GET['num'])\n consoles = consoles[:num]\n serializer = ConsoleSerializer(consoles, many=True)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef create_console(request):\n data = json.loads(request.data['data'])\n if 'file' not in request.data:\n serializer = ConsoleSerializer(data=data)\n serializer.is_valid()\n errors = {'image': [\"This field may not be null!\"]}\n errors.update(serializer.errors)\n return Response(errors, status=status.HTTP_400_BAD_REQUEST)\n data['image'] = request.data['file']\n serializer = ConsoleSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['PUT'])\ndef update_console(request):\n data = json.loads(request.data['data'])\n id = data['id']\n try:\n console = Console.objects.get(id=id)\n except Console.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n if 'file' in request.data:\n data['image'] = request.data['file']\n serializer = ConsoleSerializer(console, data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['DELETE'])\ndef delete_console(request, id):\n try:\n console = Console.objects.get(id=id)\n except Console.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n console.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n@api_view(['GET'])\ndef get_review(request):\n id = int(request.GET['id'])\n try:\n review = Review.objects.get(id=id)\n except Review.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n serializer = ReviewReadSerializer(review)\n return Response(serializer.data)\n\n\n@api_view(['GET'])\ndef get_reviews(request):\n reviews = Review.objects.all()\n if 'reviewer' in request.GET:\n reviews = reviews.filter(reviewer_id=request.GET['reviewer'])\n if 'reviewed' in request.GET:\n reviews = reviews.filter(reviewed_id=request.GET['reviewed'])\n if 'rate' in request.GET:\n reviews = reviews.filter(rate=request.GET['rate'])\n if 'num' in request.GET:\n num = int(request.GET['num'])\n reviews = reviews[:num]\n serializer = ReviewReadSerializer(reviews, many=True)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef create_review(request):\n print(request.data)\n serializer = ReviewSerializer(data=request.data)\n print(serializer)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n print(\n serializer.errors\n )\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","sub_path":"backend/rest_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"561175273","text":"import json\nimport os\nimport re\nimport numpy as np\nimport pandas as pd\nfrom textstat.textstat import textstat\nfrom textblob import TextBlob\nfrom collections import Counter\n\n\nclass DataProcessor():\n \"\"\" Handles the processing of the dataset containing reddit comments\n\n Attributes:\n dataset: list of dicts containing reddit comments and their attributes\n \"\"\"\n\n def __init__(self, input_data_path):\n \"\"\"Inits DataProcessor a dataset containing reddit comments\"\"\"\n self.input_data_path = input_data_path\n with open(input_data_path) as fp:\n self.dataset = json.load(fp)\n for idx in range(len(self.dataset)):\n self.dataset[idx]['text'] = self.process_text(\n self.dataset[idx]['text'])\n self.top_160_words = self.get_160_most_frequent_words(\n self.dataset[:10000])\n\n def generate_df_features(self, dataset, top_words,\n features=[0, 0, 0, 0, 0, 0, 0, 0, 0],\n interaction=None):\n bias = self.generate_df_bias(dataset)\n\n children = self.generate_df_children(dataset)\n controversiality = self.generate_df_controversiality(dataset)\n is_root = self.generate_df_is_root(dataset)\n\n df_features = pd.concat(\n [bias, children, controversiality, is_root], axis=1)\n\n if top_words > 0:\n top_words = self.generate_df_most_frequent_words(\n dataset, self.top_160_words[:top_words])\n df_features = pd.concat([df_features, top_words], axis=1)\n\n if features[0] > 1:\n children = self.generate_df_children(dataset, features[0])\n df_features = pd.concat([df_features, children], axis=1)\n if features[1] > 1:\n controversiality = self.generate_df_controversiality(\n dataset, features[1])\n df_features = pd.concat([df_features, controversiality], axis=1)\n if features[2] > 1:\n is_root = self.generate_df_is_root(dataset, features[2])\n df_features = pd.concat([df_features, is_root], axis=1)\n\n if features[3] > 0:\n word_count = self.generate_df_word_count(\n dataset, features[3])\n df_features = pd.concat([df_features, word_count], axis=1)\n if features[4] > 0:\n word_length = self.generate_df_avg_word_length(\n dataset, features[4])\n df_features = pd.concat([df_features, word_length], axis=1)\n if features[5] > 0:\n nb_word_per_sent = self.generate_df_nb_words_per_sent(\n dataset, features[5])\n df_features = pd.concat([df_features, nb_word_per_sent], axis=1)\n if features[6] > 0:\n sentiment = self.generate_df_sentiment(dataset, features[6])\n df_features = pd.concat([df_features, sentiment], axis=1)\n if features[7] > 0:\n readability = self.generate_df_readability(\n dataset, features[7])\n df_features = pd.concat([df_features, readability], axis=1)\n if features[8] > 0:\n sentiment = self.generate_df_sentiment(dataset)\n sentiment_square = self.generate_interact(sentiment,'sentiment',sentiment,'sentiment')\n nb_word_per_sent = self.generate_df_nb_words_per_sent(dataset)\n nb_word_per_sent_sentiment2 = self.generate_interact(\n sentiment_square,'sentiment*sentiment',nb_word_per_sent,'nb_word_per_sent')\n df_features = pd.concat([df_features, nb_word_per_sent_sentiment2], axis=1)\n\n if interaction is not None:\n interaction = self.generate_interact(\n df_features, interaction[0], df_features, interaction[1])\n df_features = pd.concat([df_features, interaction], axis=1)\n\n df_output = self.generate_df_popularity_score(dataset)\n return df_features, df_output\n\n # extra features begin here\n\n def generate_df_word_count(self, dataset, exponent=1):\n \"\"\" Generates a 10000x1 df of the word count for each comment\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains the word count\n for every training instance\n \"\"\"\n if exponent == 1:\n column = ['word_count']\n elif exponent > 1:\n column = ['word_count**' + str(exponent)]\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'text':\n word_count = info_value.size\n if exponent > 1:\n word_count = word_count ** exponent\n rows.append(word_count)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def generate_df_avg_word_length(self, dataset, exponent=1):\n \"\"\" Generates a 10000x1 df for the average word length\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains the word length\n for every training instance\n \"\"\"\n if exponent == 1:\n column = ['word_length']\n elif exponent > 1:\n column = ['word_length**' + str(exponent)]\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'text':\n info_value = self.array_to_str(info_value)\n words = info_value.split()\n word_length = sum(len(word)for word in words) / len(words)\n if exponent > 1:\n word_length = word_length ** exponent\n rows.append(word_length)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def generate_df_nb_words_per_sent(self, dataset, exponent=1):\n \"\"\" Generates a 10000x1 df for the avg number of words per sentence\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains the averaged number of\n words per sentence for every training instance\n \"\"\"\n if exponent == 1:\n column = ['nb_word_per_sent']\n elif exponent > 1:\n column = ['nb_word_per_sent**' + str(exponent)]\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'text':\n info_value = self.array_to_str(info_value)\n sents = info_value.replace(\n '?', '.').replace('!', '.').split('.')\n sents = list(filter(None, sents))\n if len(sents) > 0:\n nb_words_per_sent = sum(\n len(x.split())for x in sents) / len(sents)\n else:\n nb_words_per_sent = 1\n if exponent > 1:\n nb_words_per_sent = nb_words_per_sent ** exponent\n rows.append(nb_words_per_sent)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def generate_df_sentiment(self, dataset, exponent=1):\n \"\"\" Generates a 10000x1 df for the sentiment_score\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains sentiment_score\n for every training instance\n \"\"\"\n if exponent == 1:\n column = ['sentiment']\n elif exponent > 1:\n column = ['sentiment**' + str(exponent)]\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'text':\n info_value = self.array_to_str(info_value)\n sentiment_score = TextBlob(info_value).sentiment.polarity\n if exponent > 1:\n sentiment_score = sentiment_score ** exponent\n rows.append(sentiment_score)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def generate_df_readability(self, dataset, exponent=1):\n \"\"\" Generates a 10000x1 df for the readability score (Gunning Fox index)\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains readability_score\n for every training instance\n \"\"\"\n if exponent == 1:\n column = ['readability']\n elif exponent > 1:\n column = ['readability**' + str(exponent)]\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'text':\n info_value = self.array_to_str(info_value)\n readability_score = textstat.gunning_fog(info_value)\n if exponent > 1:\n readability_score = readability_score ** exponent\n rows.append(readability_score)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def generate_interact(self, dataset1, col1, dataset2, col2):\n \"\"\" Generates a 10000x1 df for the product of col1 and string2\n\n Args:\n dataset: list of dicts containing exist features\n\n Raises:\n InputError: If the input colume name col1 or col2 does not exist.\n\n Returns:\n df: 10000x1 pandas df that contains the product of col1 and col2\n for every training instance\n \"\"\"\n column = [col1+'*'+col2]\n if col1 not in dataset1:\n raise ValueError('1st argument does not exist in dataset1.')\n if col2 not in dataset2:\n raise ValueError('2nd argument does not exist in dataset2.')\n df = pd.DataFrame(\n (dataset1[col1]*dataset2[col2]).values, columns=column)\n return df\n\n # extra features ends here\n\n def generate_df_most_frequent_words(self, dataset, most_frequent_words):\n \"\"\" Generates a 10000xN df for the most frequent words\n\n The df contains one row for every training instance and one\n columnfor each word in the top N. The result is a 10000xN matrix\n that contains occurences of the most common words for every reddit\n comment\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n most_frequent_words: list of tuples containing the most\n frequent words and their occurences\n\n Returns:\n df: 10000xN pandas df that contains occurences of the\n most frequent words for every training instance\n \"\"\"\n columns = []\n for item in most_frequent_words:\n columns.append(item)\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'text':\n occurences = []\n for item in most_frequent_words:\n occurences.append(np.count_nonzero(info_value == item))\n rows.append(occurences)\n\n df = pd.DataFrame(rows, columns=columns)\n return df\n\n def generate_df_bias(self, dataset):\n \"\"\" Generates a 10000x1 df for the number of children comments\n\n Args:\n dataset: list of dicts containing reddit comments and their\n attributes\n Returns:\n df: 10000x1 pandas df that contains only ones and serves\n as the bias term\n \"\"\"\n\n ones_data = np.ones(len(dataset))\n df = pd.DataFrame(ones_data, columns=['bias'])\n return df\n\n def generate_df_children(self, dataset, exponent=1):\n \"\"\" Generates a 10000x1 df for the number of children comments\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains the number of children\n comments for every training instance\n \"\"\"\n if exponent == 1:\n column = ['children']\n elif exponent > 1:\n column = ['children**' + str(exponent)]\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'children':\n children = info_value\n if exponent > 1:\n children = children ** exponent\n rows.append(children)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def generate_df_controversiality(self, dataset, exponent=1):\n \"\"\" Generates a 10000x1 df for the number of controversiality\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains the controversiality\n value for every training instance\n \"\"\"\n if exponent == 1:\n column = ['controversiality']\n elif exponent > 1:\n column = ['controversiality**' + str(exponent)]\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'controversiality':\n controversiality = info_value\n if exponent > 1:\n controversiality = controversiality ** exponent\n rows.append(controversiality)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def generate_df_is_root(self, dataset, exponent=1):\n \"\"\" Generates a 10000x1 df for the feature is_root\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains is_root\n for every training instance\n \"\"\"\n if exponent == 1:\n column = ['is_root']\n elif exponent > 1:\n column = ['is_root**' + str(exponent)]\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'is_root':\n if info_value is False:\n is_root = 0\n elif info_value is True:\n is_root = 1\n rows.append(is_root)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def generate_df_popularity_score(self, dataset):\n \"\"\" Generates a 10000x1 df for the popularity_score\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n df: 10000x1 pandas df that contains popularity_score\n for every training instance\n \"\"\"\n column = ['popularity_score']\n\n rows = []\n for data_point in dataset:\n for info_name, info_value in data_point.items():\n if info_name == 'popularity_score':\n popularity_score = info_value\n rows.append(popularity_score)\n\n df = pd.DataFrame(rows, columns=column)\n return df\n\n def get_160_most_frequent_words(self, dataset):\n \"\"\" Gets a list containing the 160 most frequent words and their occurences\n\n Process reddit comments by applying lower() and split() on them, then\n returns the most frequent words and their occurences from the dataset\n\n Args:\n dataset: list of dicts containing reddit comments and\n their attributes\n\n Returns:\n most_frequent_words: list of tuples containing the most\n frequent words and their occurences\n \"\"\"\n all_text = np.concatenate([item['text'] for item in dataset])\n unique_text, count = np.unique(all_text, return_counts=True)\n most_frequent_words = unique_text[np.argsort(-count)][:160:1]\n most_frequent_words = np.array(most_frequent_words)\n return most_frequent_words.tolist()\n\n def flatten_list_of_lists(l):\n return [item for sublist in l for item in sublist]\n\n def data_point_to_str(self, data_point):\n \"\"\" Prints info about a data point\n\n A data point is a dictionary with the following attributes:\n popularity_score : float representiing the popualrity score\n children : the number of replies to this comment (type: int)\n text : the text of this comment (type: string)\n controversiality : '0' or '1' representing wether the comment\n is controversial\n is_root : 'true' if comment is a reply to a post, 'false' if it's\n a reply to a thread\n\n Args:\n data_point: dict containing a data point from the dataset\n\n Returns:\n s: string containing the available info about the data point\n \"\"\"\n s = ''\n for info_name, info_value in data_point.items():\n s += info_name + ' : ' + str(info_value) + '\\n'\n return s\n\n def create_wordstxt(self):\n \"\"\" Creates the word.txt file of 160 most frequent words in training set\n \"\"\"\n with open('words.txt', 'w', encoding=\"utf-8\") as fp:\n for word in self.top_160_words:\n fp.write(word + '\\n')\n\n def array_to_str(self, array):\n string = \"\"\n for item in array:\n string += item + ' '\n return string[:-1]\n\n def process_text(self, string):\n \"\"\" Lowers() and splits() a string \"\"\"\n processed_text = np.array(string.lower().split())\n return processed_text\n\n def get_training_dataset(self):\n \"\"\" Returns partitioned training dataset\"\"\"\n return self.dataset[:10000]\n\n def get_validation_dataset(self):\n \"\"\" Returns partitioned validation dataset\"\"\"\n return self.dataset[10000:11000]\n\n def get_test_dataset(self):\n \"\"\" Returns partitioned testing dataset\"\"\"\n return self.dataset[11000:]\n","sub_path":"project_1/process_dataset.py","file_name":"process_dataset.py","file_ext":"py","file_size_in_byte":18328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"337975217","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n \"\"\"\n Creación inicial de modelos.\n \"\"\"\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Area',\n fields=[\n ('id', models.AutoField(verbose_name='ID',\n auto_created=True,\n serialize=False,\n primary_key=True)),\n ('nombre', models.CharField(max_length=50)),\n ],\n ),\n migrations.CreateModel(\n name='Aula',\n fields=[\n ('id', models.AutoField(verbose_name='ID',\n auto_created=True,\n serialize=False,\n primary_key=True)),\n ('numero', models.PositiveSmallIntegerField()),\n ('nombre', models.CharField(blank=True, max_length=50)),\n ('capacidad', models.PositiveSmallIntegerField()),\n ('calendar_codigo', models.CharField(max_length=100)),\n ('calendar_color', models.CharField(max_length=10)),\n ('archivo_ubicacion', models.FileField(upload_to='ubicacion_aulas', blank=True)),\n ('areas', models.ManyToManyField(to='app_reservas.Area')),\n ],\n ),\n migrations.CreateModel(\n name='Cuerpo',\n fields=[\n ('id', models.AutoField(verbose_name='ID',\n auto_created=True,\n serialize=False,\n primary_key=True)),\n ('numero', models.PositiveSmallIntegerField()),\n ],\n ),\n migrations.CreateModel(\n name='Nivel',\n fields=[\n ('id', models.AutoField(verbose_name='ID',\n auto_created=True,\n serialize=False,\n primary_key=True)),\n ('numero', models.SmallIntegerField()),\n ('cuerpo', models.ForeignKey(to='app_reservas.Cuerpo')),\n ],\n ),\n migrations.AddField(\n model_name='aula',\n name='nivel',\n field=models.ForeignKey(to='app_reservas.Nivel'),\n ),\n ]\n","sub_path":"app_reservas/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"236099591","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mar 23 17:41:05 2022\n\n@author: sandypashikanti\n\"\"\"\nfrom datetime import date, timedelta\n\nimport config\nimport holidays\nimport numpy as np\nimport pandas as pd\nimport queries\n\n\ndef harvest_season(data_frame: pd.DataFrame, warehouse: str):\n \"\"\"\n extract harvest start date of different warehouses\n\n returns: pandas dataframe\n \"\"\"\n location = warehouse.lower()\n\n harvest = data_frame.copy()\n harvest[\"crop_date\"] = pd.to_datetime(harvest[\"crop_date\"], format=\"%Y-%m-%d\")\n harvest[\"crop_year\"] = harvest[\"crop_date\"].dt.year\n harvest = harvest.groupby(\"crop_year\").agg({\"crop_date\": [\"min\"]}).reset_index()\n harvest.columns = [\"crop_year\", f\"{location}_crop_date_min\"]\n\n if config.current_year not in harvest.crop_year.unique():\n harvest = harvest.append(\n {\n \"crop_year\": config.current_year,\n f\"{location}_crop_date_min\": pd.to_datetime(\n date.today() + timedelta(days=1), format=\"%Y-%m-%d\"\n ),\n },\n ignore_index=True,\n )\n\n return harvest\n\n\ndef holiday_dates(states: list, start_year: int, end_year: int):\n \"\"\"\n extract holidays for different states in brazil from 2019 to current year\n\n returns: pandas dataframe\n \"\"\"\n holidays_dict = {}\n holiday_state, holiday_date = ([] for _ in range(2))\n\n for year in range(start_year, end_year + 1):\n for state in states:\n for day, name in sorted(holidays.Brazil(subdiv=state, years=year).items()):\n holiday_state.append(state)\n holiday_date.append(day)\n\n holidays_dict[\"crop_state\"] = holiday_state\n holidays_dict[\"holiday\"] = holiday_date\n\n holidays_data = pd.DataFrame(holidays_dict)\n holidays_data[\"holiday\"] = pd.to_datetime(\n holidays_data[\"holiday\"], format=\"%Y-%m-%d\"\n )\n\n return holidays_data\n\n\ndef geo_rotation_x(data: pd.DataFrame, var1: str, var2: str, degrees: int):\n \"\"\"\n new geo x co-ordinates based on the angle of rotation\n\n returns: float value\n \"\"\"\n rotaional_value_x = (np.cos(np.radians(degrees)) * data[f\"{var1}\"]) + (\n np.sin(np.radians(degrees)) * data[f\"{var2}\"]\n )\n\n return rotaional_value_x\n\n\ndef geo_rotation_y(data: pd.DataFrame, var1: str, var2: str, degrees: int):\n \"\"\"\n new geo y co-ordinates based on the angle of rotation\n\n returns: float value\n \"\"\"\n rotaional_value_y = (np.cos(np.radians(degrees)) * data[f\"{var1}\"]) - (\n np.sin(np.radians(degrees)) * data[f\"{var2}\"]\n )\n\n return rotaional_value_y\n\n\ndef geo_data(geo_file):\n \"\"\"\n get latitude and longitude data for different warehouses\n\n returns: pandas dataframe\n \"\"\"\n data = pd.read_excel(config.raw_dir + f\"{geo_file}.xls\")\n data = data[[\"warehouse\", \"crop_state\", \"latitude\", \"longitude\"]]\n data[\"warehouse\"] = data[\"warehouse\"].str.lower()\n\n # create rotational columns for latitude & longitude combo\n data[\"rot_lat_45\"] = geo_rotation_x(data, \"latitude\", \"longitude\", 45)\n data[\"rot_long_45\"] = geo_rotation_y(data, \"longitude\", \"latitude\", 45)\n data[\"rot_lat_30\"] = geo_rotation_x(data, \"latitude\", \"longitude\", 30)\n data[\"rot_long_30\"] = geo_rotation_x(data, \"longitude\", \"latitude\", 30)\n\n data.to_pickle(config.interim_dir + \"geo_data.pickle\")\n\n return data\n\n\ndef preprocessing_fn(\n start_year: int, start_month: int, end_month: int, product_id: str, sub_folder: str\n):\n \"\"\"\n weather, contracts, & transactions data are combined to generate engineered features for different warehouses\n\n returns: pandas dataframe\n \"\"\"\n\n contracts_data = config.cdp_conn.get_data(\n queries.get_datetime_features(\n start_year, config.current_year, start_month, end_month,\n ),\n )\n\n # weather data\n for k, (i, j) in enumerate(config.warehouse_dict.items()):\n\n # weather data\n for metric in [x for x in config.crop_vars if x not in (\"vol\", \"trk\")]:\n\n # create new weather dataframe for the first warehouse and the first weather metric combination\n # and join the dataframes of other warehouses & weather metrics combinations to this one\n if k == 0 and metric == config.crop_vars[0]:\n weather_data = config.cdp_conn.get_data(\n queries.get_weather_data(\n start_year,\n config.current_year,\n start_month,\n end_month,\n metric,\n j[0],\n j[1],\n j[2],\n ),\n )\n\n else:\n data = config.cdp_conn.get_data(\n queries.get_weather_data(\n start_year,\n config.current_year,\n start_month,\n end_month,\n metric,\n j[0],\n j[1],\n j[2],\n ),\n )\n # merge data\n weather_data = pd.merge(weather_data, data, how=\"outer\", on=\"crop_date\")\n\n # create new transactions data frame for the first warehouse and join the dataframes of other warehouses to\n # this one\n if k == 0:\n transactions_data = config.cdp_conn.get_data(\n queries.get_transactions_data(\n start_year,\n config.current_year,\n start_month,\n end_month,\n product_id,\n j[0],\n j[5],\n j[6],\n ),\n )\n\n harvest_dates = harvest_season(transactions_data, j[0])\n\n else:\n data = config.cdp_conn.get_data(\n queries.get_transactions_data(\n start_year,\n config.current_year,\n start_month,\n end_month,\n product_id,\n j[0],\n j[5],\n j[6],\n ),\n )\n\n harvest = harvest_season(data, j[0])\n\n # merge data\n transactions_data = pd.merge(\n transactions_data, data, how=\"outer\", on=\"crop_date\"\n )\n harvest_dates = pd.merge(\n harvest_dates, harvest, how=\"outer\", on=\"crop_year\"\n )\n\n # extract number of contracts started during the crop season for a warehouse till a particular day\n started = config.cdp_conn.get_data(\n queries.get_contracts_started_data(\n start_year,\n config.current_year,\n start_month,\n end_month,\n product_id,\n j[0],\n j[7],\n ),\n )\n\n # extract number of contracts fulfilled during the crop season for a warehouse till a particular day\n fulfilled = config.cdp_conn.get_data(\n queries.get_fulfilled_data(\n start_year,\n config.current_year,\n start_month,\n end_month,\n product_id,\n j[0],\n j[7],\n ),\n )\n\n # extract number of contracts agreed for the crop season\n agreed = config.cdp_conn.get_data(\n queries.get_agreed_data(\n start_year,\n config.current_year,\n start_month,\n end_month,\n product_id,\n j[0],\n j[7],\n ),\n )\n\n # merge data\n contracts_data = (\n contracts_data.merge(started, how=\"left\", on=\"crop_date\")\n .merge(fulfilled, how=\"left\", on=\"crop_date\")\n .merge(agreed, how=\"left\", on=\"crop_year\")\n )\n\n # export interim data\n weather_data.to_pickle(config.interim_dir + sub_folder + \"weather_data.pickle\")\n transactions_data.to_pickle(\n config.interim_dir + sub_folder + \"transactions_data.pickle\"\n )\n contracts_data.to_pickle(config.interim_dir + sub_folder + \"contracts_data.pickle\")\n harvest_dates.to_pickle(config.interim_dir + sub_folder + \"harvest_dates.pickle\")\n\n \"\"\"\n TODO: if any of the rows have missing values, it implies that weather data is not available in the database table\n Create an alert for the dates and columns that have missing NA\n \"\"\"\n\n print(\n \"Dates with missing weather data:\",\n weather_data[weather_data.isna().any(axis=1)][\"crop_date\"],\n )\n\n # extract all the dates of the crop season\n season_dates = config.cdp_conn.get_data(\n queries.get_season_dates(\n start_year - 1, config.current_year, start_month, end_month,\n ),\n )\n\n crop_data = (\n season_dates.merge(weather_data, how=\"left\", on=\"crop_date\")\n .merge(transactions_data, how=\"left\", on=\"crop_date\")\n .merge(\n contracts_data,\n how=\"left\",\n on=[\"crop_date\", \"crop_year\", \"crop_month\", \"crop_day\"],\n )\n .merge(harvest_dates, how=\"left\", on=\"crop_year\")\n )\n crop_data = crop_data.replace(np.NAN, 0)\n crop_data[\"crop_date\"] = pd.to_datetime(crop_data[\"crop_date\"], format=\"%Y-%m-%d\")\n crop_data.sort_values(by=[\"crop_date\"], inplace=True)\n crop_data.reset_index(inplace=True, drop=True)\n\n for i, j in config.warehouse_dict.items():\n\n warehouse = (f\"{j[0]}\").lower()\n\n for metric in config.crop_vars:\n\n # historic data of last one week\n for lag in range(1, 8):\n crop_data[f\"{warehouse}_{metric}_past{lag}\"] = crop_data[\n f\"{warehouse}_{metric}\"\n ].shift(lag)\n\n # avg metrics in the last 3, 7 days\n for n in config.avg_days:\n crop_data[f\"{warehouse}_{metric}_avg_{n}days\"] = crop_data[\n [f\"{warehouse}_{metric}_past{lag}\" for lag in range(1, n + 1)]\n ].mean(axis=1)\n\n for metric in [x for x in config.crop_vars if x != \"trk\"]:\n\n # forecasted weather metrics and future volumes\n for lead in range(1, config.forecast_days):\n crop_data[f\"{warehouse}_{metric}_next{lead}\"] = crop_data[\n f\"{warehouse}_{metric}\"\n ].shift(-lead)\n\n # avg forecasted weather metrics & volume\n for n in range(1, config.forecast_days):\n crop_data[f\"{warehouse}_{metric}_avg_forecast{n}\"] = crop_data[\n [f\"{warehouse}_{metric}_next{day}\" for day in range(1, n + 1)]\n + [f\"{warehouse}_{metric}\"]\n ].mean(axis=1)\n\n # daily cumulative volume\n crop_data[f\"{warehouse}_cum_volume\"] = crop_data.groupby(\"crop_year\")[\n f\"{warehouse}_vol\"\n ].apply(lambda x: x.cumsum())\n\n # cumulative volume till previous day\n crop_data[f\"{warehouse}_vol_cumulative\"] = crop_data.groupby(\"crop_year\")[\n f\"{warehouse}_cum_volume\"\n ].shift(1)\n\n # contracts\n crop_data[f\"{warehouse}_contracts_started\"] = crop_data.groupby(\"crop_year\")[\n f\"{warehouse}_contracts_kickoff\"\n ].shift(1)\n crop_data[f\"{warehouse}_contracts_finished\"] = crop_data.groupby(\"crop_year\")[\n f\"{warehouse}_contracts_delivered\"\n ].shift(1)\n crop_data[f\"{warehouse}_vol_overdelivered\"] = crop_data.groupby(\"crop_year\")[\n f\"{warehouse}_volume_overdelivered\"\n ].shift(1)\n\n # impute missing values - at the beginning of each year\n crop_data[\n [\n f\"{warehouse}_contracts_started\",\n f\"{warehouse}_contracts_finished\",\n f\"{warehouse}_vol_overdelivered\",\n f\"{warehouse}_vol_cumulative\",\n ]\n ] = crop_data[\n [\n f\"{warehouse}_contracts_started\",\n f\"{warehouse}_contracts_finished\",\n f\"{warehouse}_vol_overdelivered\",\n f\"{warehouse}_vol_cumulative\",\n ]\n ].replace(\n np.NAN, 0\n )\n\n crop_data[f\"{warehouse}_contracts_to_start\"] = (\n crop_data[f\"{warehouse}_contracts_agreed\"]\n - crop_data[f\"{warehouse}_contracts_started\"]\n )\n crop_data[f\"{warehouse}_contracts_to_finish\"] = (\n crop_data[f\"{warehouse}_contracts_agreed\"]\n - crop_data[f\"{warehouse}_contracts_finished\"]\n )\n crop_data[f\"{warehouse}_vol_to_deliver\"] = (\n crop_data[f\"{warehouse}_vol_agreed\"]\n - crop_data[f\"{warehouse}_vol_cumulative\"]\n )\n\n # harvest\n crop_data[f\"{warehouse}_crop_date_min\"] = pd.to_datetime(\n crop_data[f\"{warehouse}_crop_date_min\"], errors=\"coerce\", format=\"%Y-%m-%d\"\n )\n crop_data[f\"{warehouse}_days_since_harvest_start\"] = (\n crop_data[\"crop_date\"] - crop_data[f\"{warehouse}_crop_date_min\"]\n ).astype(\"timedelta64[D]\")\n\n # extract volume received on the same date of last year\n past_season = crop_data[\n [\"crop_date\", \"crop_day\", \"crop_month\", \"crop_year\", f\"{warehouse}_vol\"]\n ]\n seasonal_vol = pd.merge(\n past_season, past_season, how=\"inner\", on=[\"crop_day\", \"crop_month\"]\n )\n seasonal_vol = seasonal_vol[\n seasonal_vol.crop_year_x - seasonal_vol.crop_year_y == 1\n ][[\"crop_date_x\", f\"{warehouse}_vol_y\"]]\n seasonal_vol.rename(\n columns={\n \"crop_date_x\": \"crop_date\",\n f\"{warehouse}_vol_y\": f\"{warehouse}_vol_lastyear\",\n },\n inplace=True,\n )\n crop_data = pd.merge(crop_data, seasonal_vol, how=\"left\", on=\"crop_date\")\n\n # missing values - Feb 29th will have last year's vol missing\n crop_data[f\"{warehouse}_vol_lastyear\"] = crop_data[\n f\"{warehouse}_vol_lastyear\"\n ].fillna(method=\"ffill\", limit=1)\n\n # drop variables unknown at prediction time\n crop_data = crop_data.drop(\n [\n f\"{warehouse}_cum_volume\",\n f\"{warehouse}_contracts_kickoff\",\n f\"{warehouse}_contracts_delivered\",\n f\"{warehouse}_volume_overdelivered\",\n f\"{warehouse}_trk\",\n f\"{warehouse}_vol_avg_forecast14\",\n f\"{warehouse}_crop_date_min\",\n ],\n axis=1,\n )\n\n crop_data.sort_values(by=[\"crop_date\"], inplace=True)\n crop_data.reset_index(inplace=True, drop=True)\n\n # export processed data\n crop_data.to_pickle(config.interim_dir + sub_folder + \"crop_data.pickle\")\n\n return crop_data\n\n\ndef feature_eng_fn(\n crop_data_frame: pd.DataFrame, holidays_start_year: int, sub_folder: str\n):\n \"\"\"\n crop data is converted from wide to long format and features related to holidays, & location are added\n\n returns: pandas dataframe\n \"\"\"\n\n geo_data = pd.read_pickle(config.interim_dir + \"geo_data.pickle\")\n\n # get holidays in Brazil for different states\n season_holidays = holiday_dates(\n config.brazil_states, holidays_start_year, config.current_year\n )\n\n # individual warehouses data are stacked to form a single dataframe\n for k, (i, j) in enumerate(config.warehouse_dict.items()):\n\n warehouse = (f\"{j[0]}\").lower()\n warehouse_vars = config.datetime_vars + list(\n crop_data_frame.filter(regex=f\"^{warehouse}_\")\n )\n\n # create new stacked crop dataframe for the first warehouse and join the dataframes of other warehouses to\n # this one\n if k == 0:\n stacked_crop_data = crop_data_frame[warehouse_vars]\n stacked_crop_data.columns = [\n var.replace(f\"{warehouse}_\", \"\") for var in list(stacked_crop_data)\n ]\n stacked_crop_data[\"warehouse\"] = f\"{warehouse}\"\n stacked_crop_data[\"unit_name\"] = f\"{j[8]}\"\n stacked_crop_data[\"sub_regional\"] = f\"{j[9]}\"\n stacked_crop_data[\"unit_id\"] = f\"{j[10]}\"\n\n else:\n data = crop_data_frame[warehouse_vars]\n data.columns = [var.replace(f\"{warehouse}_\", \"\") for var in list(data)]\n data[\"warehouse\"] = f\"{warehouse}\"\n data[\"unit_name\"] = f\"{j[8]}\"\n data[\"sub_regional\"] = f\"{j[9]}\"\n data[\"unit_id\"] = f\"{j[10]}\"\n\n stacked_crop_data = pd.concat([stacked_crop_data, data], axis=0)\n\n # export processed data\n stacked_crop_data.to_pickle(\n config.processed_dir + sub_folder + \"stacked_crop_data.pickle\"\n )\n\n # add location and holidays info to stacked_crop_data\n agg_crop_data = stacked_crop_data.merge(geo_data, how=\"left\", on=\"warehouse\").merge(\n season_holidays,\n left_on=[\"crop_state\", \"crop_date\"],\n right_on=[\"crop_state\", \"holiday\"],\n how=\"left\",\n )\n agg_crop_data[\"holiday\"] = np.where(pd.isnull(agg_crop_data[\"holiday\"]), 0, 1)\n agg_crop_data[\"days_since_harvest_start\"] = agg_crop_data[\n \"days_since_harvest_start\"\n ].clip(lower=-1)\n\n # generate encoded variables for different categories of states\n for state in list(pd.unique(agg_crop_data.crop_state)):\n var = state.lower()\n agg_crop_data[f\"state_{var}\"] = np.where(\n agg_crop_data[\"crop_state\"] == state, 1, 0\n )\n agg_crop_data.to_pickle(config.processed_dir + sub_folder + \"agg_crop_data.pickle\")\n\n return agg_crop_data\n\n\ndef model_data_fn(agg_crop_data: pd.DataFrame, sub_folder: str):\n \"\"\"\n modeling datasets for different forecasting days are created\n\n returns: dict\n \"\"\"\n\n # create datasets for different forecasting days and store them in a dictionary\n forecast_days_data = {}\n\n # different days of agg data\n for day in range(config.forecast_days):\n excluded = []\n for metric in config.crop_vars:\n for var in [\"next\", \"avg_forecast\"]:\n for n in range(day, config.forecast_days):\n if var == \"avg_forecast\" and metric == \"vol\":\n excluded.extend(\n list(agg_crop_data.filter(regex=f\"{metric}_{var}{n}$\"))\n )\n else:\n excluded.extend(\n list(agg_crop_data.filter(regex=f\"{metric}_{var}{n+1}$\"))\n )\n included = [x for x in list(agg_crop_data) if x not in excluded]\n data = agg_crop_data[included]\n data.to_pickle(config.processed_dir + sub_folder + f\"forecast_day{day}.pickle\")\n forecast_days_data[f\"data_day{day}\"] = data\n\n return forecast_days_data\n","sub_path":"Docker/Files/src/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":18935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"633227172","text":"from datetime import datetime\n\nfrom sqlalchemy import Boolean\nfrom sqlalchemy import Column\nfrom sqlalchemy import DateTime\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy import Integer\nfrom sqlalchemy import String\nfrom sqlalchemy import Table\nfrom sqlalchemy import Text\nfrom sqlalchemy import exists\nfrom sqlalchemy import or_\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.orm import sessionmaker\n\nfrom opwen_email_client.domain.email.store import EmailStore\nfrom opwen_email_client.util.sqlalchemy import create_database\nfrom opwen_email_client.util.sqlalchemy import get_or_create\nfrom opwen_email_client.util.sqlalchemy import session\n\n_Base = declarative_base()\n\n\n_EmailTo = Table('emailto',\n _Base.metadata,\n Column('email_id', Integer, ForeignKey('email.id')),\n Column('to_id', Integer, ForeignKey('to.id')))\n\n_EmailCc = Table('emailcc',\n _Base.metadata,\n Column('email_id', Integer, ForeignKey('email.id')),\n Column('cc_id', Integer, ForeignKey('cc.id')))\n\n_EmailBcc = Table('emailbcc',\n _Base.metadata,\n Column('email_id', Integer, ForeignKey('email.id')),\n Column('bcc_id', Integer, ForeignKey('bcc.id')))\n\n_EmailAttachment = Table(\n 'emailattachment',\n _Base.metadata,\n Column('email_id', Integer, ForeignKey('email.id')),\n Column('attachment_id', Integer, ForeignKey('attachment.id')))\n\n\nclass _To(_Base):\n __tablename__ = 'to'\n id = Column(Integer, primary_key=True)\n\n address = Column(String(length=128), index=True, unique=True)\n\n\nclass _Cc(_Base):\n __tablename__ = 'cc'\n id = Column(Integer, primary_key=True)\n\n address = Column(String(length=128), index=True, unique=True)\n\n\nclass _Bcc(_Base):\n __tablename__ = 'bcc'\n id = Column(Integer, primary_key=True)\n\n address = Column(String(length=128), index=True, unique=True)\n\n\nclass _Attachment(_Base):\n __tablename__ = 'attachment'\n id = Column(Integer, primary_key=True)\n\n filename = Column(Text)\n content = Column(Text)\n\n\nclass _Email(_Base):\n __tablename__ = 'email'\n id = Column(Integer, primary_key=True)\n\n uid = Column(String(length=64), unique=True, index=True)\n subject = Column(Text)\n body = Column(Text)\n sent_at = Column(DateTime())\n read = Column(Boolean, default=False, nullable=False)\n sender = Column(String(length=128), index=True)\n attachments = relationship(_Attachment, secondary=_EmailAttachment,\n backref='emails')\n to = relationship(_To, secondary=_EmailTo)\n cc = relationship(_Cc, secondary=_EmailCc)\n bcc = relationship(_Bcc, secondary=_EmailBcc)\n\n def to_dict(self):\n attachments = self.attachments\n attachments = ([{'filename': attachment.filename,\n 'content': attachment.content}\n for attachment in attachments]\n if attachments else None)\n\n sent_at = self.sent_at\n sent_at = (sent_at.strftime('%Y-%m-%d %H:%M')\n if sent_at else None)\n\n return {k: v for (k, v) in (\n ('from', self.sender),\n ('to', [_.address for _ in self.to]),\n ('cc', [_.address for _ in self.cc]),\n ('bcc', [_.address for _ in self.bcc]),\n ('subject', self.subject),\n ('body', self.body),\n ('_uid', self.uid),\n ('sent_at', sent_at),\n ('read', self.read),\n ('attachments', attachments),\n ) if v}\n\n @classmethod\n def from_dict(cls, db, email):\n sent_at = email.get('sent_at')\n sent_at = (datetime.strptime(sent_at, '%Y-%m-%d %H:%M')\n if sent_at else None)\n\n return _Email(\n uid=email['_uid'],\n to=[get_or_create(db, _To, address=_.lower())\n for _ in email.get('to', [])],\n cc=[get_or_create(db, _Cc, address=_.lower())\n for _ in email.get('cc', [])],\n bcc=[get_or_create(db, _Bcc, address=_.lower())\n for _ in email.get('bcc', [])],\n attachments=[get_or_create(db, _Attachment, **_)\n for _ in email.get('attachments', [])],\n subject=email.get('subject'),\n body=email.get('body'),\n sent_at=sent_at,\n read=email.get('read', False),\n sender=email.get('from', '').lower() or None)\n\n @classmethod\n def is_sent_by(cls, email_address):\n email_address = email_address.lower()\n return cls.sender == email_address\n\n @classmethod\n def is_received_by(cls, email_address):\n email_address = email_address.lower()\n return (cls.to.any(_To.address == email_address) |\n cls.cc.any(_Cc.address == email_address) |\n cls.bcc.any(_Bcc.address == email_address))\n\n\nclass _SqlalchemyEmailStore(EmailStore):\n def __init__(self, database_uri: str, restricted=None):\n super().__init__(restricted)\n self._base = _Base\n self._engine = create_database(database_uri, self._base)\n self._sesion_maker = sessionmaker(autocommit=False, autoflush=False,\n bind=self._engine)\n\n def _dbread(self):\n return session(self._sesion_maker, commit=False)\n\n def _dbwrite(self):\n return session(self._sesion_maker, commit=True)\n\n def _create(self, emails):\n with self._dbwrite() as db:\n for email in emails:\n uid_exists = exists().where(_Email.uid == email['_uid'])\n if not db.query(uid_exists).scalar():\n db.add(_Email.from_dict(db, email))\n\n def _mark_sent(self, uids):\n now = datetime.utcnow()\n set_sent_at = {_Email.sent_at: now}\n\n with self._dbwrite() as db:\n db.query(_Email)\\\n .filter(_match_email_uid(uids))\\\n .update(set_sent_at, synchronize_session='fetch')\n\n def _mark_read(self, email_address, uids):\n set_read = {_Email.read: True}\n\n with self._dbwrite() as db:\n db.query(_Email)\\\n .filter(_match_email_uid(uids) & _can_access(email_address))\\\n .update(set_read, synchronize_session='fetch')\n\n def _delete(self, email_address, uids):\n should_delete = _match_email_uid(uids) & _can_access(email_address)\n\n with self._dbwrite() as db:\n for email in db.query(_Email).filter(should_delete).all():\n email.attachments = []\n db.delete(email)\n\n self._delete_orphaned_attachments()\n\n def _delete_orphaned_attachments(self):\n with self._dbwrite() as db:\n db.query(_Attachment)\\\n .filter(~_Attachment.emails.any())\\\n .delete(synchronize_session='fetch')\n\n def _find(self, query):\n with self._dbread() as db:\n results = db.query(_Email).filter(query)\n email = results.first()\n return email.to_dict() if email else None\n\n def _query(self, query):\n with self._dbread() as db:\n results = db.query(_Email).filter(query)\n for email in results.order_by(_Email.sent_at.desc()).all():\n yield email.to_dict()\n\n def inbox(self, email_address):\n return self._query(_Email.is_received_by(email_address))\n\n def outbox(self, email_address):\n return self._query(_Email.is_sent_by(email_address)\n & _Email.sent_at.is_(None))\n\n def search(self, email_address, query):\n textquery = '%{}%'.format(query)\n contains_query = or_(*(_Email.subject.ilike(textquery),\n _Email.body.ilike(textquery),\n _Email.sender.ilike(textquery),\n _Email.to.any(_To.address.ilike(textquery)),\n _Email.cc.any(_Cc.address.ilike(textquery)),\n _Email.bcc.any(_Bcc.address.ilike(textquery))))\n return self._query(_can_access(email_address) & contains_query)\n\n def pending(self):\n return self._query(_Email.sent_at.is_(None))\n\n def get(self, uid):\n return self._find(_Email.uid == uid)\n\n def sent(self, email_address):\n return self._query(_Email.is_sent_by(email_address)\n & _Email.sent_at.isnot(None))\n\n\nclass SqliteEmailStore(_SqlalchemyEmailStore):\n def __init__(self, database_path: str, restricted=None):\n super().__init__('sqlite:///{}'.format(database_path), restricted)\n\n\ndef _can_access(email_address):\n return (_Email.is_sent_by(email_address)\n | _Email.is_received_by(email_address))\n\n\ndef _match_email_uid(uids):\n return _Email.uid.in_(uids)\n","sub_path":"opwen_email_client/domain/email/sql_store.py","file_name":"sql_store.py","file_ext":"py","file_size_in_byte":8884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"203876826","text":"# -*- coding: utf-8 -*-\n\nimport os, webapp2\n\ndebug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev')\n\nroutes = [\n (r'/', 'handlers.MainHandler.MainHandler'),\n \n]\n\nconfig = {}\nconfig['webapp2_extras.sessions'] = {\n 'secret_key': 'секретный ключ для сессии',\n}\n\napplication = webapp2.WSGIApplication(routes=routes, debug=debug, config=config)\n\ndef main():\n application.run()\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"348727899","text":"from snr import Seq\nimport random\n\n\ndef is_increasing(f_d):\n for k in range(len(f_d)):\n if f_d[k] < f_d[k-1]:\n return False\n return True\n\n\nclass Signary:\n\n _DIV = \".\"\n\n def __init__(self, d, n):\n self.d = d\n self.n = n\n\n def __str__(self):\n out = self.n.val[::-1]\n return Signary._DIV.join([str(k) for k in out])\n\n def trim(self):\n out = self.n\n for x in range(len(out) - 1, -1 , -1):\n if out[x] == 0:\n out.val.pop(x)\n else:\n self.n = out\n return self\n self.n = out\n return self\n\n def get_base_10(self):\n f_d = self.d.f(l=len(self.n))\n out = 0\n for k in range(len(self.n)):\n out += f_d[k] * self.n[k]\n return out\n\n @staticmethod\n def create_numeration(d, N):\n \"\"\"\n This algorithm fails when f_d is not monotonic increasing\n\n :param d: the signature of the numeration\n :param N: the base-10 value to give the numeration\n :return: The number N in signary form\n \"\"\"\n f_d = d.f(l=25) # Using large length to avoid better code\n if not is_increasing(f_d):\n raise ValueError(\"Sequence \" + str(f_d) + \" is not increasing\")\n p = 0\n for k in range(25):\n if N > f_d[k]:\n p += 1\n else:\n break\n out = [0 for k in range(p)]\n for k in range(p, -1, -1):\n while N >= f_d[k]:\n N -= f_d[k]\n out[k] += 1\n return Signary(d, Seq(out))\n\n\nd = Seq([9, 6])\nN = random.randint(0, random.randint(0, 100000))\nS = Signary.create_numeration(d, N)\n\nprint(d.f(len(S.n)))\nprint(N)\nprint(S)\nprint(S.get_base_10())\n","sub_path":"archive/misc/signary/signary.py","file_name":"signary.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"294578480","text":"import ast\nimport ipaddress\nimport os\nimport re\nimport time\nimport warnings\nimport xml.dom.minidom\nfrom datetime import datetime\nfrom xml.etree import ElementTree\n\nimport pexpect\nimport xmltodict\nfrom boardfarm.exceptions import (ACSFaultCode, CodeError, TR069FaultCode,\n TR069ResponseError)\nfrom boardfarm.lib.bft_pexpect_helper import bft_pexpect_helper\nfrom boardfarm.lib.network_testing import (kill_process, tcpdump_capture,\n tshark_read)\nfrom debtcollector import moves\nfrom nested_lookup import nested_lookup\nfrom requests import HTTPError, Session\nfrom requests.auth import HTTPBasicAuth\nfrom zeep import Client\nfrom zeep.cache import InMemoryCache\nfrom zeep.transports import Transport\nfrom zeep.wsse.username import UsernameToken\n\nfrom . import base_acs\n\nwarnings.simplefilter('always')\n\n\nclass AxirosACS(base_acs.BaseACS):\n \"\"\"ACS connection class used to perform TR069 operations on stations/board.\"\"\"\n model = \"axiros_acs_soap\"\n name = \"acs_server\"\n # should the following be dynamic?\n namespaces = {'http://www.w3.org/2001/XMLSchema-instance': None}\n CPE_wait_time = 60 * 1 # too long?\n Count_retry_on_error = 3 # to be audited\n\n def __init__(self, *args, **kwargs):\n \"\"\"Intialize the varible that are used in establishing connection to the ACS and\\\n Intialize an HTTP SOAP client which will authenticate with the ACS server.\n\n :param ``*args``: the arguments to be used if any\n :type ``*args``: tuple\n :param ``**kwargs``: extra args to be used if any (mainly contains username, password, ipadress and port)\n :type ``**kwargs``: dict\n \"\"\"\n self.args = args\n self.kwargs = kwargs\n self.username = self.kwargs['username']\n self.password = self.kwargs['password']\n self.ipaddr = self.kwargs['ipaddr']\n self.port = self.kwargs.get('port', None)\n self.cli_port = self.kwargs.pop('cli_port', '22')\n self.cli_username = self.kwargs.pop('cli_username', None)\n self.cli_password = self.kwargs.pop('cli_password', None)\n self.color = self.kwargs.pop('color', None)\n self.options = self.kwargs.pop('options', None)\n AxirosACS.CPE_wait_time = self.kwargs.pop('wait_time',\n AxirosACS.CPE_wait_time)\n\n if self.options:\n options = [x.strip() for x in self.options.split(',')]\n for opt in options:\n if opt.startswith('wan-static-ipv6:'):\n ipv6_address = opt.replace('wan-static-ipv6:', '').strip()\n if \"/\" not in opt:\n ipv6_address += \"/64\"\n self.ipv6_interface = ipaddress.IPv6Interface(ipv6_address)\n self.gwv6 = self.ipv6_interface.ip\n\n if self.port is not None:\n target = self.ipaddr + \":\" + self.port\n else:\n target = self.ipaddr\n\n self.wsdl = \"http://\" + target + \"/live/CPEManager/DMInterfaces/soap/getWSDL\"\n\n session = Session()\n session.auth = HTTPBasicAuth(self.username, self.password)\n\n self.client = Client(\n wsdl=self.wsdl,\n transport=Transport(session=session,\n cache=InMemoryCache(timeout=3600 * 3)),\n wsse=UsernameToken(self.username, self.password),\n )\n\n # to spawn pexpect on cli\n if all([self.ipaddr, self.cli_username, self.cli_password]):\n bft_pexpect_helper.spawn.__init__(\n self,\n command=\"ssh\",\n args=[\n '%s@%s' % (self.cli_username, self.ipaddr), '-p',\n self.cli_port, '-o', 'StrictHostKeyChecking=no', '-o',\n 'UserKnownHostsFile=/dev/null', '-o',\n 'ServerAliveInterval=60', '-o', 'ServerAliveCountMax=5'\n ])\n self.check_connection(self.cli_username, self.name,\n self.cli_password)\n self.print_connected_console_msg(self.ipaddr, self.cli_port,\n self.color, self.name)\n # this should be populater ONLY when using __main__\n self.cpeid = self.kwargs.pop('cpeid', None)\n\n def sudo_sendline(self, cmd):\n # overwriting linux behaviour\n # this is under assumption that acs is having root credentials.\n self.sendline(cmd)\n\n def tcp_dump(func):\n \"\"\" Decorator to capture tcpdump in error cases\n \"\"\"\n def wrapper(self, *args, **kwargs):\n try:\n capture_file = \"acs_debug\" + time.strftime(\n \"%Y%m%d-%H%M%S\") + \".pcap\"\n tcpdump_capture(self, \"any\", capture_file=capture_file)\n out = func(self, *args, **kwargs)\n kill_process(self, process=\"tcpdump\")\n return out\n except Exception as e:\n kill_process(self, process=\"tcpdump\")\n tshark_read(self, capture_file, filter_str=\"-Y http\")\n raise (e)\n finally:\n self.sendline(\"rm %s\" % capture_file)\n\n return wrapper\n\n def __str__(self):\n \"\"\"Format the string representation of self object (instance).\n\n :returns: :class:`Response ` string representation of self object.\n :rtype: string\n \"\"\"\n return \"AxirosACS\"\n\n # TO DO: maybe this could be moved to a lib\n def _data_conversion(d):\n \"\"\"Conversion type/data helper.\"\"\"\n def to_int(v):\n return int(v)\n\n def to_bool(v):\n if v == '1':\n return 'true'\n elif v == '0':\n return 'false'\n return v\n\n def to_dateTime(v):\n if re.search(r'^1\\s', v):\n v = v.zfill(len(v) + 3)\n v = datetime.strptime(\n v, '%Y %m %d %H %M %S.0').strftime('%Y-%m-%dT%H:%M:%S')\n return v\n\n conv_table = {\n 'xsd3:string': {\n 'string': None\n },\n 'xsd3:integer': {\n 'integer': to_int\n },\n 'xsd3:boolean': {\n 'boolean': to_bool\n },\n 'xsd3:ur-type[6]': {\n 'dateTime': to_dateTime\n }\n }\n convdict = conv_table.get(d['type'])\n if convdict:\n d['type'] = next(iter(convdict))\n if d['value'] != '' and convdict[d['type']]:\n v = convdict[d['type']](d['value'])\n d['value'] = v\n return d\n\n @staticmethod\n def _parse_xml_response(data_values):\n data_list = []\n if type(data_values) is list:\n pass\n else:\n data_values = [data_values]\n for data in data_values:\n if 'AccessList' in data['value']:\n data_list.append({\n 'Name':\n data['key']['text'],\n 'AccessList':\n data['value']['AccessList']['item']['text'],\n 'Notification':\n data['value']['Notification']['text']\n })\n else:\n v = data['value'].get('text', '')\n if v == '':\n if 'item' in data['value']:\n v = \" \".join(\n [val.get('text') for val in data['value']['item']])\n val_type = data['value']['type']\n if val_type == 'SOAP-ENC:Array':\n val_type = data['value'][\n 'http://schemas.xmlsoap.org/soap/encoding/:arrayType']\n data_list.append(\n AxirosACS._data_conversion({\n 'key': data['key']['text'],\n 'type': val_type,\n 'value': v\n }))\n\n return data_list\n\n @staticmethod\n def _get_xml_key(resp, k='text'):\n result = nested_lookup(\n 'Result',\n xmltodict.parse(resp.content,\n attr_prefix='',\n cdata_key=k,\n process_namespaces=True,\n namespaces=AxirosACS.namespaces))\n return result\n\n @staticmethod\n def _parse_soap_response(response):\n \"\"\"Parse the ACS response and return a\\\n list of dictionary with {key,type,value} pair.\"\"\"\n if 'BFT_DEBUG' in os.environ:\n msg = xml.dom.minidom.parseString(response.text)\n print(msg.toprettyxml(indent=' ', newl=\"\"))\n\n result = AxirosACS._get_xml_key(response)\n if len(result) > 1:\n raise KeyError(\"More than 1 Result in reply not implemented yet\")\n result = result[0]\n httpcode = result['code']['text']\n msg = result['message']['text']\n http_error_message = \"HTTP Error code:\" + httpcode + \" \" + msg\n if httpcode != '200':\n # with 507 (timeout/expired) there seem to be NO faultcode message\n if httpcode == '500':\n if 'faultcode' not in result['message']['text']:\n raise HTTPError(http_error_message)\n else:\n raise HTTPError(http_error_message)\n\n # is this needed (might be overkill)?\n if not all([\n result.get('details'),\n result.get('message'),\n result.get('ticketid')\n ]):\n e = TR069ResponseError(\n 'ACS malformed response (issues with either '\n 'details/message/ticketid).')\n e.result = result # for inspection later\n raise e\n fault = 'faultcode' in msg\n if fault:\n # could there be more than 1 fault in a response?\n e = TR069FaultCode(msg)\n e.faultdict = \\\n ast.literal_eval(msg[msg.index('{'):])\n raise e\n # 'item' is not present in FactoryReset RPC response\n if 'item' in result['details']:\n return AxirosACS._parse_xml_response(result['details']['item'])\n elif 'ns1:KeyValueStruct[0]' in result['details'][\n 'http://schemas.xmlsoap.org/soap/encoding/:arrayType']:\n return []\n\n def _get_cmd_data(self, *args, **kwagrs):\n \"\"\"Return CmdOptTypeStruct_data. It is a helper method.\"\"\"\n c_opt_type = 'ns0:CommandOptionsTypeStruct'\n CmdOptTypeStruct_type = self.client.get_type(c_opt_type)\n CmdOptTypeStruct_data = CmdOptTypeStruct_type(*args, **kwagrs)\n return CmdOptTypeStruct_data\n\n def _get_class_data(self, *args, **kwagrs):\n \"\"\"Return CPEIdClassStruct_data. It is a helper method.\"\"\"\n cpe__id_type = 'ns0:CPEIdentifierClassStruct'\n CPEIdClassStruct_type = self.client.get_type(cpe__id_type)\n CPEIdClassStruct_data = CPEIdClassStruct_type(*args, **kwagrs)\n return CPEIdClassStruct_data\n\n def _get_pars_val_data(self, p_arr_type, *args, **kwargs):\n \"\"\"Return ParValsParsClassArray_data.It is a helper method.\"\"\"\n ParValsClassArray_type = self.client.get_type(p_arr_type)\n ParValsParsClassArray_data = ParValsClassArray_type(*args, **kwargs)\n return ParValsParsClassArray_data\n\n def _build_input_structs(self,\n cpeid,\n param,\n action,\n next_level=None,\n **kwargs):\n \"\"\"Helper function to create the get structs used in the get/set param values\n\n NOTE: The command option is set as Syncronous\n :param cpeid: the serial number of the modem through which ACS communication\n happens.\n :type cpeid: string\n :param param: parameter to used\n :type param: string or list of strings for get, dict or list of dict for set\n :param action: one of GPV/SPV/GPN/AO/DO/SI/REBOOT/DOWNLOAD\n :type action: string\n :param next_level: defaults to null takes True/False\n :type next_level: boolean\n :raises: NA\n :returns: param_data, cmd_data, cpeid_data\n \"\"\"\n if action == 'SPV':\n if type(param) is not list:\n param = [param]\n list_kv = []\n # this is a list of single k,v pairs\n for d in param:\n k = next(iter(d))\n list_kv.append({'key': k, 'value': d[k]})\n p_arr_type = 'ns0:SetParameterValuesParametersClassArray'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, list_kv)\n\n elif action == 'GPV':\n if type(param) is not list:\n param = [param]\n p_arr_type = 'ns0:GetParameterValuesParametersClassArray'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, param)\n\n elif action == 'SPA':\n if type(param) is not list:\n param = [param]\n list_kv = []\n for d in param:\n k = next(iter(d))\n list_kv.append({\n 'Name':\n k,\n 'Notification':\n d[k],\n 'AccessListChange':\n kwargs.get(\"access_param\", '0'),\n 'AccessList': {\n 'item': 'Subscriber'\n },\n 'NotificationChange':\n kwargs.get(\"notification_param\", '1')\n })\n p_arr_type = 'ns0:SetParameterAttributesParametersClassArray'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, list_kv)\n\n elif action == 'GPN':\n\n p_arr_type = 'ns0:GetParameterNamesArgumentsStruct'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, NextLevel=next_level, ParameterPath=param)\n\n elif action == 'GPA':\n if type(param) is not list:\n param = [param]\n p_arr_type = 'ns0:GetParameterAttributesParametersClassArray'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, param)\n\n elif action == \"SI\":\n if type(param) is not list:\n param = [param]\n p_arr_type = 'ns0:ScheduleInformArgumentsStruct'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, *param)\n\n elif action in ['AO', 'DO']:\n p_arr_type = 'ns0:AddDelObjectArgumentsStruct'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, param, '')\n\n elif action == \"REBOOT\":\n p_arr_type = 'xsd:string'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, param)\n\n elif action == \"DOWNLOAD\":\n p_arr_type = 'ns0:DownloadArgumentsStruct'\n ParValsParsClassArray_data = self._get_pars_val_data(\n p_arr_type, *param)\n\n else:\n raise CodeError('Invalid action: ' + action)\n\n CmdOptTypeStruct_data = self._get_cmd_data(\n Sync=True, Lifetime=AxirosACS.CPE_wait_time)\n\n CPEIdClassStruct_data = self._get_class_data(cpeid=cpeid)\n\n return ParValsParsClassArray_data,\\\n CmdOptTypeStruct_data,\\\n CPEIdClassStruct_data\n\n def close(self):\n \"\"\"Implement to close ACS connection. TODO.\"\"\"\n pass\n\n def get_ticketId(self, cpeid, param):\n \"\"\"ACS server maintain a ticket ID for all TR069 RPC calls.\n\n This method will contruct a TR069 GPV query, execute it and\n return the ticket id associated with it.\n\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param param: parameter to used\n :type param: string\n :raises: NA\n :returns: ticketid\n :rtype: string\n \"\"\"\n GetParameterValuesParametersClassArray_type = self.client.get_type(\n 'ns0:GetParameterValuesParametersClassArray')\n GetParameterValuesParametersClassArray_data = GetParameterValuesParametersClassArray_type(\n [param])\n\n CommandOptionsTypeStruct_type = self.client.get_type(\n 'ns0:CommandOptionsTypeStruct')\n CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type()\n\n CPEIdentifierClassStruct_type = self.client.get_type(\n 'ns0:CPEIdentifierClassStruct')\n CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type(\n cpeid=cpeid)\n\n # get raw soap response (parsing error with zeep)\n with self.client.settings(raw_response=True):\n response = self.client.service.GetParameterValues(\n GetParameterValuesParametersClassArray_data,\n CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data)\n\n ticketid = None\n root = ElementTree.fromstring(response.content)\n for value in root.iter('ticketid'):\n ticketid = value.text\n break\n return ticketid\n\n @moves.moved_method('GPV')\n def get(self, cpeid, param, wait=8):\n \"\"\"Perform a remote procedure call (GetParameterValue).\n\n This method is deprecated.\n The method will query the ACS server for value against ticket_id generated\n during the GPV RPC call.\n Example usage : acs_server.get(self.cpeid, 'Device.DeviceInfo.SoftwareVersion')\n\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param param: parameter to be used in get\n :type param: string\n :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8\n :type wait: int\n :raises: NA\n :returns: first value of ACS reponse for the parameter.\n :rtype: string\n \"\"\"\n try:\n return self.GPV(param)[0]['value']\n except Exception as e:\n print(e)\n return None\n\n @moves.moved_method('GPV')\n def getcurrent(self, cpeid, param, wait=8):\n \"\"\"Get the key, value of the response for the given parameter from board.\n\n Example usage : acs_server.getcurrent(self.cpeid, 'Device.IP.Interface.')\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param param: parameter to be used in get\n :type param: string\n :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8\n :type wait: int\n :raises: NA\n :returns: dictionary with the key, value of the response for the given parameter.\n :rtype: dict\n \"\"\"\n try:\n out = self.GPV(param)\n dict_key_value = {item['key']: item['value'] for item in out}\n return dict_key_value\n except Exception as e:\n print(e)\n return {}\n\n @moves.moved_method('SPV')\n def set(self, cpeid, attr, value):\n \"\"\"Set a parameter in board via TR069 RPC call (SetParameterValue).\n\n This method constructs a SPV query and sends it to ACS server\n ACS server will generate a ticket_id and perform the RPC call.\n The method will then return the value associated with the ticket_id\n Example usage : acs_server.set(self.cpeid, 'Device.WiFi.AccessPoint.1.AC.1.Alias', \"TestSSID\")\n\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param attr: attribute to be used to set\n :type attr: string\n :param values: the value to be set to the attr\n :type values: string\n :raises: NA\n :returns: ticketId for set.\n :rtype: string\n \"\"\"\n try:\n param = {}\n param[attr] = value\n return str(self.SPV(param))\n except Exception as e:\n print(e)\n return None\n\n def Axiros_GetListOfCPEs(self):\n \"\"\"Get the list of all devices registered on the ACS server.\n\n :raises: NA\n :returns: ACS response containing the list of CPE.\n :rtype: string\n \"\"\"\n CPESearchOptionsClassStruct_type = self.client.get_type(\n 'ns0:CPESearchOptionsClassStruct')\n CPESearchOptionsClassStruct_data = CPESearchOptionsClassStruct_type()\n\n CommandOptionsForCPESearchStruct_type = self.client.get_type(\n 'ns0:CommandOptionsForCPESearchStruct')\n CommandOptionsForCPESearchStruct_data = CommandOptionsForCPESearchStruct_type(\n )\n\n response = self.client.service.GetListOfCPEs(\n CPESearchOptionsClassStruct_data,\n CommandOptionsForCPESearchStruct_data)\n if response['code'] != 200:\n return None\n\n return response\n\n def Axiros_DeleteCPEs(self, cpeid):\n \"\"\"Delete a CPE on the ACS server.\n\n :raises: NA\n :returns: True if successful\n :rtype: True/False\n \"\"\"\n CPESearchOptionsClassStruct_type = self.client.get_type(\n 'ns0:CPESearchOptionsClassStruct')\n CPESearchOptionsClassStruct_data = CPESearchOptionsClassStruct_type(\n cpeid=cpeid)\n\n CommandOptionsForCPESearchStruct_type = self.client.get_type(\n 'ns0:CommandOptionsForCPESearchStruct')\n CommandOptionsForCPESearchStruct_data = CommandOptionsForCPESearchStruct_type(\n )\n\n response = self.client.service.DeleteCPEs(\n CPESearchOptionsClassStruct_data,\n CommandOptionsForCPESearchStruct_data)\n print(response)\n if response['code'] != 200:\n return False\n\n return True\n\n delete_cpe = Axiros_DeleteCPEs\n\n def Axiros_GetTicketResponse(self, ticketid):\n \"\"\"Get the ticket response on ACS.\n\n :param ticketid: the ticketid to be used to get the ACS response.\n :type ticketid: string\n :raises: NA\n :returns: ACS response.\n :rtype: string\n \"\"\"\n response = self.client.service.get_generic_sb_result(ticketid)\n\n if response['code'] != 200:\n return None\n\n return response['code']\n\n def Axiros_GetTicketValue(self, ticketid, wait=8, objtype=False):\n \"\"\"Get the text of ticket response on ACS.\n\n :param ticketid: the ticketid to be used to get the ACS response.\n :type ticketid: string\n :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8\n :type wait: int\n :param objtype: to get object's data type this flag must be true; defaults to false\n :type objtype: boolean\n :raises: ACSFaultCode\n :returns: ACS response text / None.\n :rtype: string/None\n \"\"\"\n for _ in range(wait):\n time.sleep(1)\n with self.client.settings(raw_response=True):\n ticket_resp = self.client.service.get_generic_sb_result(\n ticketid)\n\n root = ElementTree.fromstring(ticket_resp.content)\n for value in root.iter('code'):\n break\n if (value.text != '200'):\n for message in root.iter('message'):\n if message.text:\n if 'faultcode' in message.text:\n raise ACSFaultCode(message.text)\n break\n continue\n for value in root.iter('value'):\n if all([objtype, value.text]):\n for key, object_type in value.attrib.items():\n if 'type' in key:\n return object_type.split(\":\")[1]\n else:\n return value.text\n return None\n\n @tcp_dump\n def GPA(self, param):\n \"\"\"Get parameter attribute on ACS of the parameter specified i.e a remote procedure call (GetParameterAttribute).\n\n Example usage : acs_server.GPA('Device.WiFi.SSID.1.SSID')\n :param param: parameter to be used in get\n :type param: string\n :returns: dictionary with keys Name, AccessList, Notification indicating the GPA\n :rtype: dict\n \"\"\"\n\n # TO DO: ideally this should come off the environment helper\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param,\n action='GPA')\n\n with self.client.settings(raw_response=True):\n response = self.client.service.GetParameterAttributes(\n p, cmd, cpe_id)\n return AxirosACS._parse_soap_response(response)\n\n @moves.moved_method('GPA')\n def rpc_GetParameterAttributes(self, cpeid, param):\n \"\"\"Get parameter attribute on ACS of the parameter specified i.e a remote procedure call (GetParameterAttribute).\n\n Example usage : acs_server.rpc_GetParameterAttributes('DEAP815610DA', 'Device.WiFi.SSID.1.SSID')\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param param: parameter to be used in get\n :type param: string\n :raises: NA\n :returns: dictionary with keys Name, Notification (0/1), AccessList indicating the GPA\n :rtype: dict\n \"\"\"\n try:\n return self.GPA(param)\n\n except Exception as e:\n print(e)\n return {}\n\n @moves.moved_method('SPA')\n def rpc_SetParameterAttributes(self, cpeid, attr, value):\n \"\"\"Set parameter attribute on ACS of the parameter specified i.e a remote procedure call (SetParameterAttribute).\n\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param attr: attribute to be used to set\n :type attr: string\n :param values: the value to be set to the attr\n :type values: string\n :raises: NA\n :returns: ticket response on ACS.\n :rtype: string\n \"\"\"\n try:\n param = {}\n param[attr] = value\n return self.SPA(param)\n except Exception as e:\n print(e)\n return None\n\n @tcp_dump\n def SPA(self, param, **kwargs):\n \"\"\"Get parameter attribute on ACS of the parameter specified i.e a remote procedure call (GetParameterAttribute).\n\n Example usage : acs_server.SPA({'Device.WiFi.SSID.1.SSID':'1'}),could be parameter list of dicts/dict containing param name and notifications\n :param param: parameter to be used in set\n :type param: string\n :param kwargs : access_param,notification_param\n :returns: SPA response\n :rtype: dict\n \"\"\"\n\n # TO DO: ideally this should come off the environment helper\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param,\n action='SPA',\n **kwargs)\n\n with self.client.settings(raw_response=True):\n response = self.client.service.SetParameterAttributes(\n p, cmd, cpe_id)\n return AxirosACS._parse_soap_response(response)\n\n @moves.moved_method('AddObject')\n def rpc_AddObject(self, cpeid, param, wait=8):\n \"\"\"Add object ACS of the parameter specified i.e a remote procedure call (AddObject).\n\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param param: parameter to be used to add\n :type param: string\n :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8\n :type wait: integer, optional\n :raises assertion: rpc_AddObject failed to lookup for the param\n :returns: ticket response on ACS\n :rtype: dictionary\n \"\"\"\n return {i['key']: i['value'] for i in self.AddObject(param)}\n\n def AddObject(self, param):\n \"\"\"Add object ACS of the parameter specified i.e a remote procedure call (AddObject).\n\n :param param: parameter to be used to add\n :type param: string\n :raises assertion: On failure\n :returns: list of dictionary with key, value, type indicating the AddObject\n :rtype: dictionary\n \"\"\"\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param,\n action='AO')\n\n # get raw soap response\n with self.client.settings(raw_response=True):\n response = self.client.service.AddObject(p, cmd, cpe_id)\n\n return AxirosACS._parse_soap_response(response)\n\n @moves.moved_method('DelObject')\n def rpc_DelObject(self, cpeid, param):\n \"\"\"Delete object ACS of the parameter specified i.e a remote procedure call (DeleteObject).\n\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param param: parameter to be used to delete\n :type param: string\n :returns: ticket response on ACS ('0' is returned)\n :rtype: string\n \"\"\"\n return str(self.DelObject(param)[0]['value'])\n\n def DelObject(self, param):\n \"\"\"Delete object ACS of the parameter specified i.e a remote procedure call (DeleteObject).\n\n :param param: parameter to be used to delete\n :type param: string\n :returns: list of dictionary with key, value, type indicating the DelObject\n :rtype: string\n \"\"\"\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param,\n action='DO')\n\n # get raw soap response\n with self.client.settings(raw_response=True):\n response = self.client.service.DeleteObject(p, cmd, cpe_id)\n\n return AxirosACS._parse_soap_response(response)\n\n def Read_Log_Message(self, cpeid, wait=8):\n \"\"\"Read ACS log messages.\n\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8\n :type wait: integer, optional\n :returns: ticket response on ACS(Log message)\n :rtype: dictionary\n \"\"\"\n CommandOptionsTypeStruct_type = self.client.get_type(\n 'ns0:CommandOptionsForCPELogStruct')\n CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type()\n\n CPEIdentifierClassStruct_type = self.client.get_type(\n 'ns0:CPEIdentifierClassStruct')\n CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type(\n cpeid=cpeid)\n\n # get raw soap response (parsing error with zeep)\n with self.client.settings(raw_response=True):\n response = self.client.service.GetLogMessagesOfCPE(\n CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data)\n\n for _ in range(wait):\n time.sleep(1)\n root = ElementTree.fromstring(response.content)\n for value in root.iter('code'):\n break\n if (value.text != '200'):\n continue\n dict_value1 = {}\n num = 1\n for key, value in zip(root.iter('ts'), root.iter('message')):\n dict_value = {}\n dict_value['time'] = key.text\n dict_value['msg'] = value.text\n dict_value1['log_msg' + str(num)] = dict_value\n num += 1\n return dict_value1\n return None\n\n def Del_Log_Message(self, cpeid, wait=8):\n \"\"\"Delete ACS log messages.\n\n :param cpeid: the serial number of the modem through which ACS communication happens.\n :type cpeid: string\n :param wait: the number of tries to be done if we are not getting proper ACS response, defaults to 8\n :type wait: integer, optional\n :returns: True or None\n :rtype: Boolean\n \"\"\"\n CPEIdentifierClassStruct_type = self.client.get_type(\n 'ns0:CPEIdentifierClassStruct')\n CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type(\n cpeid=cpeid)\n\n # get raw soap response (parsing error with zeep)\n with self.client.settings(raw_response=True):\n response = self.client.service.DeleteLogMessagesOfCPE(\n CPEIdentifierClassStruct_data)\n\n for _ in range(wait):\n time.sleep(1)\n root = ElementTree.fromstring(response.content)\n for value in root.iter('code'):\n break\n if (value.text == '200'):\n return True\n else:\n continue\n return None\n\n @tcp_dump\n def GPV(self, param):\n \"\"\"Get value from CM by ACS for a single given parameter key path synchronously.\n\n :param param: path to the key that assigned value will be retrieved\n :return: value as a dictionary\n \"\"\"\n # TO DO: ideally this should come off the environment helper\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param,\n action='GPV')\n\n val = 0\n while val <= 1:\n try:\n with self.client.settings(raw_response=True):\n response = self.client.service.GetParameterValues(\n p, cmd, cpe_id)\n return AxirosACS._parse_soap_response(response)\n except HTTPError as e:\n if \"507\" not in str(e):\n raise (e)\n else:\n # adding 10 sec timeout\n warnings.warn(\n \"Ten seconds of timeout is added to compensate DOS attack.\"\n )\n self.expect(pexpect.TIMEOUT, timeout=10)\n if val == 1:\n raise (e)\n val += 1\n\n @tcp_dump\n def SPV(self, param_value):\n \"\"\"Modify the value of one or more CPE Parameters.\n\n It can take a single k,v pair or a list of k,v pairs.\n :param param_value: dictionary that contains the path to the key and\n the value to be set. E.g. {'Device.WiFi.AccessPoint.1.AC.1.Alias':'mok_1'}\n :return: status of the SPV as int (0/1)\n :raises: TR069ResponseError if the status is not (0/1)\n \"\"\"\n # TO DO: ideally this should come off the environment helper\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param_value,\n action='SPV')\n\n val = 0\n while val <= 1:\n try:\n with self.client.settings(raw_response=True):\n response = self.client.service.SetParameterValues(\n p, cmd, cpe_id)\n result = AxirosACS._parse_soap_response(response)\n break\n except HTTPError as e:\n if \"507\" not in str(e):\n raise (e)\n else:\n # adding 10 sec timeout\n warnings.warn(\n \"Ten seconds of timeout is added to compensate DOS attack.\"\n )\n self.expect(pexpect.TIMEOUT, timeout=10)\n if val == 1:\n raise (e)\n val += 1\n status = int(result[0]['value'])\n if status not in [0, 1]:\n raise TR069ResponseError(\"SPV Invalid status: \" + str(status))\n return status\n\n @tcp_dump\n def GPN(self, param, next_level):\n \"\"\"This method is used to discover the Parameters accessible on a particular CPE\n\n :param param: parameter to be discovered\n :type param: string\n :next_level: displays the next level children of the object if marked true\n :type next_level: boolean\n :return: value as a dictionary\n \"\"\"\n\n # TO DO: ideally this should come off the environment helper\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param,\n action='GPN',\n next_level=next_level)\n\n with self.client.settings(raw_response=True):\n response = self.client.service.GetParameterNames(p, cmd, cpe_id)\n return AxirosACS._parse_soap_response(response)\n\n def FactoryReset(self):\n \"\"\"Execute FactoryReset RPC.\n\n Returns true if FactoryReset request is initiated.\n Note: This method only informs if the FactoryReset request initiated or not.\n The wait for the Reeboot of the device has to be handled in the test.\n\n :return: returns factory reset response\n \"\"\"\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n CmdOptTypeStruct_data = self._get_cmd_data(Sync=True, Lifetime=20)\n CPEIdClassStruct_data = self._get_class_data(cpeid=self.cpeid)\n\n with self.client.settings(raw_response=True):\n response = self.client.service.FactoryReset(\n CommandOptions=CmdOptTypeStruct_data,\n CPEIdentifier=CPEIdClassStruct_data)\n return AxirosACS._parse_soap_response(response)\n\n def connectivity_check(self, cpeid):\n \"\"\"Check the connectivity between the ACS and the DUT by\\\n requesting the DUT to perform a schedule inform.\n\n NOTE: The scope of this method is to verify that the ACS and DUT can\n communicate with eachother!\n\n :param cpeid: the id to use for the ping\n :param type: string\n\n :return: True for a successful ScheduleInform, False otherwise\n \"\"\"\n old_cpeid = self.cpeid\n self.cpeid = cpeid\n r = True\n try:\n self.ScheduleInform(DelaySeconds=1)\n except Exception as e:\n # on ANY exception assume ScheduleInform failed-> comms failed\n print(e)\n print(f\"connectivity_check failed for {cpeid}\")\n r = False\n self.cpeid = old_cpeid\n return r\n\n def ScheduleInform(self, CommandKey='Test', DelaySeconds=20):\n \"\"\"Execute ScheduleInform RPC\n\n :param commandKey: the string paramenter passed to scheduleInform\n :param type: string\n :param DelaySecond: delay of seconds in integer\n :param type: integer\n\n :return: returns ScheduleInform response\n \"\"\"\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n param = [CommandKey, DelaySeconds]\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param,\n action='SI')\n\n with self.client.settings(raw_response=True):\n response = self.client.service.ScheduleInform(CommandOptions=cmd,\n CPEIdentifier=cpe_id,\n Parameters=p)\n\n return AxirosACS._parse_soap_response(response)\n\n def Reboot(self, CommandKey=\"Reboot Test\"):\n \"\"\"Execute Reboot.\n\n Returns true if Reboot request is initiated.\n\n :return: returns reboot RPC response\n \"\"\"\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n CommandKey,\n action='REBOOT')\n\n with self.client.settings(raw_response=True):\n response = self.client.service.Reboot(CommandOptions=cmd,\n CPEIdentifier=cpe_id,\n Parameters=p)\n\n return AxirosACS._parse_soap_response(response)\n\n def GetRPCMethods(self):\n \"\"\"Execute GetRPCMethods RPC.\n\n :return: returns GetRPCMethods response of supported functions\n \"\"\"\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n CmdOptTypeStruct_data = self._get_cmd_data(Sync=True, Lifetime=20)\n CPEIdClassStruct_data = self._get_class_data(cpeid=self.cpeid)\n\n with self.client.settings(raw_response=True):\n response = self.client.service.GetRPCMethods(\n CommandOptions=CmdOptTypeStruct_data,\n CPEIdentifier=CPEIdClassStruct_data)\n return AxirosACS._parse_soap_response(response)\n\n def Download(self,\n URL,\n FileType=\"1 Firmware Upgrade Image\",\n TargetFileName=\"\",\n FileSize=200,\n Username=\"\",\n Password=\"\",\n CommandKey=\"\",\n DelaySeconds=10,\n SuccessURL=\"\",\n FailureURL=\"\"):\n \"\"\"Execute Download RPC.\n\n :param URL: URL to download file\n :param type: string\n :param FileType: the string paramenter from following 6 values only\n [\"1 Firmware Upgrade Image\", \"2 Web Content\",\n \"3 Vendor Configuration File\", \"4 Tone File\",\n \"5 Ringer File\", \"6 Stored Firmware Image\" ]\n default=\"3 Vendor Configuration File\"\n :param type: string\n :param TargetFileName: TargetFileName to download through RPC\n :param type: string\n :param FileSize: the size of file to download in bytes\n :param type: integer\n :param Username: User to authenticate with file Server. Default=\"\"\n :param type: string\n :param Password: Password to authenticate with file Server. Default=\"\"\n :param type: string\n :param CommandKey: the string paramenter passed in Download API\n :param type: string\n :param DelaySeconds: delay of seconds in integer\n :param type: integer\n :param SuccessURL: URL to access in case of Download API execution succeeded\n :param type: string\n :param FailureURL: URL to access in case of Download API execution Failed\n :param type: string\n\n :return: returns Download response\n \"\"\"\n if self.cpeid is None:\n self.cpeid = self.dev.board._cpeid\n\n param = [\n CommandKey, DelaySeconds, FailureURL, FileSize, FileType, Password,\n SuccessURL, TargetFileName, URL, Username\n ]\n p, cmd, cpe_id = self._build_input_structs(self.cpeid,\n param,\n action='DOWNLOAD')\n\n with self.client.settings(raw_response=True):\n response = self.client.service.Download(CommandOptions=cmd,\n CPEIdentifier=cpe_id,\n Parameters=p)\n return AxirosACS._parse_soap_response(response)\n\n\nif __name__ == '__main__':\n from pprint import pprint\n import sys\n \"\"\"Good values to test:\n Device.DeviceInfo.ModelNumber\n Device.DeviceInfo.SoftwareVersion\n Device.DeviceInfo.Processor\n\n NOTE: big queries may timeout\n\n To use from cmdline change:\n from . import base_acs\n to:\n from boardfarm.devices import base_acs\n\n some cmd line samples (user/passwd from json serial no from ACS gui):\n\n # this must work\n python3 ./axiros_acs.py ip:port user passwd serialno GVP \"'Device.DeviceInfo.ModelNumber'\"\n\n # this must fail\n python3 ./axiros_acs.py ip:port user passwd serailno GVP \"'Device.DeviceInfo.ModelNumber1'\"\n\n # this must fail\n python3 ./axiros_acs.py ip:port user passwd serialno SVP \"{'Device.DeviceInfo.ModelNumber':'mik'}\"\n\n # this should work\n python3 ./axiros_acs.py ip:port user passwod serialno SVP \"[{'Device.WiFi.AccessPoint.1.AC.1.Alias':'mok_1'}, {'Device.WiFi.AccessPoint.2.AC.1.Alias':'mik_2'}]\"\n\n # this must fail\n python3 ./axiros_acs.py ip:port user passwd serialno SVP \"[{'Device.WiFi.AccessPoint.1.AC.1.Alias':'mok_1'}, {'Device.WiFi.AccessPoint.2.AC.1.Alias':2}]\"\n \"\"\"\n\n if len(sys.argv) < 3:\n print(\"Usage:\")\n print(\n '\\tpython3 axiros_acs.py ip:port \"\\'\\'\" NOTE: the quotes are importand'\n )\n print(\n '\\tpython3 axiros_acs.py ip:port \"\\'Device.DeviceInfo.SoftwareVersion.\\']\"'\n )\n print(\n '\\tpython3 axiros_acs.py ip:port \"[\\'Device.DeviceInfo.ModelNumber\\', \\'Device.DeviceInfo.SoftwareVersion.\\']'\n )\n sys.exit(1)\n\n if ':' in sys.argv[1]:\n ip = sys.argv[1].split(':')[0]\n port = sys.argv[1].split(':')[1]\n else:\n ip = sys.argv[1]\n port = 80\n\n if len(sys.argv) > 4:\n cpe_id = sys.argv[4]\n print(\"Using CPEID: {}\".format(cpe_id))\n else:\n print('Error: missing cpeid')\n sys.exit(1)\n\n acs = AxirosACS(ipaddr=ip,\n port=port,\n username=sys.argv[2],\n password=sys.argv[3],\n cpeid=cpe_id)\n\n action = acs.SPV if sys.argv[5] == 'SPV' else acs.GPV\n\n param = 'Device.DeviceInfo.SoftwareVersion.'\n if len(sys.argv) > 6:\n param = ast.literal_eval(sys.argv[6])\n\n acs.Axiros_GetListOfCPEs()\n try:\n ret = action(param)\n pprint(ret)\n except TR069FaultCode as fault:\n print('==== Received TR069FaultCode exception:====')\n pprint(fault.faultdict)\n print('=========================================')\n raise\n except Exception as e:\n print('==== Received UNEXPECTED exception:======')\n pprint(e)\n print('=========================================')\n raise\n","sub_path":"boardfarm/devices/axiros_acs.py","file_name":"axiros_acs.py","file_ext":"py","file_size_in_byte":47105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"172122775","text":"from random import randrange\r\n\r\nsoucet = 0\r\nwhile soucet < 21:\r\n print('Máš', soucet, 'bodů')\r\n odpoved = input('Otočit kartu? ')\r\n if odpoved == 'ano':\r\n karta = randrange(2, 11)\r\n print('Otočil/a jsi', karta)\r\n soucet = soucet + karta\r\n elif odpoved == 'ne':\r\n break\r\n else:\r\n print('Nerozumím! Odpovídej \"ano\", nebo \"ne\"')\r\n\r\nif soucet == 21:\r\n print('Gratuluji! Vyhrál/a jsi!')\r\nelif soucet > 21:\r\n print('Smůla!', soucet, 'bodů je moc!')\r\nelse:\r\n print('Chybělo jen', 21 - soucet, 'bodů!')","sub_path":"okobere.py","file_name":"okobere.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"388455990","text":"# -*- coding: utf-8 -*-\n\"\"\"Selectors for various common page components\"\"\"\nimport copy\n\nfrom great_magna_tests_shared.constants import (\n MD5_CHECKSUM_EIG_LOGO,\n MD5_CHECKSUM_EVENTS_BIG_FOOTER_LOGO,\n MD5_CHECKSUM_EVENTS_BIG_HEADER_LOGO,\n MD5_CHECKSUM_GREAT_LOGO,\n MD5_CHECKSUM_INVEST_IN_GREAT,\n)\nfrom browserpages import ElementType\nfrom browserpages.common_actions import By, Selector\n\nDOMESTIC_HERO_WITH_LINK = {\n \"hero\": {\n \"hero banner\": Selector(By.ID, \"hero\"),\n \"title\": Selector(By.CSS_SELECTOR, \"#hero h1\"),\n \"view export market guides\": Selector(\n By.CSS_SELECTOR, \"#hero a\", type=ElementType.LINK\n ),\n }\n}\nDOMESTIC_HERO_WO_LINK = {\n \"hero\": {\n \"hero banner\": Selector(By.ID, \"hero\"),\n \"title\": Selector(By.CSS_SELECTOR, \"#hero h1\"),\n }\n}\n\nDOMESTIC_HEADER = {\n \"header\": {\n # cookie notice\n \"itself\": Selector(By.ID, \"header-cookie-notice\", is_visible=False),\n \"find out more about cookies\": Selector(\n By.CSS_SELECTOR, \"#header-cookie-notice a\", is_visible=False\n ),\n # global header\n \"global header\": Selector(By.ID, \"great-global-header\"),\n \"great global logo\": Selector(By.ID, \"great-global-header-logo\"),\n \"for uk businesses\": Selector(By.ID, \"great-global-header-domestic-link\"),\n \"for international businesses\": Selector(\n By.ID, \"great-global-header-international-link\"\n ),\n # header menu\n \"header menu\": Selector(By.CSS_SELECTOR, \".menu\"),\n \"invest in great logo\": Selector(By.ID, \"great-header-logo\"),\n \"advice\": Selector(By.ID, \"header-advice\", type=ElementType.LINK),\n \"markets\": Selector(By.ID, \"header-markets\", type=ElementType.LINK),\n \"services\": Selector(By.ID, \"header-services\", type=ElementType.LINK),\n \"search box\": Selector(\n By.ID, \"great-header-search-box\", type=ElementType.INPUT\n ),\n \"search button\": Selector(\n By.CSS_SELECTOR,\n \"#great-header-search-box ~ button\",\n type=ElementType.BUTTON,\n ),\n }\n}\nCOOKIE_BANNER = {\n \"cookie banner\": {\n \"banner\": Selector(\n By.CSS_SELECTOR, \"div[aria-label='Cookies consent manager']\"\n ),\n \"accept all cookies\": Selector(\n By.CSS_SELECTOR,\n \"body > div.ReactModalPortal a[href='#']\",\n type=ElementType.LINK,\n ),\n \"reject all cookies\": Selector(\n By.CSS_SELECTOR,\n \"body > div.ReactModalPortal a.button[href$='cookies/']\",\n type=ElementType.LINK,\n ),\n }\n}\nSSO_LOGGED_OUT = {\n \"sso links - logged out\": {\n \"sign in\": Selector(By.ID, \"header-sign-in-link\", is_visible=False)\n }\n}\n\nBETA_BAR = {\n \"beta bar\": {\n \"itself\": Selector(By.ID, \"header-beta-bar\"),\n \"badge\": Selector(By.CSS_SELECTOR, \"#header-beta-bar .phase-tag\"),\n \"message\": Selector(By.CSS_SELECTOR, \"#header-beta-bar span\"),\n \"link\": Selector(By.CSS_SELECTOR, \"#header-beta-bar a\"),\n }\n}\n\nBREADCRUMBS = {\n \"breadcrumbs\": {\n \"itself\": Selector(By.CSS_SELECTOR, \".breadcrumbs\"),\n \"current page\": Selector(\n By.CSS_SELECTOR, \".breadcrumbs li[aria-current='page']\"\n ),\n \"links\": Selector(By.CSS_SELECTOR, \".breadcrumbs a\"),\n }\n}\n\nERROR_REPORTING = {\n \"error reporting\": {\n \"itself\": Selector(By.CSS_SELECTOR, \"section.error-reporting\"),\n \"report a problem with the page\": Selector(\n By.ID, \"error-reporting-section-contact-us\"\n ),\n }\n}\n\nDOMESTIC_FOOTER = {\n \"footer\": {\n \"great footer logo\": Selector(By.ID, \"great-footer-great-logo\"),\n \"contact us\": Selector(By.ID, \"footer-contact\"),\n \"privacy and cookies\": Selector(By.ID, \"footer-privacy-and-cookies\"),\n \"terms and conditions\": Selector(By.ID, \"footer-terms-and-conditions\"),\n \"performance\": Selector(By.ID, \"footer-performance\"),\n \"department for international trade on gov.uk\": Selector(By.ID, \"footer-dit\"),\n \"go to the page for international businesses\": Selector(\n By.ID, \"footer-international\"\n ),\n \"dit footer logo\": Selector(By.ID, \"great-global-footer-logo\"),\n \"copyright notice\": Selector(By.ID, \"great-footer-copyright\"),\n }\n}\n\nFAVICON = Selector(By.CSS_SELECTOR, \"link[rel='shortcut icon']\")\nEXOPPS_FAVICON = Selector(By.CSS_SELECTOR, \"link[rel='icon']\")\nEIG_LOGO = Selector(By.CSS_SELECTOR, \"#great-header-logo > img\")\nSIGN_IN_LINK = Selector(By.ID, \"header-sign-in-link\")\n\nLOGOS = {\n \"eig\": {\"selector\": EIG_LOGO, \"md5\": MD5_CHECKSUM_EIG_LOGO},\n \"great - header\": {\n \"selector\": Selector(By.CSS_SELECTOR, \"#great-header-logo img\"),\n \"md5\": MD5_CHECKSUM_GREAT_LOGO,\n },\n \"great - footer\": {\n \"selector\": Selector(By.ID, \"great-footer-great-logo\"),\n \"md5\": MD5_CHECKSUM_GREAT_LOGO,\n },\n \"invest in great - header\": {\n \"selector\": Selector(By.CSS_SELECTOR, \"#great-header-logo img\"),\n \"md5\": MD5_CHECKSUM_INVEST_IN_GREAT,\n },\n \"events business is great - header\": {\n \"selector\": Selector(By.CSS_SELECTOR, \"header img\"),\n \"md5\": MD5_CHECKSUM_EVENTS_BIG_HEADER_LOGO,\n },\n \"events business is great - footer\": {\n \"selector\": Selector(By.CSS_SELECTOR, \"#footer_section img\"),\n \"md5\": MD5_CHECKSUM_EVENTS_BIG_FOOTER_LOGO,\n },\n}\n","sub_path":"tests/smoke/browserpages/common_selectors.py","file_name":"common_selectors.py","file_ext":"py","file_size_in_byte":5454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"376615627","text":"from lstudio.common.views import JSONResponseMixin\nfrom django.views.generic import TemplateView\nfrom .forms import ReviewForm, ImageReviewForm\nfrom lstudio.emailing.jobs import send_review_nofitication\nfrom lstudio.common.util import get_client_ip\nfrom sorl.thumbnail import get_thumbnail\nfrom .models import Review, check_spam\nfrom django.utils.translation import ugettext as _\nfrom lstudio.common.views import ContentPlaceholderLoaderMixin\n\n\nclass ReviewView(TemplateView, JSONResponseMixin, ContentPlaceholderLoaderMixin):\n model = Review\n http_method_names = ['post']\n\n def post(self, request, *args, **kwargs):\n # first we send an image, and then if image is correct\n # save review instance with image and return review's pk and token\n # to save other data\n only_image = request.GET.get('only_image')\n\n if only_image:\n form = ImageReviewForm(request.POST, request.FILES)\n if form.is_valid():\n form.instance.ip = get_client_ip(request)\n review = form.save()\n thumbnail = get_thumbnail(review.image, '105x105', crop='center')\n resp = {'status': 'ok',\n 'image': \"\".format(thumbnail.url),\n 'save_token': form.instance.save_token}\n else:\n resp = {'status': 'error', 'errors': form.errors}\n\n else:\n save_token = request.POST.get('save_token')\n if not save_token:\n resp = {'status': 'error', 'errors': {'image': _('Image is required')}}\n else:\n try:\n # get object by save_token\n obj = Review.objects.get(save_token=save_token, text__isnull=True)\n form = ReviewForm(request.POST, request.FILES, instance=obj)\n if form.is_valid():\n form.instance.spam = check_spam(form.cleaned_data.get('text'), obj.ip)\n review = form.save()\n if not review.spam:\n send_review_nofitication(review)\n resp = {'status': 'ok'}\n else:\n resp = {'status': 'error', 'errors': form.errors}\n\n except Review.DoesNotExist:\n resp = {'status': 'error', 'errors': {'server': _('Something went wrong')}}\n return self.render_to_json_response(resp)\n","sub_path":"lstudio/reviews/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"344826412","text":"import discord\r\nfrom discord.ext.commands import Bot\r\nfrom urllib.parse import urlencode\r\nimport secrets\r\nimport aiohttp\r\nimport asyncio\r\nimport time\r\nimport os\r\nimport sys\r\nimport random\r\n\r\n\r\nbob_the_builder = Bot(command_prefix=\"!\")\r\n\r\n@bob_the_builder.event\r\nasync def on_read():\r\n print('Client logged in')\r\n\r\n#bobnr1\r\n@bob_the_builder.command()\r\nasync def bob(*args):\r\n return await bob_the_builder.say(\"Who is Bob, you ask? Bob is the greatest human being ever conceived.\")\r\n\r\n#bless \r\n@bob_the_builder.command()\r\nasync def bless(*args):\r\n return await bob_the_builder.say(\":sparkles: You have been blessed by Bob\")\r\n\r\n#youtube \r\n@bob_the_builder.command()\r\nasync def youtube(*args):\r\n print(args)\r\n url = (\"https://www.youtube.com/results?{}\".format(urlencode({'search_query': ' '.join(args)}))) \r\n return await bob_the_builder.say(\"Got'em! Here are your results : \\n \\n %s\" % url)\r\n\r\n#rng \r\n@bob_the_builder.command(pass_context=True)\r\nasync def blessrng(ctx):\r\n x = random.randint(1, 100)\r\n await bob_the_builder.send_message(ctx.message.channel, \"<:BlessRNG:403833576313061387>\\n \\n\" + \"RNGesus gives you a \" + \"__**\" + str(x) + \"**__\")\r\n\r\n#random map drop \r\n@bob_the_builder.command()\r\nasync def drop(*args):\r\n drop = ['school :school:', 'roz :house:', 'pochinki(mah city):homes: ', 'prison :cop: ', 'mylta :house_abandoned:', 'primo :house_with_garden:', '*pick* :map:']\r\n return await bob_the_builder.say(\"__**\" + random.choice(drop) + \"**__\")\r\n\r\n#flip \r\n@bob_the_builder.command()\r\nasync def flip(*args):\r\n drop = ['Yes :ok_hand::skin-tone-2:','No <:DansGame:259203114207412224>']\r\n return await bob_the_builder.say(\":crystal_ball:\\n \\n\" + \"__**\" + random.choice(drop) + \"**__\")\r\n\r\n\r\nbob_the_builder.run(secrets.BOT_TOKEN)\r\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570598634","text":"# entry point for deepforest model\nimport os\nimport pandas as pd\nfrom skimage import io\nimport torch\n\nimport pytorch_lightning as pl\nfrom torch import optim\nimport matplotlib\n\nfrom deepforest import utilities\nfrom deepforest import dataset\nfrom deepforest import get_data\nfrom deepforest import model\nfrom deepforest import predict\nfrom deepforest import evaluate as evaluate_iou\n\n\nclass deepforest(pl.LightningModule):\n \"\"\"Class for training and predicting tree crowns in RGB images\n \"\"\"\n\n def __init__(self, num_classes=1, label_dict = {\"Tree\":0}):\n \"\"\"\n Args:\n num_classes (int): number of classes in the model\n Returns:\n self: a deepforest pytorch ligthning module\n \"\"\"\n super().__init__()\n \n # Read config file - if a config file exists in local dir use it,\n # if not use installed.\n if os.path.exists(\"deepforest_config.yml\"):\n config_path = \"deepforest_config.yml\"\n else:\n try:\n config_path = get_data(\"deepforest_config.yml\")\n except Exception as e:\n raise ValueError(\n \"No deepforest_config.yml found either in local \"\n \"directory or in installed package location. {}\".format(e))\n\n print(\"Reading config file: {}\".format(config_path))\n self.config = utilities.read_config(config_path)\n\n # release version id to flag if release is being used\n self.__release_version__ = None\n\n self.num_classes = num_classes\n self.create_model()\n \n #Label encoder and decoder\n if not len(label_dict) == num_classes:\n raise ValueError(\"label_dict {} does not match requested number of classes {}, please supply a label_dict argument {'label1':0, 'label2':1, 'label3':2 ... etc} for each label in the dataset\".format(label_dict, num_classes))\n \n self.label_dict = label_dict\n self.numeric_to_label_dict = {v: k for k, v in label_dict.items()}\n\n def use_release(self):\n \"\"\"Use the latest DeepForest model release from github and load model.\n Optionally download if release doesn't exist.\n Returns:\n model (object): A trained keras model\n \"\"\"\n # Download latest model from github release\n release_tag, self.release_state_dict = utilities.use_release()\n self.model.load_state_dict(\n torch.load(self.release_state_dict, map_location=self.device))\n\n # load saved model and tag release\n self.__release_version__ = release_tag\n print(\"Loading pre-built model: {}\".format(release_tag))\n\n def create_model(self):\n \"\"\"Define a deepforest retinanet architecture\"\"\"\n self.model = model.create_model(self.num_classes, self.config[\"nms_thresh\"],\n self.config[\"score_thresh\"])\n\n def create_trainer(self, logger=None, callbacks=None, **kwargs):\n \"\"\"Create a pytorch ligthning training by reading config files\n Args:\n callbacks (list): a list of pytorch-lightning callback classes\n \"\"\"\n\n self.trainer = pl.Trainer(logger=logger,\n max_epochs=self.config[\"train\"][\"epochs\"],\n gpus=self.config[\"gpus\"],\n checkpoint_callback=False,\n distributed_backend=self.config[\"distributed_backend\"],\n fast_dev_run=self.config[\"train\"][\"fast_dev_run\"],\n callbacks=callbacks,\n **kwargs)\n\n def save_model(self, path):\n \"\"\"\n Save the trainer checkpoint in user defined path, in order to access in future\n Args:\n Path: the path located the model checkpoint\n\n \"\"\"\n self.trainer.save_checkpoint(path)\n\n def load_dataset(self,\n csv_file,\n root_dir=None,\n augment=False,\n shuffle=True,\n batch_size=1):\n \"\"\"Create a tree dataset for inference\n Csv file format is .csv file with the columns \"image_path\", \"xmin\",\"ymin\",\"xmax\",\"ymax\" for the image name and bounding box position.\n Image_path is the relative filename, not absolute path, which is in the root_dir directory. One bounding box per line.\n\n Args:\n csv_file: path to csv file\n root_dir: directory of images. If none, uses \"image_dir\" in config\n augment: Whether to create a training dataset, this activates data augmentations\n Returns:\n ds: a pytorch dataset\n \"\"\"\n\n ds = dataset.TreeDataset(csv_file=csv_file,\n root_dir=root_dir,\n transforms=dataset.get_transform(augment=augment),\n label_dict=self.label_dict)\n\n data_loader = torch.utils.data.DataLoader(\n ds,\n batch_size=batch_size,\n shuffle=shuffle,\n collate_fn=utilities.collate_fn,\n num_workers=self.config[\"workers\"],\n )\n\n return data_loader\n\n def train_dataloader(self):\n \"\"\"\n Train loader using the configurations\n Returns: loader\n\n \"\"\"\n loader = self.load_dataset(csv_file=self.config[\"train\"][\"csv_file\"],\n root_dir=self.config[\"train\"][\"root_dir\"],\n augment=True,\n shuffle=True,\n batch_size=self.config[\"batch_size\"])\n\n return loader\n\n def val_dataloader(self):\n \"\"\"\n Create a val data loader only if specified in config\n Returns: loader or None\n\n \"\"\"\n loader = None\n if self.config[\"validation\"][\"csv_file\"] is not None:\n loader = self.load_dataset(csv_file=self.config[\"validation\"][\"csv_file\"],\n root_dir=self.config[\"validation\"][\"root_dir\"],\n augment=False,\n shuffle=False,\n batch_size=self.config[\"batch_size\"])\n\n return loader\n\n def predict_image(self, image=None, path=None, return_plot=False):\n \"\"\"Predict an image with a deepforest model\n\n Args:\n image: a numpy array of a RGB image ranged from 0-255\n path: optional path to read image from disk instead of passing image arg\n return_plot: Return image with plotted detections\n Returns:\n boxes: A pandas dataframe of predictions (Default)\n img: The input with predictions overlaid (Optional)\n \"\"\"\n if isinstance(image, str):\n raise ValueError(\n \"Path provided instead of image. If you want to predict an image from disk, is path =\"\n )\n\n if path:\n if not isinstance(path, str):\n raise ValueError(\"Path expects a string path to image on disk\")\n image = io.imread(path)\n\n # Load on GPU is available\n if torch.cuda.is_available:\n self.model.to(self.device)\n\n self.model.eval()\n\n # Check if GPU is available and pass image to gpu\n result = predict.predict_image(model=self.model,\n image=image,\n return_plot=return_plot,\n device=self.device,\n iou_threshold=self.config[\"nms_thresh\"])\n \n #Set labels to character from numeric if returning boxes df\n if not return_plot:\n if not result is None:\n result[\"label\"] = result.label.apply(lambda x: self.numeric_to_label_dict[x])\n \n return result\n\n def predict_file(self, csv_file, root_dir, savedir=None):\n \"\"\"Create a dataset and predict entire annotation file\n\n Csv file format is .csv file with the columns \"image_path\", \"xmin\",\"ymin\",\"xmax\",\"ymax\" for the image name and bounding box position.\n Image_path is the relative filename, not absolute path, which is in the root_dir directory. One bounding box per line.\n\n Args:\n csv_file: path to csv file\n root_dir: directory of images. If none, uses \"image_dir\" in config\n savedir: Optional. Directory to save image plots.\n Returns:\n df: pandas dataframe with bounding boxes, label and scores for each image in the csv file\n \"\"\"\n self.model.eval()\n result = predict.predict_file(model=self.model,\n csv_file=csv_file,\n root_dir=root_dir,\n savedir=savedir,\n device=self.device,\n iou_threshold=self.config[\"nms_thresh\"])\n\n #Set labels to character from numeric\n result[\"label\"] = result.label.apply(lambda x: self.numeric_to_label_dict[x])\n \n return result\n\n def predict_tile(self,\n raster_path=None,\n image=None,\n patch_size=400,\n patch_overlap=0.05,\n iou_threshold=0.15,\n return_plot=False,\n use_soft_nms=False,\n sigma=0.5,\n thresh=0.001):\n \"\"\"For images too large to input into the model, predict_tile cuts the\n image into overlapping windows, predicts trees on each window and\n reassambles into a single array.\n\n Args:\n raster_path: Path to image on disk\n image (array): Numpy image array in BGR channel order\n following openCV convention\n patch_size: patch size default400,\n patch_overlap: patch overlap default 0.15,\n iou_threshold: Minimum iou overlap among predictions between\n windows to be suppressed. Defaults to 0.5.\n Lower values suppress more boxes at edges.\n return_plot: Should the image be returned with the predictions drawn?\n use_soft_nms: whether to perform Gaussian Soft NMS or not, if false, default perform NMS.\n sigma: variance of Gaussian function used in Gaussian Soft NMS\n thresh: the score thresh used to filter bboxes after soft-nms performed\n\n Returns:\n boxes (array): if return_plot, an image.\n Otherwise a numpy array of predicted bounding boxes, scores and labels\n \"\"\"\n\n self.model.eval()\n\n result = predict.predict_tile(model=self.model,\n raster_path=raster_path,\n image=image,\n patch_size=patch_size,\n patch_overlap=patch_overlap,\n iou_threshold=iou_threshold,\n return_plot=return_plot,\n use_soft_nms=use_soft_nms,\n sigma=sigma,\n thresh=thresh,\n device=self.device)\n\n #edge case, if no boxes predictioned return None\n if result is None:\n print(\"No predictions made, returning None\")\n return None\n \n #Set labels to character from numeric if returning boxes df\n if not return_plot:\n result[\"label\"] = result.label.apply(lambda x: self.numeric_to_label_dict[x])\n \n return result\n\n def training_step(self, batch, batch_idx):\n \"\"\"Train on a loaded dataset\n \"\"\"\n path, images, targets = batch\n\n loss_dict = self.model.forward(images, targets)\n\n # sum of regression and classification loss\n losses = sum([loss for loss in loss_dict.values()])\n\n return losses\n\n def validation_step(self, batch, batch_idx):\n \"\"\"Train on a loaded dataset\n\n \"\"\"\n path, images, targets = batch\n\n self.model.train()\n loss_dict = self.model.forward(images, targets)\n\n # sum of regression and classification loss\n losses = sum([loss for loss in loss_dict.values()])\n\n # Log loss\n for key, value in loss_dict.items():\n self.log(\"val_{}\".format(key), value, on_epoch=True)\n\n return losses\n\n def validation_end(self, outputs):\n avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()\n comet_logs = {'val_loss': avg_loss}\n\n return {'avg_val_loss': avg_loss, 'log': comet_logs}\n\n def configure_optimizers(self):\n self.optimizer = optim.SGD(self.model.parameters(),\n lr=self.config[\"train\"][\"lr\"],\n momentum=0.9)\n self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer,\n mode='min',\n factor=0.1,\n patience=10,\n verbose=True,\n threshold=0.0001,\n threshold_mode='rel',\n cooldown=0,\n min_lr=0,\n eps=1e-08)\n return self.optimizer\n\n def evaluate(self,\n csv_file,\n root_dir,\n iou_threshold=None,\n show_plot=False,\n savedir=None):\n \"\"\"Compute intersection-over-union and precision/recall for a given iou_threshold\n\n Args:\n df: a pandas-type dataframe (geopandas is fine) with columns \"name\",\"xmin\",\"ymin\",\"xmax\",\"ymax\",\"label\", each box in a row\n root_dir: location of files in the dataframe 'name' column.\n iou_threshold: float [0,1] intersection-over-union union between annotation and prediction to be scored true positive\n show_plot: open a blocking matplotlib window to show plot and annotations, useful for debugging.\n savedir: optional path dir to save evaluation images\n Returns:\n results: dict of (\"results\", \"precision\", \"recall\") for a given threshold\n \"\"\"\n self.model.eval()\n\n if not self.device.type == \"cpu\":\n self.model = self.model.to(self.device)\n\n predictions = predict.predict_file(model=self.model,\n csv_file=csv_file,\n root_dir=root_dir,\n savedir=savedir,\n device=self.device,\n iou_threshold=self.config[\"nms_thresh\"])\n \n predictions[\"label\"] = predictions.label.apply(lambda x: self.numeric_to_label_dict[x])\n ground_df = pd.read_csv(csv_file)\n\n # if no arg for iou_threshold, set as config\n if iou_threshold is None:\n iou_threshold = self.config[\"validation\"][\"iou_threshold\"]\n\n results = evaluate_iou.evaluate(predictions=predictions,\n ground_df=ground_df,\n root_dir=root_dir,\n iou_threshold=iou_threshold,\n show_plot=show_plot)\n\n return results\n","sub_path":"deepforest/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"158199196","text":"\"\"\"empty message\n\nRevision ID: 41ea4fac36d6\nRevises: \nCreate Date: 2019-05-17 23:03:43.137593\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '41ea4fac36d6'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('carpool_questions', sa.Column('counter', sa.Integer(), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('carpool_questions', 'counter')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/41ea4fac36d6_.py","file_name":"41ea4fac36d6_.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"129545446","text":"from option_critic._generators.common import read_file, write_file\n\n# Set the random seeds\nRANDOM_SEEDS = range(1000, 1000 + 5)\n\n# Set the spec template (common contents) to read\nCOMMON_SPEC_TEMPLATE_PATH_TO_READ = 'option_critic/specs/train/_generators/common.template.yml'\n\n# Set the spec template (run contents) to read\nRUN_SPEC_TEMPLATE_PATH_TO_READ = 'option_critic/specs/train/_generators/run.template.yml'\n\n# Set the spec template (download contents) to read\nDOWNLOAD_SPEC_TEMPLATE_PATH_TO_READ = 'option_critic/specs/train/_generators/download.template.yml'\n\n\ndef gen_specs(settings):\n # Read the spec template\n spec_template = read_spec_template(settings)\n\n # Read the spec template for common content\n common_template = read_common_template()\n\n # Read the spec template for run contents\n run_template = read_run_template()\n\n # Read the spec template for download contents\n download_template = read_download_template()\n\n # Write the specs\n write_specs(settings, spec_template, common_template,\n run_template, download_template)\n\n\ndef read_spec_template(settings):\n # Get the template path\n template_path = settings['template_path_to_read']\n\n # Fill the name\n template_path = template_path.format(name=settings['name'])\n\n # Read the file and return the content\n return read_file(template_path)\n\n\ndef read_common_template():\n return read_file(COMMON_SPEC_TEMPLATE_PATH_TO_READ)\n\n\ndef read_run_template():\n return read_file(RUN_SPEC_TEMPLATE_PATH_TO_READ)\n\n\ndef read_download_template():\n return read_file(DOWNLOAD_SPEC_TEMPLATE_PATH_TO_READ)\n\n\ndef write_specs(\n settings, spec_template, common_template, run_template,\n download_template):\n # Write all specs\n for format_mapping in gen_spec_format_mappings(settings):\n # Build the common content\n commom_content = build_common_content(common_template, format_mapping)\n\n # Build the run contents\n run_contents = build_content_parts(run_template)\n\n # Build the download contents\n download_contents = build_content_parts(download_template)\n\n # Add the contents to the format mapping\n format_mapping['common_content'] = commom_content\n format_mapping['run_contents'] = run_contents\n format_mapping['download_contents'] = download_contents\n\n # Build the spec path\n spec_path = settings['spec_path_to_write'].format(**format_mapping)\n\n # Build the spec content\n spec_content = spec_template.format(**format_mapping)\n\n # Write the spec content\n write_file(spec_path, spec_content)\n\n\ndef build_common_content(common_template, format_mapping):\n # Build the common content and return\n return common_template.format(**format_mapping)\n\n\ndef build_content_parts(template):\n # Initialize the parts\n parts = []\n\n # Build all content parts\n for format_mapping in gen_parts_format_mappings():\n # Build the content part\n part = template.format(**format_mapping)\n\n # Add to the parts\n parts.append(part)\n\n # Merge all parts and return\n return '\\n'.join(parts)\n\n\ndef gen_spec_format_mappings(settings):\n # Generate for all environments\n for env_id in settings['env_ids']:\n # Build the format mapping and yield\n yield {\n 'name': settings['name'],\n 'env_id': env_id,\n }\n\n\ndef gen_parts_format_mappings():\n # Generate for all random seeds\n for random_seed in RANDOM_SEEDS:\n # Build the format mapping and yield\n yield {\n 'random_seed': random_seed,\n }\n","sub_path":"option_critic/specs/train/_generators/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641004670","text":"import re\nimport matplotlib\n\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\n\ndef acc_loss_graph(file):\n regex_utility = re.compile(r\"(validation utility loss:\\s)(\\d+\\.\\d+)\")\n regex_budget = re.compile(r\"(validation budget accuracy:\\s)(\\d+\\.\\d+)\")\n step_lst = []\n utility_acc_lst = []\n budget_acc_lst = []\n step = 0\n with open(file) as f:\n for line in f:\n line = line.rstrip('\\n')\n r_utility = re.search(regex_utility, line)\n r_budget = re.search(regex_budget, line)\n if r_utility is not None and r_budget is not None:\n utility_acc_lst.append(float(r_utility.group(2)))\n #utility_acc_lst.append(float(r_utility.group(2)) / 1000)\n budget_acc_lst.append(float(r_budget.group(2)))\n step_lst.append(step)\n step += 25\n\n plt.plot(step_lst, utility_acc_lst, 'rx-', label='Utility Task Loss')\n #plt.plot(step_lst, budget_acc_lst, 'b^-', label='Budget Task Acc')\n plt.legend(loc='center right', shadow=True)\n plt.xlabel('Step#')\n plt.ylabel('Loss')\n plt.title('Validation Loss of Head Pose Estimation')\n plt.show()\n\nif __name__ == '__main__':\n acc_loss_graph('/home/wuzhenyu/Desktop/summaries/NoL1LossLambdaDecayAvgReplicateMonitorBudgetNoMonitorUtilityRestart4_100.0_0.5_SuppressingMostConfident_20180629-184804/val_summary.txt')","sub_path":"legacy/AFLW/plot_acc_loss.py","file_name":"plot_acc_loss.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"347696597","text":"'''\nThree special cases to consier:\n1) 10; 100; 100; for number like this, A will be 0, and half will be 1 at the end; if will satisfy\nA = half//10 and return True; but it's actually false\n2) other cases: we can use A == half to handle even number and A == half//10 handle odd numebr\n\n'''\n\n\nclass Solution:\n # @return a boolean\n def isPalindrome(self, A):\n \"\"\"\n if A == 0:\n return True\n \n if A<0 or A%10 == 0: return False\n \"\"\"\n if A<0 or (A!=0 and A%10==0):\n return False \n\n half = 0\n \n while A>half:\n half = half*10+A%10\n A = A//10\n # A == half for even number, like \"1221\"; A = half //10 for odd number, like \"12321\" \n \n return A==half or half//10 == A\n \n \n ","sub_path":"Leetcode_Python/Palindrome Number.py","file_name":"Palindrome Number.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"284543438","text":"from operator import itemgetter\nimport math\nimport datetime\nimport string\nimport heapq\nfrom compgraph.graph import ComputeGraph\n\n\ndef _filter_punctuation(txt):\n p = set(string.punctuation)\n return \"\".join(c for c in txt if c not in p)\n\n\ndef extract_words(text):\n for word in _filter_punctuation(text).split():\n if word:\n yield word.lower().strip()\n\n\ndef emit_words(record):\n for word in extract_words(record[\"text\"]):\n yield {'doc_id': record['doc_id'], 'word': word, 'count': 1}\n\n\ndef collect_counts(records):\n count_sum = 0\n for record in records:\n count_sum += record[\"count\"]\n yield {'text': record['word'], \"count\": count_sum}\n\n\ndef collect_words(records):\n count_sum = 0\n for record in records:\n count_sum += record[\"count\"]\n yield {'word': record['word'], \"count\": count_sum}\n\n\ndef count_rows(state, record):\n if state is None:\n state = {\"docs_count\": 0}\n return {'docs_count': state['docs_count'] + 1}\n\n\ndef unique(records):\n for record in records:\n yield {\"doc_id\": record[\"doc_id\"], \"word\": record[\"word\"]}\n break\n\n\ndef calc_idf(records):\n records = list(records)\n for record in records:\n yield {\"doc_id\": record[\"doc_id\"], \"word\": records[0][\"word\"], \"idf\": records[0][\"docs_count\"]/len(records)}\n\n\ndef tf(records):\n word_counts = {}\n records = list(records)\n for record in records:\n word_counts[record[\"word\"]] = word_counts.get(record[\"word\"], 0) + 1\n for word, count in word_counts.items():\n yield {\"word\": word, \"tf\": count/len(records), \"doc_id\": record[\"doc_id\"]}\n\n\ndef tf_with_sift(records):\n word_counts = {}\n for record in records:\n if len(record[\"word\"]) > 4:\n word_counts[record[\"word\"]] = word_counts.get(record[\"word\"], 0) + 1\n total_count = 0\n for word in word_counts:\n if word_counts[word] > 1:\n total_count += word_counts[word]\n\n for word, count in word_counts.items():\n if count > 1:\n yield {\"word\": word, \"tf\": count/total_count, \"doc_id\": record[\"doc_id\"],\n \"count_in_doc\": count, \"total_count_in_doc\": total_count}\n\n\ndef culc_tf_idf(record):\n return {\"text\": record[\"word\"], \"doc_id\": record[\"doc_id\"], \"tf_idf\": record[\"tf\"] * math.log(record[\"idf\"])}\n\n\ndef invert_index(records):\n yield from heapq.nlargest(3, (culc_tf_idf(record) for record in records), key=itemgetter(\"tf_idf\"))\n\n\ndef frequency_of_word_in_doc(records):\n word_count = 0\n records = list(records)\n for record in records:\n word_count += record[\"count\"]\n yield {\"\"}\n\n\ndef sum_words(state, record):\n if state is None:\n state = {\"words_count\": 0}\n state[\"words_count\"] += record[\"count_in_doc\"]\n return state\n\n\ndef calc_pmi(records):\n for record in records:\n yield {\"doc_id\": record[\"doc_id\"], \"text\": record[\"word\"],\n \"pmi\": math.log(record[\"tf\"]*record[\"words_count\"]/record[\"count\"])}\n\n\ndef collect_words_pmi(records):\n count_sum = 0\n for record in records:\n count_sum += record[\"count_in_doc\"]\n yield {'word': record['word'], \"count\": count_sum}\n\n\ndef get_top_10(records):\n yield from sorted(records, key=lambda x: x[\"pmi\"], reverse=True)[:10]\n\n\ndef build_word_count_graph(input_stream, text_column='text', count_column='count'):\n return ComputeGraph(input_stream).map(emit_words).sort(\"word\").reduce(collect_counts, \"word\").sort(count_column)\n\n\ndef build_inverted_index_graph(input_stream, doc_column='doc_id', text_column='text'):\n \"\"\"For every pair (word, document) tf - idf is\n TFIDF(word_i, doc_i) = (frequency of word_i in doc_i) * log((total number of docs) / (docs where word_i is present))\n Result should look like {'term': 'word', 'index': [(doc_id_1, tf_idf_1)...]}\"\"\"\n split_word = ComputeGraph(input_stream).map(emit_words)\n count_docs = ComputeGraph(input_stream).fold(count_rows)\n count_idf = ComputeGraph(split_word).sort(\"doc_id\", \"word\").reduce(unique, keys=(\"doc_id\", \"word\"))\\\n .join(count_docs, type='inner').sort('word').reduce(calc_idf, keys=('word'))\n calc_index = ComputeGraph(split_word).sort('doc_id').reduce(tf, keys='doc_id')\\\n .join(count_idf, keys=('word', \"doc_id\"), type='left').sort('word').reduce(invert_index, keys='word')\n\n return calc_index\n\n\ndef build_pmi_graph(input_stream, doc_column='doc_id', text_column='text'):\n word_count_pre_doc = ComputeGraph(input_stream).map(emit_words).sort(\"doc_id\").reduce(tf_with_sift, \"doc_id\")\n\n total_word_count = ComputeGraph(word_count_pre_doc).fold(sum_words)\n\n word_count = ComputeGraph(word_count_pre_doc).sort(\"word\").reduce(collect_words_pmi, \"word\")\n\n calc_index = ComputeGraph(word_count_pre_doc).join(total_word_count)\\\n .join(word_count, keys=\"word\", type=\"left\").sort((\"word\", \"doc_id\"))\\\n .reduce(calc_pmi, keys=(\"word\", \"doc_id\")).sort(\"doc_id\").reduce(get_top_10, \"doc_id\")\n\n return calc_index\n\n\ndef build_yandex_maps_graph(input_stream, input_stream_length):\n lengths = ComputeGraph(input_stream_length).map(add_distance)\n speed = ComputeGraph(input_stream).map(add_weekday).map(add_hour).map(add_delta_time).join(lengths, keys=\"edge_id\")\\\n .sort(\"weekday\", \"hour\").reduce(culc_speed, keys=(\"weekday\", \"hour\"))\n return speed\n\n\ndef parse_date(date):\n return datetime.datetime.strptime(date, \"%Y%m%dT%H%M%S.%f\")\n\n\ndef get_day(datetime):\n return datetime.strftime('%a')\n\n\ndef date_range(start_date, end_date):\n start_date = parse_date(start_date)\n end_date = parse_date(end_date)\n for ordinal in range(start_date.toordinal(), end_date.toordinal()):\n yield datetime.datetime.fromordinal(ordinal + 1)\n yield end_date\n\n\ndef cucl_deltatime(start_time, end_time):\n delta_time = end_time - start_time\n return delta_time.total_seconds()\n\n\ndef add_weekday(record):\n enter_time = parse_date(record[\"enter_time\"])\n leave_time = parse_date(record[\"leave_time\"])\n delta_time = cucl_deltatime(enter_time, leave_time)\n for leave_time in date_range(record[\"enter_time\"], record[\"leave_time\"]):\n yield {**record, \"enter_time\": enter_time, \"leave_time\": leave_time,\n \"weekday\": get_day(enter_time), \"part\": cucl_deltatime(enter_time, leave_time) / delta_time}\n\n\ndef add_hour(record):\n enter_time = record[\"enter_time\"]\n leave_time = record[\"leave_time\"]\n delta_time = cucl_deltatime(enter_time, leave_time)\n middle_time = enter_time\n while middle_time < leave_time:\n middle_time += datetime.timedelta(hours=1)\n if middle_time > leave_time:\n middle_time = leave_time\n yield {**record, \"enter_time\": enter_time, \"leave_time\": middle_time, \"hour\": enter_time.hour,\n \"part\": record[\"part\"] * cucl_deltatime(enter_time, middle_time) / delta_time}\n enter_time = middle_time\n\n\ndef add_delta_time(record):\n enter_time = record[\"enter_time\"]\n leave_time = record[\"leave_time\"]\n delta_time = cucl_deltatime(enter_time, leave_time) / 3600\n yield {**record, \"time\": delta_time}\n\n\ndef add_distance(record):\n yield {\"edge_id\": record[\"edge_id\"], \"distance\": distance(record[\"start\"], record[\"end\"])}\n\n\ndef distance(origin, destination):\n \"\"\"\n Calculate the Haversine distance.\n\n Parameters\n ----------\n origin : tuple of float\n (lat, long)\n destination : tuple of float\n (lat, long)\n\n Returns\n -------\n distance_in_km : float\n\n \"\"\"\n lon1, lat1 = origin\n lon2, lat2 = destination\n radius = 6371\n dlat = math.radians(lat2 - lat1)\n dlon = math.radians(lon2 - lon1)\n a = (math.sin(dlat / 2) * math.sin(dlat / 2) +\n math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *\n math.sin(dlon / 2) * math.sin(dlon / 2))\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n d = radius * c\n return d\n\n\ndef culc_speed(records):\n distance = 0\n time = 0\n for record in records:\n distance += record[\"distance\"] * record[\"part\"]\n time += record[\"time\"] * record[\"part\"]\n yield {\"hour\": record[\"hour\"], \"speed\": distance/time, \"weekday\": record[\"weekday\"]}\n","sub_path":"examples/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":8155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29960967","text":"from django.conf.urls import url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.home),\n url(r'^colaboradores/', views.colaboradores),\n url(r'^colaboradoresNovo/', views.colaboradoresNovo),\n url(r'^colaboradoresVisualizar/', views.colaboradoresVisualizar),\n url(r'^colaboradoresSite/', views.colaboradoresSite),\n url(r'^colaboradoresSiteVisualizar/', views.colaboradoresSiteVisualizar),\n url(r'^fornecedores/', views.fornecedores),\n url(r'^fornecedoresNovo/', views.fornecedoresNovo),\n url(r'^fornecedoresVisualizar/', views.fornecedoresVisualizar),\n url(r'^fornecedoresEditar/', views.fornecedoresEditar),\n url(r'^fornecedoresSalvar/', views.fornecedoresSalvar),\n url(r'^funcao/', views.funcaoHome),\n url(r'^funcaoNovo/', views.funcaoNovo),\n url(r'^funcaoVisualizar/', views.funcaoVisualizar),\n url(r'^funcaoSalvar/', views.funcaoSalvar),\n url(r'^clientes/', views.clientesHome),\n url(r'^clientesNovo/', views.clientesNovo),\n url(r'^clientesVisualizar/', views.clientesVisualizar),\n url(r'^clientesEditar/', views.clientesEditar),\n url(r'^orcamentos/', views.orcamentosHome),\n url(r'^estoque/', views.estoqueHome),\n url(r'^equipamentos/', views.equipamentosHome),\n url(r'^equipamentosNovo/', views.equipamentosNovo),\n url(r'^equipamentosVisualizar/', views.equipamentosVisualizar),\n url(r'^equipamentosSalvar/', views.equipamentosSalvar),\n url(r'^contas/', views.contasHome),\n url(r'^contasRelatorios/', views.contasRelatorioHome),\n url(r'^contasPagar/', views.contasPagarHome),\n url(r'^contasPagarNovo/', views.contasPagarNovo),\n url(r'^contasPagarVisualizar', views.contasPagarVisualizar),\n url(r'^contasPagarEditar', views.contasPagarEditar),\n url(r'^contasReceber/', views.contasReceberHome),\n url(r'^contasReceberNovo/', views.contasReceberNovo),\n url(r'^contasReceberVisualizar', views.contasReceberVisualizar),\n url(r'^contasReceberEditar', views.contasReceberEditar),\n url(r'^caixaHome/', views.caixaHome),\n url(r'^caixaEntradaNovo/', views.caixaEntradaNovo),\n url(r'^caixaSaidaNovo/', views.caixaSaidaNovo),\n url(r'^balancoHome/', views.balancoHome),\n]","sub_path":"gerencia/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"397045838","text":"import cv2 as cv\nimport sys\nimg = cv.imread(cv.samples.findFile('test.jpg'))\n\nif img is None:\n sys.exit(\"Image Error\")\ncv.imshow(\"IMAGE\", img)\nk = cv.waitKey(0)\nif k == ord(\"s\"):\n cv.imwrite(\"TESTIMAGE.png\", img)\n\n\n\n","sub_path":"opencv/opencvTest.py","file_name":"opencvTest.py","file_ext":"py","file_size_in_byte":222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"575765125","text":"import numpy as np \nimport models\nimport torch\nfrom torch.autograd import Variable\nimport cv2\nimport random\nimport gym_ple\n\n\"\"\"\nThis is the implementation of DQN\n\n2017-01-17\n\nauthor: Tianhong Dai\n\n\"\"\"\n\nclass dqn_brain:\n def __init__(self, args, env):\n # get the arguments...\n self.args = args\n # init the parameters....\n self.env = env \n # check if use the cuda to train the network...\n self.use_cuda = torch.cuda.is_available() and self.args.cuda \n print('The cuda is avaiable: ' + str(torch.cuda.is_available()))\n print('If use the cuda: ' + str(self.args.cuda))\n\n # get the number of actions....\n # action space fot the FlappyBird....\n self.action_space = [0, 1]\n self.num_actions = len(self.action_space)\n\n # build up the network.... and the target network\n self.deep_q_network = models.Deep_Q_Network(self.num_actions)\n self.target_network = models.Deep_Q_Network(self.num_actions)\n # decide if put into the cuda...\n\n if self.use_cuda:\n self.deep_q_network.cuda()\n self.target_network.cuda()\n\n # init the parameters of the target network...\n self.target_network.load_state_dict(self.deep_q_network.state_dict())\n\n # init the optimizer\n self.optimizer = torch.optim.Adam(self.deep_q_network.parameters(), lr=self.args.lr)\n\n # this is used to train the network...\n def train_network(self):\n # init the memory buff...\n brain_memory = []\n num_of_episode = 0\n global_step = 0\n update_step_counter = 0\n reward_mean = None\n epsilon = self.args.init_exploration\n loss = 0\n\n while True:\n state = self.env.reset()\n state = self._pre_processing(state)\n # for the first state we need to stack them together....\n state = np.stack((state, state, state, state), axis=0)\n # clear the rewrad_sum...\n reward_sum = 0\n pipe_num = 0\n # I haven't set a max step here, but you could set it...\n while True:\n state_tensor = torch.Tensor(state).unsqueeze(0)\n if self.use_cuda:\n state_tensor = Variable(state_tensor).cuda()\n else:\n state_tensor = Variable(state_tensor)\n\n _, _, actions = self.deep_q_network(state_tensor)\n\n action_selected = self._selected_the_actions(actions, epsilon)\n # input the action into the environment...\n state_, reward, done, _ = self.env.step(self.action_space[action_selected])\n\n # process the output state...\n state_ = self._pre_processing(state_)\n\n # concatenate them together...\n state_temp = state[0:3, :, :].copy()\n state_ = np.expand_dims(state_, 0)\n state_ = np.concatenate((state_, state_temp), axis=0)\n\n # wrapper the reward....\n reward = self._reward_wrapper(reward)\n\n # add the pip num...\n if reward > 0:\n pipe_num += 1\n\n reward_sum += reward\n global_step += 1\n\n # store the transition...\n brain_memory.append((state, state_, reward, done, action_selected))\n\n if len(brain_memory) > self.args.buffer_size:\n brain_memory.pop(0)\n\n if global_step >= self.args.observate_time:\n mini_batch = random.sample(brain_memory, self.args.batch_size)\n loss = self._update_network(mini_batch)\n update_step_counter += 1\n # up date the target network...\n if update_step_counter % self.args.hard_update_step == 0:\n self._hard_update_target_network(self.deep_q_network, self.target_network)\n\n # process the epsilon\n if global_step <= self.args.exploration_steps:\n epsilon -= (self.args.init_exploration - self.args.final_exploration) / self.args.exploration_steps\n\n if done:\n break\n\n state = state_\n\n # expoential weighted average...\n reward_mean = pipe_num if reward_mean is None else reward_mean * 0.99 + pipe_num * 0.01\n\n if num_of_episode % self.args.display_interval == 0:\n print('The episode number is ' + str(num_of_episode) + ', the reward mean is ' + str(reward_mean) + \\\n ', and the loss ' + str(loss))\n\n if num_of_episode % self.args.save_interval == 0:\n save_path = self.args.save_dir + 'model_' + str(num_of_episode) + '.pt'\n torch.save(self.deep_q_network.state_dict(), save_path)\n\n num_of_episode += 1\n\n # process the image..\n def _pre_processing(self, x):\n x = x[:, :, (2, 1, 0)]\n x = cv2.cvtColor(x, cv2.COLOR_BGR2GRAY)\n x = np.float32(x) / 255\n x = cv2.resize(x, (84, 84))\n \n return x\n\n def _reward_wrapper(self, reward):\n if reward < 0:\n reward = -1\n elif reward > 0:\n reward = 1\n\n return reward\n\n def _selected_the_actions(self, action, epsilon):\n # transfer the action from the gpu to cpu\n action_selected = action.data.cpu().numpy()[0]\n action_selected = int(action_selected)\n\n # greedy...\n dice = random.uniform(0, 1)\n\n if dice >= 1 - epsilon:\n action_selected = random.randint(0, self.num_actions - 1)\n\n return action_selected\n\n # this is used to update the q_learning_network...\n def _update_network(self, mini_batch):\n # process the data...\n state_batch = np.array([element[0] for element in mini_batch])\n state_batch_tensor = torch.Tensor(state_batch)\n\n state_next_batch = np.array([element[1] for element in mini_batch])\n state_next_batch_tensor = torch.Tensor(state_next_batch)\n\n reward_batch = np.array([element[2] for element in mini_batch])\n reward_batch_tensor = torch.Tensor(reward_batch).unsqueeze(1)\n\n done_batch = np.array([float(element[3]) for element in mini_batch])\n done_batch = 1 - done_batch\n done_batch_tensor = torch.Tensor(done_batch).unsqueeze(1)\n\n action_batch = np.array([element[4] for element in mini_batch])\n action_batch_tensor = torch.LongTensor(action_batch).unsqueeze(1)\n\n # put the tensor into the gpu...\n\n if self.use_cuda:\n state_batch_tensor = Variable(state_batch_tensor).cuda()\n state_next_batch_tensor = Variable(state_next_batch_tensor).cuda()\n reward_batch_tensor = Variable(reward_batch_tensor).cuda()\n done_batch_tensor = Variable(done_batch_tensor).cuda()\n action_batch_tensor = Variable(action_batch_tensor).cuda()\n else: \n state_batch_tensor = Variable(state_batch_tensor)\n state_next_batch_tensor = Variable(state_next_batch_tensor)\n reward_batch_tensor = Variable(reward_batch_tensor)\n done_batch_tensor = Variable(done_batch_tensor)\n action_batch_tensor = Variable(action_batch_tensor)\n\n\n # calculate the target value....\n _, q_max_value, _ = self.target_network(state_next_batch_tensor)\n q_max_value = q_max_value.unsqueeze(1)\n\n target = reward_batch_tensor + self.args.gamma * q_max_value * done_batch_tensor\n # remove the target from the computation graph...\n target = target.detach()\n # calculate the loss\n Q_value, _, _ = self.deep_q_network(state_batch_tensor)\n\n real_Q_value = Q_value.gather(1, action_batch_tensor)\n\n loss = (target - real_Q_value).pow(2).mean()\n\n self.optimizer.zero_grad()\n loss.backward()\n\n self.optimizer.step()\n\n return loss.data.cpu().numpy()[0]\n\n # hard update the target network....\n def _hard_update_target_network(self, source, target):\n for param, param_target in zip(source.parameters(), target.parameters()):\n param_target.data.copy_(param.data)\n\n# -------------------------- Here is to test the network.... ------------------------------#\n\n def test_network(self):\n model_path = self.args.save_dir + 'model.pt'\n self.deep_q_network.load_state_dict(torch.load(model_path, map_location=lambda storage, loc: storage))\n self.deep_q_network.eval()\n\n while True: \n state = self.env.reset()\n state = self._pre_processing(state)\n # for the first state we need to stack them together....\n state = np.stack((state, state, state, state), axis=0)\n # clear the rewrad_sum...\n pipe_sum = 0\n # I haven't set a max step here, but you could set it...\n while True:\n self.env.render()\n state_tensor = torch.Tensor(state).unsqueeze(0)\n if self.use_cuda:\n state_tensor = Variable(state_tensor).cuda()\n else:\n state_tensor = Variable(state_tensor)\n\n _, _, actions = self.deep_q_network(state_tensor)\n\n # action...deterministic...\n action_selected = int(actions.data.numpy()[0])\n\n state_, reward, done, _ = self.env.step(self.action_space[action_selected])\n if reward > 0:\n pipe_sum += 1\n\n # process the output state...\n state_ = self._pre_processing(state_)\n\n # concatenate them together...\n state_temp = state[0:3, :, :].copy()\n state_ = np.expand_dims(state_, 0)\n state_ = np.concatenate((state_, state_temp), axis=0)\n\n if done:\n break\n \n state = state_\n\n print('In this episode, the bird totally pass ' + str(pipe_sum) + ' pipes!')\n\n","sub_path":"dqn/dqn_agent.py","file_name":"dqn_agent.py","file_ext":"py","file_size_in_byte":10179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"71270339","text":"#! /usr/bin/env python3\n\n\n# Define class Foo\nclass Foo:\n # __init__() is run when Foo() is initialized\n def __init__(self, text):\n # hello is stored in instance of class referenced by the self parameter\n self.hello = text\n # not_hello is not stored and will be deleted\n not_hello = \"hade\"\n \n def bar(self, text):\n # Print hello variable which is stored in the self parameter\n print(self.hello, end=\" \")\n \n # Print text parameter\n print(text)\n \n\n# Define another class FooBar\nclass FooBar:\n def __init__(self):\n self.hello = \"God dag\"\n\n\n# Create an instance of class Foo\na = Foo(\"hi\")\n\n# Print \"hi\" from the instance of Foo\nprint(a.hello)\n\n# Print \"hi world\"\na.bar(\"world\")\nFoo.bar(a, \"world\") # This is the same\n\n\n# Foo does not need to be initialized to use its functions\nFoo.bar(a, \"world\") # Prints \"hi world\"\nFoo(\"hello\").bar(\"world\") # Prints \"hello world\"\n\n# Foo.bar does not even require the \"self\" parameter to be an instance of same class\nb = FooBar()\nFoo.bar(b, \"world\") # Prints \"God dag world\"\n","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"294785065","text":"import os\n\nsample_rate = 8192 # 22050\nmusdb_dir = '../data/original/musdb18'\nccmixt_dir = '../data/original/CCMixter/ccmixter_corpus/'\nhhds_dir = '../data/original/HHDS'\nnin_dir = '../data/original/NIN'\nfma_dir = '../data/original/FMA'\ndamp_dir = '../data/original/DAMP'\nn_damp = 2600 # how many tracks to use from the total amount of DAMP tracks\ndataset_path = '../data/dataset_objects/'\nfma_genres_to_consider = [\"Rock\", \"Pop\", \"Hip-Hop\"]\nn_fft = 512\nhop_length = 64\nspectrogram_samples = 4160 # such that spectrogram has 66 temporal bins\nspect_temporal_pad = 2944 # such that spectrogram has 158 temporal bins\nspectrogram_samples_check = 76864 # about 9 sec\nspectrogram_duration = spectrogram_samples/sample_rate # about .5 sec\nexpected_spect_shape_mixture = (257, 158)\nexpected_spect_shape_target = (257, 66)\nexpected_spect_shape_check_mixture = (257, 1294) # this lasts longer. good for qualitative inspection\nexpected_spect_shape_check_target = (257, 1202)\nwave_samples = 16389 #8197 #40965\nwave_temporal_pad = 8698 #67574\nwave_samples_check = 70661 #70149 #135173\nwave_duration = wave_samples / sample_rate\n\ndef dir_maker(filename):\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n\ndir_maker(dataset_path)\n","sub_path":"src/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"168262643","text":"import httplib\nimport urllib\nimport time\nimport json\n\nimport mysql.connector\n\n__author__ = 'myatsko'\n\napi_key = '338e353e-f119-4c1d-ade9-8e6f0b9df4ab'\npage_id = 'nmm9j2skbrxf'\nmetric_id = '62yf2rjzfwsn'\napi_base = 'api.statuspage.io'\ngrab = httplib.HTTPConnection('192.168.6.73:8080')\ngrab.request(\"GET\", \"/callfire-delegator/activity-dashboard?format=json\")\ndata = json.loads(grab.getresponse().read())\nts = int(time.time())\nvalue = data[\"outbound-call-activity\"][\"calls\"] + data[\"outbound-ccc-activity\"][\"calls\"]\nparams = urllib.urlencode({'data[timestamp]': ts, 'data[value]': value})\nheaders = {\"Content-Type\": \"application/x-www-form-urlencoded\", \"Authorization\": \"OAuth \" + api_key}\nconn = httplib.HTTPSConnection(api_base)\nconn.request(\"POST\", \"/v1/pages/\" + page_id + \"/metrics/\" + metric_id + \"/data.json\", params, headers)\nresponse = conn.getresponse()\n\ndbconn = mysql.connector.connect(user='myatsko', password='myfdbuqte4n', host='127.0.0.1', database='statuspage')\ncursor = dbconn.cursor()\ncursor.execute(\"\"\"INSERT INTO active_calls (sum_active_calls) VALUES (%s)\"\"\", (value,))\ndbconn.commit()\ncursor.close()\ndbconn.close()","sub_path":"activecalls.py","file_name":"activecalls.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"594891936","text":"import ss;\n\ndef sum(a,b):\n x = a + b;\n return x;\n\n\ndef subtract(a, b):\n x = a - b;\n return x;\n\n\nif __name__ == \"__main__\":\n print(\"The sum of two numbers is :\");\n y = sum(4,5);\n print(y);\n\n print(\"The difference of two numbers is :\");\n y = subtract(4, 5);\n print(y);\n","sub_path":"team-110/phaseC/plagiarismdetector/src/main/resources/test123.py","file_name":"test123.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"134647279","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.postgres.search import SearchVector\nfrom django.core.paginator import Paginator, InvalidPage\nfrom django.shortcuts import get_object_or_404\nfrom django.views.generic import TemplateView\n\nfrom documents.defs import get_mimes_for_category\nfrom documents.models import Document, DocumentVersion\nfrom projects.forms import CategoryForm, SortForm\nfrom projects.models import Project\n\n\nclass ProjectView(LoginRequiredMixin, TemplateView):\n template_name = 'projects/project.html'\n\n def get_context_data(self, **kwargs):\n version_ids = []\n for document in self.documents:\n for version in document.documentversion_set.all():\n version_ids.append(str(version.uuid))\n versions = DocumentVersion.objects.filter(uuid__in=version_ids).order_by('person_id')\n\n if hasattr(self, 'sort_order'):\n if self.sort_order == 'AZ':\n self.documents = self.documents.order_by('name')\n if hasattr(self, 'category'):\n mimes = get_mimes_for_category(self.category)\n self.documents = self.documents.filter(mime__in=mimes)\n per_page = self.request.GET.get('per_page', 20)\n page = self.request.GET.get('page', 1)\n paginator = Paginator(self.documents, per_page)\n try:\n documents = paginator.page(page).object_list\n except InvalidPage:\n documents = paginator.page(1)\n return {\n 'categories_form': self.categories_form,\n 'documents': documents,\n 'page_range': paginator.page_range,\n 'current_page': page,\n 'project': self.project,\n 'sort_form': self.sort_form,\n 'version_count': versions.count(),\n 'user_count': versions.distinct('person').count()\n }\n\n def dispatch(self, request, pk, *args, **kwargs):\n self.project = get_object_or_404(Project.objects.active(), pk=pk)\n self.categories_form = CategoryForm(request.GET or None, project=self.project)\n self.sort_form = SortForm(request.GET or None)\n if 'search' in request.GET:\n self.documents = Document.objects.filter(\n id__in=DocumentVersion.objects.annotate(\n search=SearchVector('name', 'description')\n ).filter(\n search=request.GET.get('search', '')\n ).values_list('document_id', flat=True)\n ).filter(project=self.project).prefetch_related('documentversion_set', 'documentversion_set__person')\n self.sort_order = request.GET.get('search')\n else:\n self.documents = Document.objects.active().filter(project=self.project).select_related().prefetch_related(\n 'documentversion_set',\n 'documentversion_set__person'\n )\n\n return super(ProjectView, self).dispatch(request, *args, **kwargs)\n","sub_path":"django_kala/projects/views/projects/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87751536","text":"import xml.etree.ElementTree as ET\nfrom xml.dom import minidom\n\n\ndef create_xml_tree(root, dict_tree):\n # Node : recursively create tree nodes\n if type(dict_tree) == dict:\n for k, v in dict_tree.items():\n create_xml_tree(ET.SubElement(root, k), v)\n return root\n # Leaf : just set the value of the current node\n else:\n root.text = str(dict_tree)\n\n\ndef prettify(elem):\n \"\"\"Return a pretty-printed XML string for the Element\n \"\"\"\n rough_string = ET.tostring(elem, 'utf-8')\n reparsed = minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\"\".join([' '] * 4))\n","sub_path":"src/xml_generator.py","file_name":"xml_generator.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"291414550","text":"print('Analise de triângulo ')\nreta1 = float(input('Digite o valor da reta1: '))\nreta2 = float(input('Digite o valor da reta2: '))\nreta3 = float(input('Digite o valor da reta3: '))\n\ncorreto = 0\nif reta1 - reta2 < reta3 < reta1 + reta3:\n correto = correto + 1\nif reta1 - reta3 < reta2 < reta1 + reta3:\n correto = correto + 1\nif reta3 - reta2 < reta1 < reta3 + reta2:\n correto = correto + 1\n\nif correto == 3:\n print('Com as 3 retas conseguimos formar um triângulo !!')\nelse:\n print('Não forma um triângulo!!')\n","sub_path":"Exercicio31a40/ex035.py","file_name":"ex035.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"519547390","text":"from __future__ import annotations\n\nimport logging\nfrom typing import List, Tuple\n\nimport pygame\nfrom pygame_gui import UIManager\nfrom pygame_gui.core import UIElement\nfrom pygame_gui.elements import UIImage, UIPanel, UITextBox\n\nfrom scripts.engine import world\nfrom scripts.engine.component import Aesthetic, Aspect, Identity, Position, Resources, Traits\nfrom scripts.engine.core.constants import GAP_SIZE, ICON_IN_TEXT_SIZE, RenderLayer\n\n\nclass TileInfo(UIPanel):\n \"\"\"\n Hold text relating to the game's events, to display to the player.\n \"\"\"\n\n def __init__(self, rect: pygame.Rect, manager: UIManager):\n\n self.selected_tile_pos: Tuple[int, int] = (0, 0)\n self.sections: List[UIElement] = []\n\n # complete base class init\n super().__init__(\n rect,\n RenderLayer.UI_BASE,\n manager,\n element_id=\"tile_info\",\n anchors={\"left\": \"right\", \"right\": \"right\", \"top\": \"bottom\", \"bottom\": \"bottom\"},\n )\n\n # show self\n self.show()\n\n # confirm init complete\n logging.debug(f\"Tile Info initialised.\")\n\n def update(self, time_delta: float):\n \"\"\"\n Update based on current state and data. Run every frame.\n \"\"\"\n super().update(time_delta)\n\n def handle_events(self, event):\n \"\"\"\n Handle events created by this UI element. Method must exist, even if stubbed.\n \"\"\"\n pass\n\n ############## GET / SET ########################\n\n def set_selected_tile_pos(self, tile_pos: Tuple[int, int]):\n \"\"\"\n Set the selected tile position to show the info for that tile.\n \"\"\"\n self.selected_tile_pos = tile_pos\n\n ############### ACTIONS #########################\n\n def show(self):\n \"\"\"\n Show the tile info. Builds the sections required, after clearing any existing. Also triggers base class show\n method.\n \"\"\"\n super().show()\n\n # clear to refresh first\n self.cleanse()\n\n if self.selected_tile_pos:\n\n images = []\n info = []\n\n # get entities at selected position\n from scripts.engine.core import queries\n\n for entity, (position, identity, aesthetic) in queries.position_and_identity_and_aesthetic:\n if self.selected_tile_pos in position:\n\n # get universal info\n images.append(aesthetic.sprites.icon)\n current_info = [identity.name]\n\n ## is it an entity with more useful info?\n # get resources\n resources = world.get_entitys_component(entity, Resources)\n if resources:\n current_info.append(f\"Health: {resources.health}\")\n current_info.append(f\"Stamina: {resources.stamina}\")\n\n # get traits\n traits = world.get_entitys_component(entity, Traits)\n if traits:\n names = \"\"\n for name in traits.names:\n # if more than one trait add a separator\n if len(names) > 1:\n names += \", \"\n names += f\"{name}\"\n current_info.append(names)\n\n # get aspects\n aspect = world.get_entitys_component(entity, Aspect)\n if aspect:\n details = \"\"\n for name, duration in aspect.aspects.items():\n # if more than one aspect add a separator\n if len(details) > 1:\n details += \", \"\n details += f\"{name}:{duration}\"\n current_info.append(details)\n\n # add collected info to main info\n info.append(current_info)\n\n # create the box for the info\n self._create_sections(images, info)\n\n def cleanse(self):\n \"\"\"\n Cleanse existing section info.\n \"\"\"\n # kill the box and clear the reference\n for element in self.sections:\n element.kill()\n self.sections = []\n\n ############## CREATE ########################\n\n def _create_sections(self, images: List[pygame.surface], info: List[List[str]]):\n \"\"\"\n Create sections for the information about the tile\n \"\"\"\n sections = []\n current_y = 0\n section_number = 0\n\n # draw info\n centre_draw_x = int((self.rect.width / 2) - (ICON_IN_TEXT_SIZE / 2))\n image_rect = pygame.Rect((centre_draw_x, 0), (ICON_IN_TEXT_SIZE, ICON_IN_TEXT_SIZE))\n x = 0\n width = self.rect.width\n text_height = 0 # box will resize height anyway\n\n # loop each image provided and use as header for each group of info\n # FIXME - hovering projectile breaks it due to not havign a surface (missing icon_path?)\n for image in images:\n # create image\n _image = pygame.transform.scale(image, (ICON_IN_TEXT_SIZE, ICON_IN_TEXT_SIZE))\n ui_image = UIImage(\n relative_rect=image_rect, image_surface=_image, manager=self.ui_manager, container=self.get_container()\n )\n sections.append(ui_image)\n ui_image = None # clear to prevent any carry over\n\n # update position\n current_y += ICON_IN_TEXT_SIZE + GAP_SIZE\n\n # collect text for the section\n text = \"\"\n for line in info[section_number]:\n text += line + \"
\"\n\n # create textbox\n rect = pygame.Rect((x, current_y), (width, text_height))\n ui_text = UITextBox(\n html_text=text,\n relative_rect=rect,\n manager=self.ui_manager,\n wrap_to_height=True,\n layer_starting_height=1,\n container=self.get_container(),\n )\n sections.append(ui_text)\n ui_text = None # clear to prevent any carry over\n\n # increment section\n section_number += 1\n\n # update main sections list\n self.sections = sections\n","sub_path":"scripts/engine/ui/elements/tile_info.py","file_name":"tile_info.py","file_ext":"py","file_size_in_byte":6324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441214969","text":"import json\nimport math\n\nimport pandas as pd\nimport requests\nfrom scipy.special import ndtri\nfrom surprise import Dataset, Reader\n\nfrom models import KNNBasic\n\n\nclass ModelBuilder:\n dataset_columns = ['UserId', 'ArtistId', 'rating_value']\n k_value = 40\n gamma = 15\n full_trainset = None\n similarity_equation = 'jaccard'\n sim_options_jaccard = {\n 'name': similarity_equation,\n 'user_based': True\n }\n\n def __init__(self):\n self.to_update = False\n self.update_data()\n\n def update_data(self):\n self.updating = True\n self.build_trainset()\n self.create_model()\n self.updating = False\n if self.to_update:\n self.to_update = False\n self.update_data()\n\n def set_to_update(self):\n self.to_update = True\n\n def build_trainset(self):\n # r = requests.get(\"http://127.0.0.1:8082/api/rating\")\n r = requests.get(\"http://172.24.101.30:8082/api/rating\")\n data = r.json()\n df = pd.DataFrame(data)\n df = df[['UserId', 'ArtistId', 'rating_value']]\n\n reader = Reader(rating_scale=(1.0, 5.0))\n data = Dataset.load_from_df(df[self.dataset_columns], reader)\n full_trainset_temp = data.build_full_trainset()\n self.full_trainset = full_trainset_temp\n\n def create_model(self):\n # Create the algorithm\n algo_temp = KNNBasic(\n k=self.k_value, sim_options=self.sim_options_jaccard)\n # Create the similitude matrix (train the model)\n algo_temp.fit(self.full_trainset)\n self.algorithm = algo_temp\n\n def get_top_n(self, predictions, n=10):\n top_n = {}\n for uid, iid, true_r, est, _ in predictions:\n if uid not in top_n:\n top_n[uid] = [(iid, est)]\n else:\n top_n[uid].append((iid, est))\n\n for uid, user_ratings in top_n.items():\n user_ratings.sort(key=lambda x: x[1], reverse=True)\n top_n[uid] = user_ratings[:n]\n\n return top_n\n\n def predict_for_user(self, user_id, top_n=10):\n \"\"\"\n Returns all predicitions for the given user\n \"\"\"\n print(\"Getting recomendations for user {}\".format(user_id))\n\n user_ratings = self.full_trainset.ur[self.full_trainset.to_inner_uid(\n user_id)]\n items = self.full_trainset.ir\n items_raw_ids = []\n\n # Transform inner ids to raw ids\n for item in items:\n item_raw_id = self.full_trainset.to_raw_iid(item)\n items_raw_ids.append(item_raw_id)\n\n # Predict for the given raw user id, for all raw item ids\n predictions = [self.algorithm.predict(\n user_id, item_id) for item_id in items_raw_ids]\n\n # Get the top predictions, as a list of item and ratings\n top_n_predictions = self.get_top_n(\n predictions, n=top_n + len(user_ratings))\n\n # Retrieve only item ids from the given user\n predicted_items = [predicted_item_id for predicted_item_id,\n predicted_item_rating in top_n_predictions[user_id]]\n\n # Remove already rated items from the list\n for item_id, rating in user_ratings:\n item_raw_id = self.full_trainset.to_raw_iid(item_id)\n if item_raw_id in predicted_items:\n predicted_items.remove(item_raw_id)\n\n # Return only 10 items\n return predicted_items[:top_n]\n\n def ranking(self, top_n=10):\n items = self.full_trainset.ir\n items_ranking = {}\n for item in items:\n item_raw_id = self.full_trainset.to_raw_iid(item)\n n = 0\n average = 0\n pos = 0\n for user, rating in items[item]:\n n += 1\n average += rating\n average = average / n\n pos = len(\n [rating for user, rating in items[item] if rating > average])\n confidence = 0.95\n items_ranking[item_raw_id] = self.ci_lower_bound(\n pos, n, confidence)\n ranking = sorted(items_ranking, key=items_ranking.get, reverse=True)\n print(len(ranking[:top_n]))\n return ranking[:top_n]\n\n def ci_lower_bound(self, pos, n, confidence):\n if n == 0:\n return 0\n z = ndtri(1-(1-confidence)/2)\n phat = 1.0*pos/n\n return (phat + z*z/(2*n) - z * math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)\n","sub_path":"webpage/artistfm/src/public/batch/model_builder.py","file_name":"model_builder.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345181030","text":"from __future__ import (division, print_function)\n\nimport socket\nimport time\nimport copy\nimport WMCore\nfrom WMCore.Wrappers import JsonWrapper\nfrom WMCore.Services.Service import Service\n\ndef _changeRunStruct(dictData, sourceKey):\n if sourceKey in dictData:\n # convert output module\n for key, valueList in dictData[sourceKey].items():\n for valueDict in valueList:\n if \"runs\" in valueDict:\n newValue = [{\"runNumber\": run, \"lumis\": lumis} for run, lumis in valueDict[\"runs\"].items() ]\n valueDict[\"runs\"] = newValue\n return\n\ndef _convertDictToList(dictData, sourceKey, keyName, valueName):\n _changeRunStruct(dictData, sourceKey)\n newData = [{keyName: key, valueName: value} for key, value in dictData[sourceKey].items() ]\n dictData[sourceKey] = newData\n\ndef convertToArchiverFormat(fwjr):\n \"\"\"\n \"\"\"\n newFWJR = copy.deepcopy(fwjr)\n if newFWJR.get(\"steps\", False):\n steps = newFWJR['steps']\n for key in steps:\n if \"output\" in steps[key]:\n _convertDictToList(steps[key], 'output', \"outputModule\", \"value\")\n if \"input\" in steps[key]:\n _changeRunStruct(steps[key], 'input')\n return newFWJR\n \nclass WMArchiver(Service):\n \"\"\"\n This is skelton class which need be implemented.\n \"\"\"\n def __init__(self, url, header = {}):\n \"\"\"\n responseType will be either xml or json\n \"\"\"\n\n httpDict = {}\n # url is end point\n httpDict['endpoint'] = \"%s/data\" % url\n\n # cherrypy converts request.body to params when content type is set\n # application/x-www-form-urlencodeds\n httpDict.setdefault(\"content_type\", 'application/json')\n httpDict.setdefault('cacheduration', 0)\n httpDict.setdefault(\"accept_type\", \"application/json\")\n httpDict.update(header)\n self.encoder = JsonWrapper.dumps\n Service.__init__(self, httpDict) \n \n def createArchiverDoc(self, job_id, fwjr):\n \"\"\"\n job_id is jobid + retry count same as couch db _id\n \"\"\"\n newfwjr = convertToArchiverFormat(fwjr)\n # append meta data in fwjr\n newfwjr['meta_data'] = {'agent_ver': WMCore.__version__,\n 'host': socket.gethostname().lower(),\n 'fwjr_id': job_id,\n 'ts': int(time.time())\n }\n return newfwjr\n \n def archiveData(self, data):\n return self[\"requests\"].post('', {'data': data})[0]['result']","sub_path":"src/python/WMCore/Services/WMArchiver/WMArchiver.py","file_name":"WMArchiver.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"630100374","text":"import rospy\nimport random\nimport math\nimport time\nfrom robot_hand import Robot_hand\n\nclass Testbed(Robot_hand):\n def __init__(self):\n Robot_hand.__init__(self)\n self.start = rospy.Time.now()\n\n def random_move(self):\n \"\"\" Control cart with random velocity command \"\"\"\n rate = rospy.Rate(self.freq)\n start = time.time()\n while not rospy.is_shutdown():\n ob, reward = self.observe_env()\n if False:\n \n self.reset_env()\n else:\n # cmd = {}\n # for controller in self.controllers:\n # cmd[controller] =random.uniform(-3, 3)\n # self.take_action(cmd)\n if time.time() - start < 5:\n self.close()\n else:\n self.rotate(min(10, time.time() - start - 5) / 10)\n\n rate.sleep()\n\n\ndef main():\n print(\"Initializing node... \")\n rospy.init_node('robot_hand_random_move')\n test_agent = Testbed()\n rospy.on_shutdown(test_agent.clean_shutdown)\n test_agent.random_move()\n rospy.spin()\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/robot_hand_experiment/scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"562080892","text":"import maya.cmds as cmds\n\nfpsList = {'game':15,\n 'film': 24,\n 'pal': 25,\n 'ntsc': 30,\n 'show': 48,\n 'palf': 50,\n 'ntscf': 60}\n\n\ndef readChannelsData(channels, frameRange, progress, options):\n\n channelsValue = {x:[] for x in channels}\n for i in range(frameRange[0], frameRange[1]+1):\n cmds.currentTime(i)\n prcnt = (i * 100.0) / (frameRange[1]-frameRange[0]+1)\n progress.setValue(int(prcnt))\n for ch in channels:\n value = cmds.getAttr(ch)\n if ch.split('.')[-1] in ['tx','ty','tz']:\n value = value * options['scale']\n channelsValue[ch].append(value)\n return channelsValue\n\n\ndef exporter(data, frameRange):\n fps = fpsList[cmds.currentUnit(q=1, t=1)]\n startFrame = frameRange[0]-1\n length = frameRange[1]-frameRange[0] + 1\n count = len(data)\n text = '''\\\n{\n rate = %s\n start = %s\n tracklength = %s\n tracks = %s\n''' % (fps, startFrame, length, count)\n for ch, values in data.items():\n chanText = '''\\\n {\n name = %s\n data = %s\n }\\n''' % (ch.replace('.',':'), ' '.join([str(x) for x in values]))\n text += chanText\n text += '}'\n return text\n\ndef export(channels, outFile, frange, progres, options):\n dataChannels = readChannelsData(channels, frange, progres, options)\n text = exporter(dataChannels, frange)\n with open(outFile,'w') as f:\n f.write(text)\n\n","sub_path":"scripts/pw_MayaToHoudiniChannelExport-master/pw_MayaToHoudiniChannelExport-master/channelDataReader.py","file_name":"channelDataReader.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"16886718","text":"# coding=utf-8\n\n\"\"\"This library parses dotlang files migrated over from the old PHP\nsystem.\n\nIt caches them using the django caching library, but it could\npotentially just use thread-local variables. Caching seems safer at\nthe expense of another caching layer.\"\"\"\n\nimport codecs\nimport inspect\nimport os\nimport re\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.utils import translation\nfrom django.utils.functional import lazy\n\nfrom tower.management.commands.extract import tweak_message\n\n\nFORMAT_IDENTIFIER_RE = re.compile(r\"\"\"(%\n(?:\\((\\w+)\\))? # Mapping key\ns)\"\"\", re.VERBOSE)\n\n\ndef parse(path):\n \"\"\"Parse a dotlang file and return a dict of translations.\"\"\"\n trans = {}\n\n if not os.path.exists(path):\n return trans\n\n with codecs.open(path, 'r', 'utf-8', errors='replace') as lines:\n source = None\n\n for line in lines:\n if u'�' in line:\n mail_error(path, line)\n\n line = line.strip()\n if line == '' or line[0] == '#':\n continue\n\n if line[0] == ';':\n source = line[1:]\n elif source:\n for tag in ('{ok}', '{l10n-extra}'):\n if line.endswith(tag):\n line = line[:-len(tag)]\n trans[source] = line.strip()\n\n return trans\n\n\ndef mail_error(path, message):\n \"\"\"Email managers when an error is detected\"\"\"\n from django.core import mail\n subject = '%s is corrupted' % path\n mail.mail_managers(subject, message)\n\n\ndef fix_case(locale):\n \"\"\"Convert lowercase locales to uppercase: en-us -> en-US\"\"\"\n parts = locale.split('-')\n if len(parts) == 1:\n return locale\n else:\n return '%s-%s' % (parts[0], parts[1].upper())\n\n\ndef translate(text, files):\n \"\"\"Search a list of .lang files for a translation\"\"\"\n lang = fix_case(translation.get_language())\n\n tweaked_text = tweak_message(text)\n for file_ in files:\n key = \"dotlang-%s-%s\" % (lang, file_)\n rel_path = os.path.join('locale', lang, '%s.lang' % file_)\n\n trans = cache.get(key)\n if trans is None:\n path = os.path.join(settings.ROOT, rel_path)\n trans = parse(path)\n cache.set(key, trans, settings.DOTLANG_CACHE)\n\n if tweaked_text in trans:\n original = FORMAT_IDENTIFIER_RE.findall(text)\n translated = FORMAT_IDENTIFIER_RE.findall(trans[tweaked_text])\n if set(original) != set(translated):\n explanation = ('The translation has a different set of '\n 'replaced text (aka %s)')\n message = '%s\\n\\n%s\\n%s' % (explanation, text,\n trans[tweaked_text])\n mail_error(rel_path, message)\n return text\n return trans[tweaked_text]\n return text\n\n\ndef _(text, *args):\n \"\"\"\n Translate a piece of text from the global files. If `LANG_FILES` is defined\n in the module from which this function is called, those files (or file)\n will be searched first for the translation, followed by the default files.\n\n :param text: string to translate\n :param args: items for interpolation into `text`\n :return: translated string\n \"\"\"\n lang_files = settings.DOTLANG_FILES\n frame = inspect.currentframe()\n if frame is None:\n if settings.DEBUG:\n import warnings\n warnings.warn('Your Python runtime does not support the frame '\n 'stack. Extra LANG_FILES specified in Python '\n 'source files will not work.', RuntimeWarning)\n else:\n try:\n # gets value of LANG_FILE constant in calling module if specified\n new_lang_files = frame.f_back.f_globals.get('LANG_FILES')\n finally:\n del frame\n if new_lang_files:\n if isinstance(new_lang_files, basestring):\n new_lang_files = [new_lang_files]\n lang_files = new_lang_files + lang_files\n\n text = translate(text, lang_files)\n if args:\n text = text % args\n return text\n\n\n_lazy = lazy(_, unicode)\n","sub_path":"snippets/l10n_utils/dotlang.py","file_name":"dotlang.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14069380","text":"from avito import from_avito \nfrom youla import from_youla\nfrom irr import from_irr\nfrom multiprocessing import Pool\n\n\n\nkeywords = {\n\t'Арбидол',\n\t'ферон', \n\t'Кагоцел', \n\t'маски медицинские', \n\t'антисептичес', \n\t'хлоргексидин', \n\t'плаквенил'\n\t}\n\nregions = {\n\t'avito': {'ufa',\n\t\t'bashkortostan', \n\t\t'ekaterinburg', \n\t\t'sverdlovskaya_oblast', \n\t\t'tyumen', \n\t\t'tyumenskaya_oblast', \n\t\t'chelyabinskaya_oblast', \n\t\t'chelyabinsk', \n\t\t'moskva_i_mo'\n\t\t},\n\t'youla' : {\n\t\t'ufa',\n\t\t'ekaterinburg',\n\t\t'tyumen', \n\t\t'chelyabinsk',\n\t\t'moskva'\n\t\t},\n\n\t'irr' : {\n\t\t'ufa',\n\t\t'bashkortostan-resp',\n\t\t'ekaterinburg',\n\t\t'sverdlovskaya-obl',\n\t\t'tyumen',\n\t\t'tyumenskaya-obl',\n\t\t'chelyabinsk',\n\t\t'chelyabinskaya-obl',\n\t\t'moscow'\n\t\t}\n\t}\n\n\n\ndef data_prepare(keywords, regions, key):\n\tdata = []\n\tfor region in regions[key]:\n\t\tfor keys in keywords:\n\t\t\tdata.append([region, keys])\n\treturn data\n\n\n\navito = data_prepare(keywords, regions, 'avito')\nirr = data_prepare(keywords, regions, 'irr')\nyoula = data_prepare(keywords, regions, 'youla')\n\n\n#for item in avito:\n#\tfrom_avito(item)\n\nif __name__ == '__main__':\n\twith Pool(5) as p:\n\t\tresults1 = p.map(from_avito, avito)\n\t\tresults2 = p.map(from_youla, youla)\n\t\tresults3 = p.map(from_irr, irr)\n\n\n\n","sub_path":"handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"199538290","text":"__module_name__ = 'dnd.location'\n__module_version__ = '1.0'\n__module_description__ = 'Choose a geographic location'\n__module_author__ = 'Allen Stetson'\n\n\nfrom random import randint\n\nclass LocationGenerator(object):\n def __init__(self, location=None, world=None, kingdom=None, conditionType=None):\n self.location = location\n self.world = world\n self.kingdom = kingdom\n self.conditionType = conditionType\n self.nearbyFeatures = []\n self.nearbyFeature = None\n if not self.location:\n self.location = self.getLocation()\n self.getNearbyFeatures()\n\n def getLocation(self):\n if self.world and self.world.lower() == 'faerun':\n # Load the list kingdoms\n faerunFile = file(\"/work/td/xchat/lists/kingdoms_of_faerun.txt\")\n faerunList = faerunFile.readlines()\n loc = faerunList[randint(0,len(faerunList)-1)]\n loc = loc.replace('\\n', '')\n self.location = loc\n return self.location\n locations = ['coast','mountains','swamp','underdark','grasslands','jungle','city','settlement','fort','forest',\n 'tundra','hills','lowlands','steppe','marsh','meadow']\n if self.conditionType == \"cold\":\n locations.extend(['icelands'])\n elif self.conditionType == \"hot\":\n locations.extend(['desert'])\n self.location = locations[randint(0,len(locations)-1)]\n return self.location\n\n def getNearbyFeatures(self):\n if self.location == 'coast':\n self.nearbyFeatures = ['rocky shoals','tide pools','docks','creaking galleons','shipwreck',\n 'enormous statue']\n elif self.location == 'mountains':\n self.nearbyFeatures = ['rocky cliffs','cliff dwelling','rocky temple','mines','craggy rocks']\n elif self.location == 'swamp':\n self.nearbyFeatures = ['thick muddy waters','looming swamp trees']\n elif self.location == 'underdark':\n self.nearbyFeatures = ['surface above']\n elif self.location == 'grasslands':\n self.nearbyFeatures = ['grassy plains','vineyard','catfolk village','savannah','lone acacia tree']\n elif self.location == 'jungle':\n self.nearbyFeatures = ['leafy canopy','enormous ant hills','broad fronds','stagnant water','leafy temple',\n 'makeshift dwellings']\n elif self.location == 'city':\n self.nearbyFeatures = ['huddled rooftops','dirty streets','crowded streets','empty buildings',\n 'festive buildings','bustling vendor stands','numerous carriages','guild halls',\n 'temples','royal castle','nobles\\' homes','slums']\n elif self.location == 'settlement':\n self.nearbyFeatures = ['makeshift structures',\"woodcutter's shop\",'stables','livestock pens',\n 'food storage','church','adjacent woods','general store']\n elif self.location == 'fort':\n self.nearbyFeatures = ['barracks',\"captain's abode\",'protective wall','map room','stables','war machines',\n 'weapons store',\"raven's roost\",'lookout tower']\n elif self.location == 'forest':\n self.nearbyFeatures = ['enormous tree trunks','stone menhir','dry pines','proud trees']\n elif self.location == 'tundra':\n self.nearbyFeatures = ['stunted trees','matted grass']\n elif self.location == 'hills':\n self.nearbyFeatures = ['rocky deposits','rolling hilltops','emerald green grass',\n 'dry mustard-colored weeds','ancient ruins']\n elif self.location == 'lowlands':\n self.nearbyFeatures = ['peat bogs','sucking mud','sickly grass','verdant pastures']\n elif self.location == 'steppe':\n self.nearbyFeatures = ['shrubs','briar','pebbly ground']\n elif self.location == 'marsh':\n self.nearbyFeatures = ['reeds','foul water','lonely hut','menhir','druid temple','hatchery', 'dam',\n 'coven house','manticore den', 'lizardfolk village',\"green hag's cabin\"]\n elif self.location == 'meadow':\n self.nearbyFeatures = ['wildflowers','lush grasses','hollow blackened trees','stables','farm house',\n 'windmill','cottage']\n elif self.location == 'icelands':\n self.nearbyFeatures = ['endless hills of snow','snowy wastelands','unforgiving drifts',\n 'mountains of white','lone dwelling']\n elif self.location == 'desert':\n self.nearbyFeatures = ['vast expanse of sandy dunes','menacing cacti','oasis','coconut palms',\n 'flat red rocks','mesa','thorny shrubs','tumbleweed-strewn desert floor']\n else:\n self.nearbyFeatures = ['nearby features']\n\n self.nearbyFeature = self.nearbyFeatures[randint(0,len(self.nearbyFeatures)-1)]\n","sub_path":"mod/locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"515363390","text":"\"\"\"\nConfiguration file for flask sample application\n\"\"\"\nimport os\n\n# enable CSRF\nWTF_CSRF_ENABLED = True\n\n# secret key for authentication\nSECRET_KEY = os.environ.get(\"FLASK_SECRET_KEY\", \"you-will-never-guess\")\nAUTH_TOKEN = os.environ.get(\"FLASK_AUTH_TOKEN\", \"another-secret\")\n\n# Sample client certificate example for 12 factor app\n# You would want to store your entire pem in an environment variable\n# with something like:\n# ```\n# export CONSUMER_KEY_CERT=$(cat <\n# EOF\n# )\n# ```\n\nSQLALCHEMY_DATABASE_URI = 'mysql://www-data:password@localhost/algebra742live'\n#SQLALCHEMY_DATABASE_URI = 'sqlite:///{:s}'.format(os.path.abspath(os.path.join(os.path.dirname(__file__),'algebra742.db')))\nREDIS_HOST = 'localhost'\nREDIS_PORT = 6379\nREDIS_DB = 0\n\nCONSUMER_KEY_PEM_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__),'consumer_key.pem'))\nwith open(CONSUMER_KEY_PEM_FILE, 'w') as wfile:\n wfile.write(os.environ.get('CONSUMER_KEY_CERT', ''))\n\nPYLTI_CONFIG = {\n \"consumers\": {\n \"__consumer_key__\": {\n \"secret\": os.environ.get(\"CONSUMER_KEY_SECRET\", \"__lti_secret__\"),\n \"cert\": CONSUMER_KEY_PEM_FILE\n }\n }\n}\n\n# Remap URL to fix edX's misrepresentation of https protocol.\n# You can add another dict entry if you have trouble with the\n# PyLti URL.\nPYLTI_URL_FIX = {\n \"https://localhost:8000/\": {\n \"https://localhost:8000/\": \"http://localhost:8000/\"\n },\n \"https://localhost/\": {\n \"https://localhost/\": \"http://192.168.33.10/\"\n }\n}\n\nRESOURCES_DIR = os.path.join(os.path.dirname(__file__), 'resources')\nMARKDOWN_INCLUDE_PATH = os.path.join(os.path.dirname(__file__), 'resources', 'include')\nPRIVATE_DATA_PATH = os.path.join(os.path.dirname(__file__), 'private')\nQUESTION_DIGRAPHS_DIR = os.path.join(os.path.dirname(__file__), 'content', 'question_digraphs')\nSNOW_QM_COLLECTIONS_DIR = os.path.join(os.path.dirname(__file__), 'content', 'tasks')\nGRAPHICS_TEMPLATE_DIR = os.path.join(os.path.dirname(__file__), 'content','graphics','templates')\nGRAPHICS_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), 'content','graphics','output')\n","sub_path":"algebra742live/default_config.py","file_name":"default_config.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"366430274","text":"# coding=utf-8\n#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom __future__ import absolute_import\n\nimport argparse\nfrom datetime import datetime\nfrom datetime import timedelta\nimport logging\nimport os\nimport re\nimport time\n\nfrom .bisect import Bisector\nfrom .evaluator.browser import BrowserEvaluator\nfrom .evaluator.js import JSEvaluator\n\nlog = logging.getLogger('autobisect')\n\n\nclass ExpandPath(argparse.Action):\n \"\"\"\n Expand user and relative-paths\n \"\"\"\n def __call__(self, parser, namespace, values, option_string=None):\n setattr(namespace, self.dest, os.path.abspath(os.path.expanduser(values)))\n\n\ndef _parse_args(argv=None):\n \"\"\"\n Argument parser\n \"\"\"\n parser = argparse.ArgumentParser(description='Autobisection tool for Mozilla Firefox and SpiderMonkey')\n\n global_args = argparse.ArgumentParser(add_help=False)\n global_args.add_argument('testcase', help='Path to testcase')\n\n boundary_args = global_args.add_argument_group('boundary arguments (YYYY-MM-DD or SHA1 revision)')\n boundary_args.add_argument('--start', default=(datetime.utcnow()-timedelta(days=364)).strftime('%Y-%m-%d'),\n help='Start revision (default: earliest available TC build)')\n boundary_args.add_argument('--end', default=datetime.utcnow().strftime('%Y-%m-%d'),\n help='End revision (default: latest available TC build)')\n\n bisection_args = global_args.add_argument_group('bisection arguments')\n bisection_args.add_argument('--timeout', type=int, default=60,\n help='Maximum iteration time in seconds (default: %(default)s)')\n bisection_args.add_argument('--repeat', type=int, default=1,\n help='Number of times to evaluate testcase (per build)')\n bisection_args.add_argument('--config', action=ExpandPath, help='Path to optional config file')\n bisection_args.add_argument('--find-fix', action='store_true', help='Identify fix date')\n\n branch_args = global_args.add_argument_group('branch')\n branch_selector = branch_args.add_mutually_exclusive_group()\n branch_selector.add_argument('--inbound', action='store_const', const='inbound', dest='branch',\n help='Download from mozilla-inbound')\n branch_selector.add_argument('--central', action='store_const', const='central', dest='branch',\n help='Download from mozilla-central (default)')\n branch_selector.add_argument('--release', action='store_const', const='release', dest='branch',\n help='Download from mozilla-release')\n branch_selector.add_argument('--beta', action='store_const', const='beta', dest='branch',\n help='Download from mozilla-beta')\n branch_selector.add_argument('--esr', action='store_const', const='esr52', dest='branch',\n help='Download from mozilla-esr52')\n\n build_args = global_args.add_argument_group('build arguments')\n build_args.add_argument('--asan', action='store_true', help='Test asan builds')\n build_args.add_argument('--debug', action='store_true', help='Test debug builds')\n build_args.add_argument('--fuzzing', action='store_true', help='Test --enable-fuzzing builds')\n build_args.add_argument('--coverage', action='store_true', help='Test --coverage builds')\n build_args.add_argument('--32', dest='arch_32', action='store_true',\n help='Test 32 bit version of browser on 64 bit system.')\n\n subparsers = parser.add_subparsers(dest='target')\n firefox_sub = subparsers.add_parser('firefox', parents=[global_args], help='Bisect Firefox testcase')\n ffp_args = firefox_sub.add_argument_group('launcher arguments')\n ffp_args.add_argument('--asserts', action='store_true', help='Detect soft assertions')\n ffp_args.add_argument('--detect', choices=['crash', 'memory', 'log', 'timeout'], default='crash',\n help='Type of failure to detect (default: %(default)s)')\n ffp_args.add_argument('--launch-timeout', type=int, default=300,\n help='Maximum launch time in seconds (default: %(default)s)')\n ffp_args.add_argument('--ext', action=ExpandPath, help='Path to fuzzPriv extension')\n ffp_args.add_argument('--prefs', action=ExpandPath, help='Path to preference file')\n ffp_args.add_argument('--profile', action=ExpandPath, help='Path to profile directory')\n ffp_args.add_argument('--memory', type=int, help='Process memory limit in MBs (default: no limit)')\n ffp_args.add_argument('--log-limit', type=int, help='Log file size limit in MBs (default: no limit)')\n ffp_args.add_argument('--gdb', action='store_true', help='Use GDB')\n ffp_args.add_argument('--valgrind', action='store_true', help='Use valgrind')\n ffp_args.add_argument('--xvfb', action='store_true', help='Use xvfb (Linux only)')\n\n js_sub = subparsers.add_parser('js', parents=[global_args], help='Bisect SpiderMonkey testcase')\n js_args = js_sub.add_argument_group('launcher arguments')\n js_args.add_argument('--flags', help='Runtime flags to pass to the binary')\n js_args.add_argument('--detect', choices=['crash', 'diff', 'hang', 'output'], default='crash',\n help='Type of failure to detect (default: %(default)s)')\n\n js_diff_args = js_sub.add_argument_group('diff arguments')\n js_diff_args.add_argument('--arg_1', help='Set of arguments to supply to the first run')\n js_diff_args.add_argument('--arg_2', help='Set of arguments to supply to the second run')\n\n js_hang_args = js_sub.add_argument_group('hang arguments')\n js_hang_args.add_argument('--hang-time', type=int, metavar='TIME',\n help='Hang time threshold (must be greater than timeout)')\n\n js_out_args = js_sub.add_argument_group('output arguments')\n js_out_args.add_argument('--match', help='Mark as interesting if string detected in output')\n js_out_args.add_argument('--regex', help='Treat match as a regex')\n\n args = parser.parse_args(argv)\n\n if not args.branch:\n args.branch = 'central'\n\n if not re.match(r'^[0-9[a-f]{12,40}$|^[0-9]{4}-[0-9]{2}-[0-9]{2}$', args.start):\n parser.error('Invalid start value supplied')\n if not re.match(r'^[0-9[a-f]{12,40}$|^[0-9]{4}-[0-9]{2}-[0-9]{2}$', args.end):\n parser.error('Invalid end value supplied')\n if args.timeout <= 0:\n parser.error('Invalid timeout value supplied')\n\n if args.target == 'firefox':\n if args.detect == 'log' and args.log_limit is None:\n parser.error('Detect mode set to log-limit but no limit set!')\n if args.detect == 'memory' and args.memory is None:\n parser.error('Detect mode set to log-limit but no limit set!')\n elif args.target == 'js':\n if args.detect == 'diff':\n if not args.arg_1 or not args.args_2:\n parser.error('Detect mode set to diff but no arguments supplied!')\n if args.detect == 'hang':\n if args.hang_time is None:\n parser.error('Detect mode set to hang but no hang threshold supplied!')\n if args.hang_time <= 0:\n parser.error('Invalid hangout threshold value supplied!')\n if args.hang_time > args.timeout:\n parser.error('Hang threshold greater than timeout!')\n if args.detect == 'output':\n if args.match is None:\n parser.error('Detect mode set to output but no output string supplied!')\n\n return args\n\n\ndef main(argv=None):\n \"\"\"\n Autobisect main entry point\n \"\"\"\n log_level = logging.INFO\n log_fmt = '[%(asctime)s] %(message)s'\n if bool(os.getenv('DEBUG')):\n log_level = logging.DEBUG\n log_fmt = '%(levelname).1s %(name)s [%(asctime)s] %(message)s'\n logging.basicConfig(format=log_fmt, datefmt='%Y-%m-%d %H:%M:%S', level=log_level)\n logging.getLogger('requests').setLevel(logging.WARNING)\n\n args = _parse_args(argv)\n\n if args.target == 'firefox':\n evaluator = BrowserEvaluator(args)\n else:\n evaluator = JSEvaluator(args)\n\n bisector = Bisector(evaluator, args)\n start_time = time.time()\n bisector.bisect()\n end_time = time.time()\n elapsed = timedelta(seconds=(int(end_time - start_time)))\n log.info('Bisection completed in: %s' % elapsed)\n","sub_path":"autobisect/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"337896111","text":"#!/usr/bin/python\nfrom flask import Flask, jsonify, redirect, request, current_app\nfrom functools import wraps\nimport cPickle as pickle\nimport pandas as pd\nimport numpy as np\nimport os\nfrom train import StemTokenizer\n\napp = Flask(__name__)\npath = os.path.dirname(os.path.realpath(__file__))\n\nwith open(path + '/export/models', 'rb') as f:\n models = pickle.load(f)\nwith open(path + '/export/vectorizer', 'rb') as f:\n vectorizer = pickle.load(f)\nwith open(path + '/export/service_items', 'rb') as f:\n service_items = pickle.load(f)\n\n\ndef support_jsonp(f):\n \"\"\"Wraps JSONified output for JSONP\"\"\"\n @wraps(f)\n def decorated_function(*args, **kwargs):\n callback = request.args.get('callback', False)\n if callback:\n content = str(callback) + '(' + str(f().data) + ')'\n return current_app.response_class(\n content, mimetype='application/json')\n else:\n return f(*args, **kwargs)\n return decorated_function\n\n\n@app.route('/api/v1.0/serviceItems', methods=['GET'])\n@support_jsonp\ndef get_tasks():\n vehicle_maker = request.args.get('vehicle_maker')\n comments = request.args.get('comments') + ' ' + vehicle_maker\n predictions = [0] * len(models)\n components = comments.split(',')\n dummy = vectorizer.transform([''])\n vehicle_maker = np.char.upper(np.array([vehicle_maker]))\n X_test_vec = []\n for comment in components:\n X_test_vec.append(vectorizer.transform([comment]))\n for label_idx in xrange(len(models)):\n predictions[label_idx] = 0\n for i in xrange(len(X_test_vec)):\n predictions[label_idx] += \\\n max(0,\n models[label_idx].predict_proba(\n X_test_vec[i], vehicle_maker)[:, 1] -\n models[label_idx].predict_proba(\n dummy, vehicle_maker)[:, 1])\n\n suggestion = pd.DataFrame()\n suggestion['items'] = service_items.description\n suggestion['prediction'] = predictions\n suggestion.sort('prediction', ascending=False, inplace=True)\n suggestion = suggestion[suggestion['prediction'] > 0]\n return jsonify({'results': suggestion['items'].tolist()})\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"34981497","text":"# Copyright 2012 Managed I.T.\n#\n# Author: Kiall Mac Innes \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport json\n\nfrom designateclient import utils\nfrom designateclient.v1.base import CrudController\nfrom designateclient import warlock\n\n\nZone = warlock.model_factory(utils.load_schema('v2', 'zone'))\n\n\nclass ZonesController(CrudController):\n def list(self):\n \"\"\"\n Retrieve a list of zones\n\n :returns: A list of :class:`Zone`s\n \"\"\"\n response = self.client.get('/zones')\n\n return [Zone(i) for i in response.json()['zones']]\n\n def get(self, zone_id):\n \"\"\"\n Retrieve a zone\n\n :param zone_id: Zone Identifier\n :returns: :class:`Zone`\n \"\"\"\n response = self.client.get('/zones/%s' % zone_id)\n\n return Zone(response.json())\n\n def create(self, zone):\n \"\"\"\n Create a zone\n\n :param zone: A :class:`Zone` to create\n :returns: :class:`Zone`\n \"\"\"\n zone = {\"zone\": utils.convert(zone)}\n response = self.client.post('/zones', data=json.dumps(zone))\n\n return Zone(response.json())\n\n def update(self, zone):\n \"\"\"\n Update a zone\n\n :param zone: A :class:`Zone` to update\n :returns: :class:`Zone`\n \"\"\"\n pdb.set_trace()\n id = zone['zone']['id'] \n del zone['zone']['id'] \n response = self.client.patch('/zones/%s' % id, \n data=json.dumps(zone)) \n \n return Zone(response.json())\n\n def delete(self, zone):\n \"\"\"\n Delete a zone\n\n :param zone: A :class:`Zone`, or Zone Identifier to delete\n \"\"\"\n if isinstance(zone, Zone):\n self.client.delete('/zones/%s' % zone.id)\n else:\n self.client.delete('/zones/%s' % zone)\n\n","sub_path":"designateclient/v2/zones.py","file_name":"zones.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"641744564","text":"# -*- coding: utf-8 -*-\n\nfrom flask_script import Manager, Server\nfrom flaskapp.application import create_app\n\nmanager = Manager(create_app)\nmanager.add_command('run', Server())\n\nmanager.add_option('-c', '--config',\n dest=\"config\",\n required=False,\n help=\"config file\")\n\nif __name__ == \"__main__\":\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"241834430","text":"import ast\nimport datetime\nimport os.path\nimport sqlite3 as sqlite\nimport subprocess\nimport time\nfrom bottle import route, run, template, request, static_file, redirect\nfrom os import listdir, getcwd\n\n\n#CONSTANTS\nDATABASE = 'test.db'\n\n#PAGE ROUTES\n@route('/')\ndef index():\n index_page_content = \"\"\"\n
\n category: \n upload: \n \n
\n \"\"\"\n return index_page_content\n\n@route('/content/')\ndef view_content(contentId):\n try:\n conn = create_or_open_db(DATABASE)\n #sql = 'select * from content;'\n sql = '''select * from content where TOKENID like ?;'''\n result = conn.execute(sql, [contentId])\n #result = conn.execute(sql)\n content_id = result.fetchone()[3]\n \n #conn.commit()\n return 'The tokenId will be: {}'.format(content_id)\n except Exception as e:\n print(e)\n finally:\n conn.close()\n\n@route('/upload_file', method=\"POST\")\ndef upload_file():\n try:\n #get references to the file, file name\n upload = request.files.get('upload')\n save_file(upload)\n #create a database connection, and save the content to the database\n conn = create_or_open_db(DATABASE)\n cursor = conn.cursor()\n name = upload.filename\n author = 'Standin Author'\n timestamp = str(datetime.datetime.now())\n SQL = 'INSERT INTO content(FILENAME, AUTHOR, DATESTAMP) VALUES(?, ?, ?);'\n cursor.execute(SQL, [name, author, timestamp])\n #keep a reference to that item's SQL primary index in memory for future step\n #also keep a reference to the filename in memory; in future the content's hash as well\n row_id = cursor.lastrowid\n #server then uses that in-mem filename to create a new token on the blockchain\n create_token = subprocess.run(['node', './test/proto.js', name], stdout=subprocess.PIPE)\n time.sleep(15)\n #keep the transactionHash in memory for a future step\n txHash = create_token.stdout.decode('utf-8')\n\n #server then queries Blockchain event log\n get_logs = subprocess.run(['node', './test/logs.js'], stdout=subprocess.PIPE)\n get_logs = get_logs.stdout\n if type(get_logs) == bytes:\n get_logs = get_logs.decode('utf-8')\n if type(get_logs) == str:\n get_logs = ast.literal_eval(get_logs)\n #iterative logs & match the event log to the transaction hash saved from above\n \"\"\"\n eventLog = None\n print('point e')\n for log in get_logs:\n if log['transactionHash'] == txHash:\n eventLog = log\n \"\"\"\n #get the tokenId from that transaction log\n contentId = get_logs[1]\n\n #with the DB connection still open, get the row by the primary index still in memory\n #update that record with the tokenId, save it again\n SQL = 'update content set TOKENID = ? where id = ?;'\n cursor.execute(SQL, [contentId, row_id])\n except Exception as e:\n print(e)\n finally:\n #close connection, redirect user to page for that piece of content\n conn.commit()\n conn.close()\n new_route = '/content/{}'.format(contentId)\n return redirect(new_route)\n\n#SUPPORTING METHODS\ndef create_or_open_db(db_file):\n try:\n db_is_new = not os.path.exists(db_file)\n conn = sqlite.connect(db_file)\n if db_is_new:\n SQL = 'create table if not exists content(ID INTEGER PRIMARY KEY AUTOINCREMENT, FILENAME TEXT, AUTHOR TEXT, TOKENID TEXT, DATESTAMP TEXT);'\n conn.execute(SQL)\n conn.commit()\n return conn\n except Exception as e:\n raise e\n\ndef save_file(upload):\n try:\n _file = upload.file.read()\n name, ext = os.path.splitext(upload.filename)\n if ext not in ('.txt', '.pdf'):\n return('File extension not allowed')\n save_path = '/tmp/tests/'\n upload.save(save_path)\n except Exception as e:\n print(e)\n\n\nif __name__ == '__main__':\n run(host='0.0.0.0', port=8880, debug=True)\n","sub_path":"prototype/two.py","file_name":"two.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"233442101","text":"\ninfo_cities = []\nn_cidade = 0\n\ndef separa(s):\n \"\"\"\n feito para testar se o problema não está no split do URI\n :param s: string com espaço\n :return:\n \"\"\"\n return int(s[s.find(' '):]), int(s[:s.find(' ')+1])\n\nwhile True:\n x = int(input())\n info_cities = []\n consume = []\n total_consume, total_people = 0, 0\n\n if x == 0:\n break\n\n for x in range(0, x):\n auxiliar = input()\n consumo, pessoas = separa(auxiliar)\n total_consume += int(consumo)\n total_people += int(pessoas)\n consumo = int(consumo) // int(pessoas)\n consume.append([pessoas, consumo])\n total_consume = total_consume/total_people\n\n consume = sorted(consume, key=lambda consume: consume[1])\n\n n_cidade += 1\n\n total_consume = list(str(int(total_consume*100)))\n total_consume.insert(-2, \".\")\n total_consume = str().join(total_consume)\n\n aux = \"\"\n for i in consume:\n aux += str(i[0]) + \"-\" + str(i[1])+ \" \"\n\n # info_cities.append([n_cidade, aux, total_consume])\n print(\"Cidade# %s:\" % n_cidade)\n print(aux)\n print(\"Consumo medio: %s m3.\" % total_consume)\n print(\"\")\n\n\n # for i in range(0, len(info_cities)):\n # print(\"Cidade# %s:\" % info_cities[i][0])\n # print(info_cities[i][1])\n # print(\"Consumo médio: %s m3.\" % info_cities[i][2])\n #\n # if i < len(info_cities)-1:\n # print(\"\")\n\n\n\n# for i in range(0, len(info_cities)):\n# print(info_cities[i][0])\n# print([(print(*x)) for x in info_cities[i][1]])","sub_path":"estiagem3.py","file_name":"estiagem3.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"589150733","text":"from sklearn.decomposition import TruncatedSVD\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import pairwise_distances, euclidean_distances\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem import LancasterStemmer\nimport spacy, pandas as pd\nimport numpy as np\nimport re\nfrom stop_words import get_stop_words\n\n\n\"\"\"\nclass Tokenizer(object):\n def __init__(self):\n self.tok = RegexpTokenizer(r'some_regular_expression')\n self.stemmer = LancasterStemmer()\n def __call__(self, doc):\n return [self.stemmer.stem(token)\n for token in self.tok.tokenize(doc)]\n\"\"\"\n\nvectorizer = TfidfVectorizer(stop_words=get_stop_words(\"german\"),\n use_idf=True,\n smooth_idf=True)\n\nsvd_model = TruncatedSVD(n_components=300,\n algorithm=\"randomized\",\n n_iter=10,\n random_state=42)\n\nsvd_transformer = Pipeline([(\"tfidf\", vectorizer),\n (\"svd\", svd_model)])\n\ndf = pd.read_csv(\"./merged_data/corpus_HGB.csv\", encoding=\"utf8\")\n\ndocument_corpus = [str(cell) for cell in df.iloc[:,1]]\ndocument_corpus = [re.sub(\"[^A-Za-züäöÜÄÖß]\", \" \", doc.lower()) for doc in document_corpus]\ndocument_corpus = [re.sub(\"\\s+\", \" \", doc) for doc in document_corpus]\ndocument_corpus = [doc for doc in document_corpus if len(doc) > 5]\n\nsvd_matrix = svd_transformer.fit_transform(document_corpus)\n\nquery = \"\"\"Angabe von Name und Sitz des Mutterunternehmens der Kapitalgesellschaft, \ndas den Konzernabschluss für den größten Kreis von Unternehmen aufstellt, \nsowie der Ort, wo der von diesem Mutterunternehmen aufgestellte \nKonzernabschluss erhältlich ist.\"\"\".lower()\n\nquery = [query]\n\nquery_vector = svd_transformer.transform(query)\n\ndistance_matrix = pairwise_distances(query_vector,\n svd_matrix,\n metric=\"cosine\",\n n_jobs=-1)\n\n#index, number\nresults = [(index, item) for index, item in enumerate(distance_matrix[0])]\nresults_sorted = sorted(results, key=lambda x: x[1])\ntop5 = results_sorted[:40]\n\n#print(top5)\nprint(\"Query: %s\" % query)\n#print(\"\\nAssessing index %s\\nBest match: %s\" % (nearest[0], document_corpus[nearest[0]]))\n\n\nfor i, top in enumerate(top5):\n print(i, document_corpus[top[0]])","sub_path":"py/LSI.py","file_name":"LSI.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"466837958","text":"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nreq = requests.get('http://finance.yahoo.com/q/hp?s=GE&a=00&b=2&c=1962&d=03&e=25&f=2016&g=d')\nif req.status_code == 200:\n print('requisição bem sucedida')\n content = req.content\n\ns = BeautifulSoup(content, 'html.parser')\ntabela = s.find(name='table')\n\ntabela_str = str(tabela)\ndf = pd.read_html(tabela_str)[0]\nprint(df)\n\n","sub_path":"Task3.py","file_name":"Task3.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124326864","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# Students who graduated college between 2010-2012 \n# Data from [American Community Servey](https://www.census.gov/programs-surveys/acs/), cleaned by and uploaded to FiveThirtyEight's [Github repo](https://github.com/fivethirtyeight/data/tree/master/college-majors)\n# \n# Each row in the data set represents one college major and includes the following:\n# \n# |Column|Description|\n# |:|:|\n# |Rank|Rank by median earnings|\n# |Major_code|Major code, FO1DP in ACS PUMS|\n# |Major|Major description|\n# |Major_category|Category of major from Carnevale et al|\n# |Total|Total number of people with major|\n# |Sample_size|Sample size (unweighted) of full-time, year-round ONLY (used for earnings)|\n# |Men |Male graduates|\n# |Women |Female graduates|\n# |ShareWomen|Women as share of total|\n# |Employed|Number employed (ESR == 1 or 2)|\n# |Full_time|Employed 35 hours or more|\n# |Part_time|Employed less than 35 hours|\n# |Full_time_year_round| \tEmployed at least 50 weeks (WKW == 1) and at least 35 hours (WKHP >= 35)|\n# |Unemployed|Number unemployed (ESR == 3)|\n# |Unemployment_rate|Unemployed / (Unemployed + Employed)|\n# |Median|Median earnings of full-time, year-round workers|\n# |P25th|25th percentile of earnigns|\n# |P75th|75th percentile of earnings|\n# |College_jobs|Number with job requiring a college degree|\n# |Non_college_jobs|Number with job not requiring a college degree|\n# |Low_wage_jobs|Number in low-wage service jobs|\n# \n# Exploritory data visualizations can be used to answer questions such as:\n# \n# 1. Do students in more popular majors each more money?\n# * Using scatter plots.\n# 2. How many majors are predominantly male/female?\n# * Using histograms.\n# 3. Which category of majors have the most students?\n# * using bar plots.\n# \n# These will be explored by reading the `.csv` file into a `pandas` dataframe and using `pandas` front-end to matplotlib.\n# \n\n# In[1]:\n\n\nimport pandas as pd\nimport matplotlib\nget_ipython().magic('matplotlib inline')\n\nrecent_grads = pd.read_csv('recent-grads.csv')\n#recent_grads.head() #sample data\n\nrecent_grads.describe()\n\n\n# In[2]:\n\n\nnum_nulls = recent_grads.isna().any(axis=1).value_counts()[1] \nprint('There are {} row(s) containing null values...'.format(num_nulls))\n\nraw_data_count = len(recent_grads)\nrecent_grads.dropna(inplace=True)\nclean_data_count = len(recent_grads)\n\nprint(\"Removed {0} row(s).\".format(raw_data_count - clean_data_count))\n\n\n\n# Now that null values have been removed from the data set we can use `pandas` as a front end to `matplotlib` and explore the data.\n\n# ## Salary vs. sample size\n# We can look at the median salary of graduates in relation to the number of grauates in each major. We can also look at how the absolute number of male and female graduates affects salary. The rate of unemplyment can also be seen. \n# \n# More usefull measures, such as the unemplyment rate and earning potential as a function of the gender-ratio of graduates are also plotted.\n\n# ##### Median salary vs absoulte number of graduates\n\n# In[3]:\n\n\nmed_v_sample = recent_grads.plot(x='Sample_size', y='Median', kind='scatter')\nmed_v_sample.set_title('Median salary vs sample size')\n\n\n# Majors from courses with low sample sizes tend to earn higher salaries. Low sample sizes may lead to outliers.\n\n# In[4]:\n\n\nmed_v_fulltime = recent_grads.plot(x='Full_time', y='Median', kind='scatter')\nmed_v_fulltime.set_title('Median salary for full-time employees')\n\n\n# The median salary for full-time emplyees is similar to the meadian salary for the sample size above. \n\n# In[5]:\n\n\nunemp_v_sample = recent_grads.plot(\n x='Sample_size', y='Unemployment_rate', kind=\"scatter\"\n )\nunemp_v_sample.set_title('Unemplyment rate for number of graduates')\n\n\n# Majors from courses with a smaller sample size exhibit higher vairiance in the unemplyment rate than majors with more data. This may be an artifact of small sample sizes, but it may imply that majors with few graduates are either in large or small demand, depending on the major.\n# \n# ----------------------------------------------------------\n\n# #### The absolute number of male or female graduates has no significant impact on unemplyment rates:\n\n# In[6]:\n\n\nrecent_grads.plot(x='Men', y='Median', kind='scatter')\n\n\n# The difference in earnings for male (above) and female grads (below) is reasonably consistant for partiular courses.\n# \n\n# In[7]:\n\n\nrecent_grads.plot(x='Women', y='Median', kind='scatter')\n\n\n\n# ##### Unemplyment rates and salary vs gender-ratio\n# More useful insights can be gained by looking at the proportion of female-to-male gradutes for each major,\n\n# In[8]:\n\n\nrecent_grads.plot(x='ShareWomen', y='Unemployment_rate', kind='scatter')\n\n\n# There is no correlation between the proportion of female graduates and employment prospects.\n\n# In[9]:\n\n\nrecent_grads.plot(x='ShareWomen', y='Median', kind='scatter')\n\n\n# There is, however, a negative correlation between the proportion of female graduates and the median pay.\n\n# ## Distributions\n\n# In[10]:\n\n\nsample_hist = recent_grads['Sample_size'].hist(bins=50,range=(0,5000))\nsample_hist.set_ylabel('Sample Size')\n#recent_grads['Sample_size'].plot(kind='hist')\n\n\n# 75 majors had a response rate of 100 or fewer graduates. 30 courses have between 100-200 responses. These two intervals account for over half of the 172 majors included in the (clean) data set. One major, however, recieved over 4000 responses.\n\n# In[11]:\n\n\nmedian_hist = recent_grads['Median'].hist(bins=24,range=(0,120000))\nmedian_hist.set_ylabel('Median Salary')\nmedian_hist.set_xlabel('$5,000 intervals')\n#recent_grads['Median'].plot(kind='hist')\n\n\n# Most graduates (45 majors) earn between \\$30,000-\\$35,000. The \\$30,000-\\$40,000 salary range accounts for about half of all recent graduates in the sample.\n\n# In[12]:\n\n\nemployed_hist = recent_grads['Employed'].hist(bins=20,range=(0,200000))\nemployed_hist.set_ylabel('Employed grads')\n#recent_grads['Employed']\n\n\n# About half of the majors had 10,000 graduates in emplyment. \n\n# In[13]:\n\n\nfull_time_hist = recent_grads['Full_time'].hist(bins=20,range=(0,200000))\n\n\n#recent_grads['Full_time'].plot(kind='hist')\n\n\n# The histogram for employed graduates id very similar to the histogram for full-time employment. Most of the emplyed graduates are working full time.\n\n# In[14]:\n\n\nratio_hist = recent_grads['ShareWomen'].hist(bins=10,range=(0,1))\nratio_hist.set_title(\"Proportion of female graduates\")\ncounts = recent_grads['ShareWomen'].round(1).value_counts()\ncounts\n\n\n# Less than 10 majors have a 90% skew to favour one sex over the other. The number of male and female gradautes is an even split, with slighly more women graduating than men.\n\n# In[15]:\n\n\nrecent_grads['Unemployment_rate'].hist(bins=50,range=(0,0.2))\n\n\n# The unemplyment rate is below 20% for all majors. most majors have an unemplyment rate in the 5%-10% interval.\n\n# In[16]:\n\n\nrecent_grads['Men'].hist(bins=50,range=(0,50000))\n\n\n# In[ ]:\n\n\n\n\n\n# In[17]:\n\n\nrecent_grads['Women'].hist(bins=50,range=(0,50000))\n\n\n# Comparing the absoulte numbers of male and female graduatres we see that the total number of female graduates is slightly higher than tht total number of male graduates. There are five majors where the number of female graduates approaches 50,000.\n\n# ## Scatter matrix plots\n# Let's use scatter matrix plots to answer the foloowing questions:\n# \n# * Do students in more popular majors make more money?\n# * Do students that majored in subjects that were mojority female make more money?\n# * Is there any link between the number of full time employees and median salary?\n# * What percent of majors are predominantly male/female?\n# * What is the most common median salary range?\n\n# In[18]:\n\n\nfrom pandas.plotting import scatter_matrix\n\nscatter_matrix(recent_grads[['Sample_size','Median']],figsize=(10,10))\n\n\n# Those majors with less extreme median earnings have more data points in their sample. We would therefore expect these to be more reliable. Conversely, the highest reported median income has only a sinlge data point. More popular majors do not earn higher salaries.\n\n# In[19]:\n\n\nscatter_matrix(recent_grads[['Median','ShareWomen']],figsize=(10,10))\n\n\n# There is a negative correlation between the proportion of female graduates and median eranings.\n\n# In[21]:\n\n\nscatter_matrix(recent_grads[['Full_time', 'Median']],\n figsize=(10,10))\n\n\n# The most common mendian salary range is in the \\$30,000-\\$40,000 range\n\n# In[47]:\n\n\ncomp_range1 = recent_grads.head(10)\ncomp_plot = comp_range1.plot.bar(\n x='Major',y='ShareWomen',legend=False)\n\ncomp_range2 = recent_grads.tail(10)\ncomp_plot = comp_range2.plot.bar(\n x='Major',y='ShareWomen',legend=False)\n\n","sub_path":"graduate_jobs/college_grads.py","file_name":"college_grads.py","file_ext":"py","file_size_in_byte":8694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"444211518","text":"import inspect\nimport six\n\n__version__ = \"0.2.1\"\n\n\ndef has_kwargs(function):\n r'''Determine whether a function has \\*\\*kwargs.\n\n Parameters\n ----------\n function : callable\n The function to test\n\n Returns\n -------\n True if function accepts arbitrary keyword arguments.\n False otherwise.\n '''\n\n if six.PY2:\n return inspect.getargspec(function).keywords is not None\n else:\n sig = inspect.signature(function)\n\n for param in sig.parameters.values():\n if param.kind == param.VAR_KEYWORD:\n return True\n\n return False\n\n\ndef filter_kwargs(_function, *args, **kwargs):\n \"\"\"Given a function and args and keyword args to pass to it, call the function\n but using only the keyword arguments which it accepts. This is equivalent\n to redefining the function with an additional \\*\\*kwargs to accept slop\n keyword args.\n\n If the target function already accepts \\*\\*kwargs parameters, no filtering\n is performed.\n\n Parameters\n ----------\n _function : callable\n Function to call. Can take in any number of args or kwargs\n\n \"\"\"\n\n if has_kwargs(_function):\n return _function(*args, **kwargs)\n\n # Get the list of function arguments\n func_code = six.get_function_code(_function)\n function_args = func_code.co_varnames[:func_code.co_argcount]\n # Construct a dict of those kwargs which appear in the function\n filtered_kwargs = {}\n for kwarg, value in list(kwargs.items()):\n if kwarg in function_args:\n filtered_kwargs[kwarg] = value\n # Call the function with the supplied args and the filtered kwarg dict\n return _function(*args, **filtered_kwargs)\n","sub_path":"museval/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"132079194","text":"import copy\n\nfrom biosensor.common.node import condition\nfrom biosensor.model_1D.settings import Settings1D\nfrom biosensor.common.math import divide\n\n\nclass DimensionlessSettings1D(Settings1D):\n \"\"\"\n Dimensionless settings for 1D biosensor model.\n\n Params:\n @settings (Settings1D): dimensional settings to import.\n \"\"\"\n def __init__(self, settings):\n self._import_settings(settings)\n\n @property\n def regions(self):\n return self._regions\n\n @regions.setter\n def regions(self, value):\n \"\"\"\n 1D regions property. It must be overriden to avoid regions\n double-checking.\n \"\"\"\n if isinstance(value, list):\n self._regions = value\n else:\n raise TypeError('List of regions expected, but {} found'\n .format(str(type(value))))\n\n @property\n def bounds(self):\n return self._bounds\n\n @bounds.setter\n def bounds(self, value):\n \"\"\"\n 1D bounds property. It must be overriden to avoid bounds\n double-checking.\n \"\"\"\n if isinstance(value, dict):\n self._bounds = value\n else:\n raise TypeError('Dict of bounds expected, but {} found'\n .format(str(type(value))))\n\n def _import_settings(self, settings):\n \"\"\"\n Take all needed settings and normalize them.\n \"\"\"\n\n self._check_type_of_settings(settings)\n\n self.regions = copy.deepcopy(settings.regions)\n self.bounds = copy.deepcopy(settings.bounds)\n self.substances = copy.deepcopy(settings.substances)\n\n self._import_normalizers(settings)\n self._import_global_settings(settings)\n\n self._make_sigmasq()\n\n self._normalize_regions()\n self._normalize_bounds()\n\n def _check_type_of_settings(self, settings):\n if not isinstance(settings, Settings1D):\n raise('Object of Settings1D expected, \"{}\" received'\n .format(settings))\n\n def _import_normalizers(self, settings):\n self.DS1 = settings.regions[0]['substances']['substrate']\\\n ['condition_args']['D']\n self.d = settings.regions[0]['d']\n self.Km = settings.Km\n\n def _import_global_settings(self, settings):\n self.tau = divide(\n settings.tau * self.DS1,\n self.d**2)\n self.ne = settings.ne\n self.F = settings.F\n self.Vmax = settings.Vmax\n self.e = settings.e\n\n def _make_sigmasq(self):\n self.sigmasq = divide(\n self.Vmax * (self.d**2),\n (self.Km * self.DS1))\n\n def _normalize_regions(self):\n \"\"\"\n Normalize regions to make them dimensionless.\n \"\"\"\n for region in self.regions:\n region['d'] = divide(region['d'], self.d)\n\n for substance, params in region['substances'].items():\n if 'condition_args' in params:\n for key in params['condition_args'].keys():\n if key == 'D':\n params['condition_args']['D'] = divide(\n params['condition_args']['D'],\n self.DS1)\n if key == 'D2':\n params['condition_args']['D2'] = divide(\n params['condition_args']['D2'],\n self.DS1)\n if key == 'U0':\n params['condition_args']['U0'] = divide(\n params['condition_args']['U0'],\n self.Km)\n if params['condition'] == condition.Constant:\n params['condition_args']['value'] = divide(\n params['condition_args']['value'],\n self.Km)\n\n def _normalize_bounds(self):\n \"\"\"\n Normalize bounds to make them dimensionless.\n \"\"\"\n for substance_name, substance_bounds in self.bounds.items():\n for axis, substance_settings_per_axis in substance_bounds.items():\n for bound_position, bound_settings in \\\n substance_settings_per_axis.items():\n if 'condition_args' in bound_settings and \\\n 'value' in bound_settings['condition_args']:\n bound_settings['condition_args']['value'] = divide(\n bound_settings['condition_args']['value'],\n self.Km)\n","sub_path":"biosensor/model_1D/settings/dimensionless.py","file_name":"dimensionless.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75764250","text":"# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\nimport os\nfrom pathlib import Path\nfrom typing import Iterable, Mapping, Optional\n\nfrom pants.backend.python.target_types import parse_requirements_file\nfrom pants.base.build_environment import get_buildroot\n\n\nclass PythonRequirements:\n \"\"\"Translates a pip requirements file into an equivalent set of `python_requirement_library`\n targets.\n\n If the `requirements.txt` file has lines `foo>=3.14` and `bar>=2.7`,\n then this will translate to:\n\n python_requirement_library(\n name=\"foo\",\n requirements=[\"foo>=3.14\"],\n )\n\n python_requirement_library(\n name=\"bar\",\n requirements=[\"bar>=2.7\"],\n )\n\n See the requirements file spec here:\n https://pip.pypa.io/en/latest/reference/pip_install.html#requirements-file-format\n\n You may also use the parameter `module_mapping` to teach Pants what modules each of your\n requirements provide. For any requirement unspecified, Pants will default to the name of the\n requirement. This setting is important for Pants to know how to convert your import\n statements back into your dependencies. For example:\n\n python_requirements(\n module_mapping={\n \"ansicolors\": [\"colors\"],\n \"setuptools\": [\"pkg_resources\"],\n }\n )\n \"\"\"\n\n def __init__(self, parse_context):\n self._parse_context = parse_context\n\n def __call__(\n self,\n requirements_relpath: str = \"requirements.txt\",\n *,\n module_mapping: Optional[Mapping[str, Iterable[str]]] = None,\n ) -> None:\n \"\"\"\n :param requirements_relpath: The relpath from this BUILD file to the requirements file.\n Defaults to a `requirements.txt` file sibling to the BUILD file.\n :param module_mapping: a mapping of requirement names to a list of the modules they provide.\n For example, `{\"ansicolors\": [\"colors\"]}`. Any unspecified requirements will use the\n requirement name as the default module, e.g. \"Django\" will default to\n `modules=[\"django\"]`.\n \"\"\"\n req_file_tgt = self._parse_context.create_object(\n \"_python_requirements_file\",\n name=requirements_relpath.replace(os.path.sep, \"_\"),\n sources=[requirements_relpath],\n )\n requirements_dep = f\":{req_file_tgt.name}\"\n\n req_file = Path(get_buildroot(), self._parse_context.rel_path, requirements_relpath)\n requirements = parse_requirements_file(\n req_file.read_text(), rel_path=str(req_file.relative_to(get_buildroot()))\n )\n for parsed_req in requirements:\n req_module_mapping = (\n {parsed_req.project_name: module_mapping[parsed_req.project_name]}\n if module_mapping and parsed_req.project_name in module_mapping\n else None\n )\n self._parse_context.create_object(\n \"python_requirement_library\",\n name=parsed_req.project_name,\n requirements=[parsed_req],\n module_mapping=req_module_mapping,\n dependencies=[requirements_dep],\n )\n","sub_path":"src/python/pants/backend/python/macros/python_requirements.py","file_name":"python_requirements.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287995487","text":"import requests\nimport json\n\nurl = \"http://rest-proxy:8082/topics/hello-python-topic\"\n\nheaders = {\n \"Content-Type\": \"application/vnd.kafka.json.v2+json\"\n}\n\nfor i in range(1,6):\n payload = {\n \"records\": [\n {\n \"key\": \"python-key-\" + str(i),\n \"value\": \"python-value-\" + str(i)\n }\n ]\n }\n\n r = requests.post(url, data=json.dumps(payload), headers=headers)\n\n if r.status_code != 200:\n print(\"Status Code: \" + str(r.status_code))\n print(r.text)","sub_path":"solution/basic-producer-python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61530120","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n# \n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom torch import nn\n\nfrom src.modules.ll_model import LifelongLearningModel\nfrom src.modules.multitask_leg_llmodel import MTLegModel\nfrom src.modules.utils import MultiHead, make_model\n\n\nclass FineTuneLegLLModel(LifelongLearningModel):\n def __init__(self, *args, **kwargs):\n super(FineTuneLegLLModel, self).__init__(*args, **kwargs)\n self.source_ll_model = None\n self.finished_tasks = 0\n self.all_dims = None\n if len(self.hidden_size) == 0:\n raise NotImplementedError(\"NewLeg and NewHead are equivalent \"\n \"when no hidden layers are used, \"\n \"please use NewHead instead.\")\n\n def get_model(self, task_id, **task_infos):\n task_model = super().get_model(task_id, **task_infos)\n\n if task_id >= self.finished_tasks and task_id > 0:\n source_model = self.source_ll_model.get_model(task_id - 1)\n task_model.load_source(source_model)\n\n return task_model\n\n def _new_model(self, x_dim, n_classes, task_id, **kwargs):\n if self.all_dims is None:\n if len(x_dim) == 1:\n self.n_convs = 0\n else:\n k = 3\n stride = 2\n second_layer_map_size = [(s - (k - 1) + 1) // stride for s in\n x_dim[1:]]\n self.hidden_size[0] = (self.hidden_size[0], *second_layer_map_size)\n self.n_convs = 1\n self.all_dims = [x_dim, *self.hidden_size]\n if self.source_ll_model is None:\n raise ValueError('Source model should be set before creating the '\n 'first model for FineTuneLegLLModel !')\n\n head = MultiHead(self.all_dims[-1], n_classes)\n common_trunc = self.base_model_func(self.all_dims[1:], n_convs=self.n_convs)\n new_trunc = make_model(common_trunc, head)\n\n new_leg = self.base_model_func(self.all_dims[:2])\n new_model = make_model(new_leg, new_trunc, seq=FineTuneLegMultiTask)\n\n return new_model\n\n def set_source_model(self, source):\n assert self.source_ll_model is None, 'Source already set for FineTune.'\n self.source_ll_model = source\n\n def finish_task(self, dataset):\n self.finished_tasks += 1\n\n\nclass FineTuneLegMultiTask(nn.Module):\n def __init__(self, leg, trunc=None):\n super(FineTuneLegMultiTask, self).__init__()\n self.trunc = trunc\n self.leg = leg\n\n def forward(self, input):\n return self.trunc(self.leg(input))\n\n def load_source(self, source):\n assert type(source) == MTLegModel\n self.leg.load_state_dict(source.legs[-1].state_dict())\n self.trunc.load_state_dict(source.trunc.state_dict())\n","sub_path":"Lileb-Training/src/modules/fine_tune_leg_llmodel.py","file_name":"fine_tune_leg_llmodel.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493263975","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport pandas as pd\nfrom functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef _get_region_list():\n \n apigeo_link = 'https://geo.api.gouv.fr/'\n \n results = requests.get(apigeo_link + 'regions')\n \n data = results.json()\n \n reg = pd.DataFrame(data)\n \n reg.columns = 'region_' + reg.columns\n \n return(reg)\n ","sub_path":"geoapyfr/admin/_get_region_list.py","file_name":"_get_region_list.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"240530829","text":"# Zora Che with adaptations from Gavin Brown\n# CS330, Fall 2021\n\nimport sys\nimport time\nimport numpy as np \n\n\n\ndef read_prefs(pref_1_filename, pref_2_filename):\n # This function reads preferences from two files\n # and returns two-dimensional preference lists and the length of a list.\n with open(pref_1_filename, 'r') as f:\n hospital_raw = f.read().splitlines()\n with open(pref_2_filename, 'r') as f:\n student_raw = f.read().splitlines()\n N = int(student_raw[0])\n hospital_prefs = [[int(id) for id in x.split(',')] for x in hospital_raw[1:]]\n student_prefs = [[int(id) for id in x.split(',')] for x in student_raw[1:]]\n return N, hospital_prefs, student_prefs\n\n\n\n# Converts the entire matrix of preference list into an inverse_preference_list (as stated in lecture)\n# Has nested for loops to iterate over every single element of the 2D matrix of preferences\n# Runs in O(n^2) because of the nested for loop\n\ndef inverse_prefs(N, prefs): \n \n n = 0\n h = 0 \n ranks = N*[None]# You'll need to replace this.\n inversed_ranks = np.zeros((N, N), dtype=int)\n for one_student_preference in prefs: \n for hospital in one_student_preference: \n ranks[hospital] = h\n h = h + 1\n h = 0 \n inversed_ranks[n] = ranks\n n = n + 1 \n return inversed_ranks\n \n \n \n \ndef run_GS(N, hospital_prefs, student_prefs, out_name):\n free_hospital = list(range(N))\n count = N*[0] # stores a pointer to each hospital's next unproposed student, going from the left of hospital's preference list \n current = N*[None] # stores current assignment; index -> student, value -> hospital\n\n # algorithm - Hospital giving offer to student\n \n # Calling rank before the while loop. helper function written above. \n rank = inverse_prefs(N, student_prefs) \n\n \n while free_hospital: # returns True if list is nonempty\n #print('--------')\n #print('current:', current)\n #print('free hospital', free_hospital)\n hospital = free_hospital.pop(0)\n student = hospital_prefs[hospital][count[hospital]]\n #print(hospital, 'proposing to', student)\n count[hospital] += 1\n if current[student] is None: # student is not paired \n current[student] = hospital\n #print('student is not paired')\n else:\n \n if rank[student][current[student]] < rank[student][hospital]: \n \n \n \n free_hospital.append(hospital)\n else:\n # student switches to new hospital, old hospital becomes free\n # print('student prefers', hospital)\n free_hospital.append(current[student])\n current[student] = hospital\n # write out matches\n with open(out_name, 'w') as f:\n for student, hospital in enumerate(current):\n f.write(str(hospital)+','+str(student)+'\\n')\n\n############################################################\n# PART 2 \n############################################################\n\ndef check_stable(N, hospital_prefs, student_prefs, match_file):\n # Implement checking of stable matches from output\n # ...\n \n # Helper function used to obtain inverse_list of hospital and student preferences: as given in lecture \n actual_hospital_rank = inverse_prefs(N, hospital_prefs)\n actual_student_rank = inverse_prefs(N, hospital_prefs)\n \n #Creating a list with N elements\n paired_list = [0] * N \n\n #Final value to print\n final_print_val = 1\n\n #reading from the given file and extracting a list where indices are students and the corresponding value is the hospital that #they are matched to \n with open(match_file, 'r') as file: \n for val in list(file):\n #removing the brackets and commas to extract a list in the manner proposed before\n\n match = val.strip(\"()\").split(',') \n h_val = int(match[0])\n stu_val = int(match[1])\n\n #Line of code where the actual execution of the previously explained intention\n paired_list[stu_val] = h_val\n \n \n \n for student_match in range(N): \n # Getting the hospital match of the student in range(N) from the list we created earlier\n hospital_match = paired_list[student_match]\n \n #Making sure that the student's first preference was not the hospital he was assigned to \n if (actual_hospital_rank[hospital_match][student_match]>0): \n # Iterating over every hospital that the students prefers more than his/her current assignemt\n for j in range(0, actual_hospital_rank[hospital_match][student_match]):\n \n # Checking whether the hospital which the student prefers to the current assigned hospital prefers this \n # particular student more than their currently assigned student. If this will be true, then the matching is \n # not stable. If this will be false then we continue the loop. If the loop terminates then we print 1. \n \n if actual_student_rank[hospital_prefs[hospital_match][j]][hospital_match] bool:\n \"\"\"\n Checks if geckodriver executable is in the $PATH.\n\n @rtype: bool\n \"\"\"\n paths = [path + \"/geckodriver\" for path in os.environ[\"PATH\"].split(\":\")]\n\n return any([os.path.isfile(file) for file in paths])\n\n\ndef set_geckodriver() -> None:\n \"\"\"\n Adds geckodriver executable to ~/.local/bin folder.\n \"\"\"\n\n tarfile_path = str(Path(__file__).parent.parent / \"data/geckodriver-v0.28.0-linux64.tar.gz\")\n tar = tarfile.open(tarfile_path, \"r:gz\")\n tar.extractall(str(Path.home() / \".local/bin\"))\n tar.close()\n\n\ndef parse_date(date_str: str, date_formats: [str]) -> datetime:\n \"\"\"\n Parses date_str using different date_formats and returns the first valid datetime which the\n datetime.strptime function could parse.\n\n @param date_str: String encoded date\n @param date_formats: List of datetime formats\n @return: Parsed datetime\n \"\"\"\n # This ugly code just tries every date_format until it can\n # parse a legit one from the string.\n for fmt in date_formats:\n try:\n date = datetime.datetime.strptime(date_str, fmt)\n\n # Set to the current date if the user just specifies day.month format\n date = date.replace(year=datetime.datetime.now().year) # Just in case\n return date\n except ValueError:\n continue\n raise ValueError('Specify valid date string. ' + date_str + \" isn't a valid string format.\")\n\n\ndef filter_schedule(all_events: [icalevents.icalparser.Event], config_path: str) -> [icalevents.icalparser.Event]:\n \"\"\"\n Given a list of events the function filters out the subjects with the groups not matching the\n accepted groups specified by the user saved in the configuration file.\n\n Subjects not specified in the configuration file are not filtered out.\n\n @param all_events: List of events\n @param config_path: Path to the configuration file\n @return: List of filtered events\n \"\"\"\n # Load user settings\n with open(config_path, \"r\") as f:\n data = yaml.load(f, Loader=yaml.FullLoader)\n user_groups = data['user'].get('groups', None)\n\n if user_groups is None:\n return all_events\n\n lecture_events = [event for event in all_events if 'PR' in event.description.split(',')[1]]\n general_groups = [get_groups(event) for event in lecture_events]\n general_groups = set(itertools.chain.from_iterable(general_groups)) # Flatten 2D to 1D list and get unique groups\n\n filtered_events = []\n for event in all_events:\n\n # Every description of a course is made out of these items\n # [name, type, organizers, groups]\n subject = [desc.strip() for desc in event.description.split(',')][0]\n groups = get_groups(event)\n\n # Finds all user specified groups of subject, if any specified\n # The partial_ratio is used so if the user makes a grammar mistake or just\n # specified part of the group\n matches = [user_subject['group'] for user_subject in user_groups if\n fuzz.partial_ratio(user_subject['name'].lower(),\n subject.lower()) >= 90] # Useful for grammar mistakes\n matches = list(itertools.chain.from_iterable(matches)) # 2D to 1D list. Just in case.\n\n # This could probably be done better, I just don't know how yet, so here's the explanation:\n # The idea behind the matches is to first filter out general groups from the events groups.\n # The reason for this is that if this wasn't implemented, some events like SV (seminarske vaje)\n # can have no specific group, but still get caught by the matches.\n if len(matches):\n # removes general groups event groups - easier to look if it has any group\n for i in range(len(groups)):\n for group in general_groups:\n groups[i] = groups[i].replace(group, '').strip()\n\n if len(\"\".join(groups)):\n if any([fuzz.partial_ratio(group, user_group) >= 90 for group in groups for user_group in matches]):\n filtered_events.append(event)\n else:\n filtered_events.append(event)\n else:\n filtered_events.append(event)\n\n return filtered_events\n\n\ndef extract_schedule(file: Path, start: datetime.datetime, end: datetime.datetime, use_filter=False) -> \\\n [icalevents.icalparser.Event]:\n \"\"\"\n Extract events from .ics file and return the events in a list\n\n Function extracts events by a datetime interval specified with the start and end parameters.\n\n By setting the use_filter parameter, the function filters the events by looking at the assigned groups saved in\n the programs configuration file. The filter will only affect the events in which there is a group.\n\n @param file: Path to .ics file\n @param start: start date\n @param end: end date\n @param use_filter: Use group filtering specified in configuration file\n @return: List of extracted events of type icalevents.icalparser.Event\n \"\"\"\n\n events_list = events(file=str(file), start=start, end=end)\n\n if use_filter:\n config_file = Path(__file__).parent.parent / \"config.yaml\"\n events_list = filter_schedule(events_list, config_file)\n\n return events_list\n\n\ndef get_organizer(event: icalevents.icalparser.Event) -> [str]:\n \"\"\"\n Return organizers of the event stored in the events description.\n\n The function does this by using regex to match valid Person names in the description string and store\n the matches into a list.\n\n @param event: Event instance of icalevents.icalparser.Event\n @return: List of event organizers\n \"\"\"\n # Using regex to get organizer names\n person_name = re.compile(r\"[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*\")\n\n description = [desc.strip() for desc in event.description.split(',')]\n # Unidecode turns all unicode characters to ASCII for regex pattern\n normalized_desc = [unidecode(desc) for desc in description]\n\n # 2:-1 because we know the index 2 starts with the organizer names\n # and the index -1 is the description ending with at least one group\n normalized_organizers = list(filter(person_name.fullmatch, normalized_desc[2:-1]))\n\n organizers = []\n for organizer in normalized_organizers:\n index = normalized_desc.index(organizer)\n organizers.append(description[index])\n\n return organizers\n\n\ndef get_groups(event: icalevents.icalparser.Event) -> [str]:\n \"\"\"\n Return groups of the event stored in the events description.\n\n @param event: Event instance of icalevents.icalparser.Event\n @return: List of event groups\n \"\"\"\n organizers = get_organizer(event)\n\n description = [desc.strip() for desc in event.description.split(',')]\n last_organizer_index = description.index(organizers[-1])\n\n return description[last_organizer_index + 1:]\n\n\ndef create_cell_line(data: str, length: int) -> str:\n \"\"\"\n Function creates a string centered with content and padded on each side with ' ' (spaces), starting and\n\n To specify the start and end of the cell the string has a prefix/suffix filled with character '#'.\n\n @param data: Content of the line\n @param length: Width of the cell\n @return: String with transformed content\n \"\"\"\n string = \"#\"\n\n if data in [\"#\", \" \", \"&\", \"-\", \"=\", \"$\"]:\n for i in range(0, length):\n string += data\n\n string = string[:-1]\n else:\n end = length - len(data) - 1\n for i in range(0, end):\n if i % 2 == 0:\n data = \"{} \".format(data)\n else:\n data = \" {}\".format(data)\n\n string = \"#%s\" % data\n\n return string\n\n\ndef create_cell(event: icalevents.icalparser.Event) -> [str]:\n \"\"\"\n Turn an event into a table cell by extracting the events duration, subject, location, organizers and\n subject groups (if any).\n\n The function before constructing the cell calculates the longest string/line which determines the width\n of the entire cell.\n\n A picture of the functions returned cell.\n\n #####################\n # #\n # start - end #\n # subject (type) #\n # location #\n # organizers #\n # groups #\n # #\n #####################\n\n @param event: Event instance of icalevents.icalparser.Event\n @return: List containing every line of the table cell\n \"\"\"\n duration = event.start.strftime(\"%H:%M\") + \" - \" + event.end.strftime(\"%H:%M\")\n subject = event.summary + \" ({})\".format(event.description.split(',')[1].strip()) # saves \"subject (type)\"\n location = event.location\n organizers = \", \".join(get_organizer(event))\n groups = \", \".join(get_groups(event))\n\n table = [\"#\", \" \", duration, subject, location, organizers, groups, \" \", \"#\"]\n largest_len = max([len(string) for string in table]) + 10\n\n for i in range(len(table)):\n table[i] = create_cell_line(table[i], largest_len)\n\n return table\n\n\ndef display_schedule(schedule: [icalevents.icalparser.Event]) -> str:\n \"\"\"\n Create a table from all the events in list.\n\n The table generated from the events looks like the picture below, where events for each day are stored\n in their own table. The cells for each event are concatenated to the end of the table, sorted by their\n start time.\n\n date: day\n #####################\n # #\n # start - end #\n # subject (type) #\n # location #\n # organizers #\n # groups #\n # #\n #####################\n\n The function returns a singe string containing all the tables separated by '\\n'.\n\n @param schedule: List of events\n @return: Schedule in a string\n \"\"\"\n days = sorted(set([event.start.date() for event in schedule]))\n schedule_by_day = [[event for event in schedule if event.start.date() == day] for day in days]\n\n display_by_day = []\n\n for events_by_day in schedule_by_day:\n\n day = [\"PON\", \"TOR\", \"SRE\", \"ČET\", \"PET\"][events_by_day[0].start.weekday()]\n date = events_by_day[0].start.strftime(\"%d.%m.%Y\")\n\n table = [\"\"] * 9 # The height of the table\n for event in events_by_day:\n cell = create_cell(event)\n for i in range(len(table)):\n table[i] += cell[i]\n\n # Close table\n for i in range(len(table)):\n table[i] += \"#\"\n\n # Adds date and day name to the top of table\n table.insert(0, \"{}: {}\".format(date, day))\n\n display_by_day.append(\"\\n\".join(table))\n\n return \"\\n\\n\".join(display_by_day)\n","sub_path":"urnik/lib/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":10986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"553283509","text":"from data.data import Data\nimport pandas as pd\n# add to data iterator\n# also add done\nfrom ienv import IEnv\n\nclass TradingData(Data, IEnv):\n epoch: int = 0\n done: bool = False\n current_cost: float\n current_costs: float\n current_date: any\n\n def __init__(self):\n super(TradingData, self).__init__()\n\n def Step(self):\n if self.epoch > len(self.x):\n self.done = True\n else:\n self.current_cost = self.GetY()[self.epoch]\n self.current_costs = self.x.to_numpy()[self.epoch]\n self.current_date = self.x.date[self.epoch]\n\n super(TradingData, self).Step()\n\n\n\ndef main():\n d = TradingData()\n d.x = pd.DataFrame({'date': [0, 1, 2, 3], 'x': [3, 2, 2, 0], 'y': [3, 2, 2, 0]})\n d.target = 'y'\n d.y = [1, 2, 3, 4, ]\n d.Step()\n print(d.current_costs, d.current_cost)\n d.Step()\n print(d.current_costs, d.current_cost)\n\nif __name__ == '__main__':\n main()","sub_path":"data/trading_data.py","file_name":"trading_data.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193970836","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\nimport gevent\nfrom gevent.queue import Queue, Empty\n\ntasks = Queue(maxsize=3)\n\ndef worker(n):\n try:\n while True:\n task = tasks.get(timeout=1) # decrements queue size by 1\n print('Worker %s got task %s' % (n, task))\n gevent.sleep(0)\n except Empty:\n print('Quitting time!')\n\ndef boss():\n \"\"\"\n Boss will wait to hand out work until a individual worker is\n free since the maxsize of the task queue is 3.\n \"\"\"\n\n for i in xrange(1,10):\n tasks.put(i)\n print('Assigned all work in iteration 1')\n\n for i in xrange(10,20):\n tasks.put(i)\n print('Assigned all work in iteration 2')\n\ngevent.joinall([\n gevent.spawn(boss),\n gevent.spawn(worker, 'steve'),\n gevent.spawn(worker, 'john'),\n gevent.spawn(worker, 'bob'),\n ])\n\n\n# output:\n# \n# Worker steve got task 1 \n# Worker john got task 2 \n# Worker bob got task 3 \n# Worker steve got task 4 \n# Worker john got task 5 \n# Worker bob got task 6 \n# Assigned all work in iteration 1 ***** Now, queue tasks [7, 8, 9]\n# Worker steve got task 7 \n# Worker john got task 8 \n# Worker bob got task 9 \n# Worker steve got task 10 \n# Worker john got task 11 \n# Worker bob got task 12 \n# Worker steve got task 13 \n# Worker john got task 14 \n# Worker bob got task 15 \n# Worker steve got task 16 \n# Worker john got task 17 \n# Worker bob got task 18 \n# Assigned all work in iteration 2 ****** Now, queue tasks [19]\n# Worker steve got task 19 \n# Quitting time! \n# Quitting time! \n# Quitting time!\n \n","sub_path":"gaozhichao/exercises/gevent/Data_Structures/Queue/gevent_queue02.py","file_name":"gevent_queue02.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"455019855","text":"def linear_search(arr, target):\n # Your code here\n for i in arr:\n if i == target:\n return arr.index(i)\n return -1 # not found\n# array = [2,3,4,1,8,9,0]\n# print(linear_search(array,9))\n\n# Write an iterative implementation of Binary Search\n\n\ndef binary_search(arr, target):\n # Your code here\n lower_index = 0 # set the lower index\n highest_index = len(arr)-1 # set the higher index \n print(len(arr)) # 8\n print(highest_index) # 7\n while lower_index <= highest_index: # until there is only one item in the list do:\n # used // that divides with integral result (discard remainder)\n middle_index = (lower_index + highest_index) // 2 \n # check if the element of the arr with the middle_index is equal to the target\n if arr[middle_index] == target:\n # if it is return the index\n return middle_index\n # because we use a binary tree the values are sorted \n # else check if if the value of the element at arr[middle index] is biger than the target\n elif arr[middle_index] > target:\n # set the highest_index to be equal to the middle_index - 1 to go left\n highest_index = middle_index - 1\n else:\n # set the lower_index to be equal to the middle_index + 1 to go right\n lower_index = middle_index + 1\n return -1 # not found \n\narray = [2, 3, 4, 1, 8, 9, 0, 7]\nprint(binary_search(array, 9))\n","sub_path":"src/searching/searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"342786340","text":"# Copyright 2015 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"This example file is meant to provide coverage to bisect_results.\"\"\"\n\nDEPS = [\n 'auto_bisect',\n 'recipe_engine/json',\n 'recipe_engine/path',\n 'recipe_engine/properties',\n 'recipe_engine/raw_io',\n]\n\nBASIC_CONFIG = {\n 'test_type': 'perf',\n 'command':\n ('src/tools/perf/run_benchmark -v --browser=release smoothness.'\n 'tough_scrolling_cases'),\n 'good_revision': '314015',\n 'bad_revision': '314017',\n 'metric': 'mean_input_event_latency/mean_input_event_latency',\n 'repeat_count': '2',\n 'max_time_minutes': '5',\n 'gs_bucket': 'chrome-perf',\n 'builder_host': 'master4.golo.chromium.org',\n 'builder_port': '8341',\n 'dummy_builds': 'True',\n 'dummy_job_names': 'True',\n 'bypass_stats_check': 'True',\n 'skip_gclient_ops': 'True',\n}\n\nBASIC_ATTRIBUTES = {\n 'bisect_over': True,\n 'results_confidence': 0.99,\n 'warnings': ['This is a demo warning'],\n 'culprit_present': True,\n}\n\nNON_TELEMETRY_TEST_CONFIG = dict(BASIC_CONFIG)\nNON_TELEMETRY_TEST_CONFIG['command'] = 'src/tools/dummy_command'\n\nDEPS_CULPRIT_ATTRIBUTES = dict(BASIC_ATTRIBUTES)\nDEPS_CULPRIT_ATTRIBUTES['culprit.depot'] = {'src': 'fake_location'}\n\nFAILED_ATTRIBUTES = dict(BASIC_ATTRIBUTES)\nFAILED_ATTRIBUTES['failed'] = True\nFAILED_ATTRIBUTES['culprit_present'] = False\n\nFAILED_DIRECTION_ATTRIBUTES = dict(BASIC_ATTRIBUTES)\nFAILED_DIRECTION_ATTRIBUTES['failed_direction'] = True\nFAILED_DIRECTION_ATTRIBUTES['culprit_present'] = False\n\nABORTED_BISECT_ATTRIBUTES = dict(BASIC_ATTRIBUTES)\nABORTED_BISECT_ATTRIBUTES['failed_initial_confidence'] = True\nABORTED_BISECT_ATTRIBUTES['culprit_present'] = False\n\n\ndef RunSteps(api):\n api.path['checkout'] = api.path.mkdtemp('bogus')\n bisector = api.auto_bisect.create_bisector(api.properties['bisect_config'],\n dummy_mode=True)\n # Load the simulated results of a bisect\n dummy_bisector_attributes = dict(api.properties['dummy_bisector_attributes'])\n\n # Simulate the side-effects of a bisect by setting the bisector attributes\n # directly.\n if dummy_bisector_attributes.pop('culprit_present'):\n bisector.culprit = bisector.bad_rev\n set_attributes(bisector, dummy_bisector_attributes)\n\n bisector.post_result()\n\n\ndef set_attributes(target, attributes):\n \"\"\"Sets values to the attributes of an object based on a dict.\n\n This goes one extra level deep so as to set an attribute's attribute:\n e.g.: set_attributes(some_object, {'some_attribute': 1,\n 'other_attribute.nested_val': False})\n \"\"\"\n for k, v in attributes.iteritems():\n if '.' in k:\n sub_target = getattr(target, k.split('.')[0])\n setattr(sub_target, k.split('.')[1], v)\n else:\n setattr(target, k, v)\n\n\ndef add_revision_mapping(api, test, pos, sha):\n step_name = ('Resolving reference range.crrev get commit hash for ' +\n 'refs/heads/master@{#%s}' % pos)\n stdout = api.json.output({'git_sha': sha})\n test += api.step_data(step_name, stdout=stdout)\n\n step_name = 'Resolving reference range.resolving hash ' + sha\n pos = 'refs/heads/master@{#%s}' % pos\n stdout = api.raw_io.output(pos)\n return test\n\n\ndef add_revision_info(api, test):\n step_name = 'Reading culprit cl information.'\n rev_info = {\n 'author': 'DummyAuthor',\n 'email': 'dummy@nowhere.com',\n 'subject': 'Some random CL',\n 'date': '01/01/2015',\n 'body': ('A long description for a CL.\\n'\n 'Containing multiple lines'),\n }\n return test + api.step_data(step_name, stdout=api.json.output(rev_info))\n\n\ndef get_post_bisect_step_data(api, test):\n \"\"\"Gets step data for perf_dashboard/resource/post_json.py.\"\"\"\n response = {'status_code': 200}\n return test + api.step_data('Post bisect results',\n stdout=api.json.output(response))\n\n\ndef GenTests(api):\n basic_test = api.test('basic_test')\n basic_test = get_post_bisect_step_data(api, basic_test)\n basic_test = add_revision_mapping(api, basic_test, '314015', 'c001c0de')\n basic_test = add_revision_mapping(api, basic_test, '314017', 'deadbeef')\n basic_test = add_revision_info(api, basic_test)\n basic_test += api.properties(\n bisect_config = BASIC_CONFIG,\n dummy_bisector_attributes = BASIC_ATTRIBUTES)\n yield basic_test\n\n deps_culprit_test = api.test('deps_culprit_test')\n deps_culprit_test = get_post_bisect_step_data(api, deps_culprit_test)\n deps_culprit_test = add_revision_mapping(\n api, deps_culprit_test, '314015', 'c001c0de')\n deps_culprit_test = add_revision_mapping(\n api, deps_culprit_test, '314017', 'deadbeef')\n deps_culprit_test = add_revision_info(api, deps_culprit_test)\n deps_culprit_test += api.properties(\n bisect_config = BASIC_CONFIG,\n dummy_bisector_attributes = DEPS_CULPRIT_ATTRIBUTES)\n yield deps_culprit_test\n\n failed_test = api.test('failed_test')\n failed_test = get_post_bisect_step_data(api, failed_test)\n failed_test = add_revision_mapping(api, failed_test, '314015', 'c001c0de')\n failed_test = add_revision_mapping(api, failed_test, '314017', 'deadbeef')\n failed_test += api.properties(\n bisect_config = BASIC_CONFIG,\n dummy_bisector_attributes = FAILED_ATTRIBUTES)\n yield failed_test\n\n failed_direction_test = api.test('failed_direction_test')\n failed_direction_test = get_post_bisect_step_data(api,\n failed_direction_test)\n failed_direction_test = add_revision_mapping(api, failed_direction_test,\n '314015', 'c001c0de')\n failed_direction_test = add_revision_mapping(api, failed_direction_test,\n '314017', 'deadbeef')\n failed_direction_test += api.properties(\n bisect_config = BASIC_CONFIG,\n dummy_bisector_attributes = FAILED_DIRECTION_ATTRIBUTES)\n yield failed_direction_test\n\n aborted_bisect_test = api.test('aborted_non_telemetry_test')\n aborted_bisect_test = get_post_bisect_step_data(api, aborted_bisect_test)\n aborted_bisect_test = add_revision_mapping(api, aborted_bisect_test, '314015',\n 'c001c0de')\n aborted_bisect_test = add_revision_mapping(api, aborted_bisect_test, '314017',\n 'deadbeef')\n aborted_bisect_test += api.properties(\n bisect_config = NON_TELEMETRY_TEST_CONFIG,\n dummy_bisector_attributes = ABORTED_BISECT_ATTRIBUTES)\n yield aborted_bisect_test\n","sub_path":"scripts/slave/recipes/bisect_test/example_bisect_results.py","file_name":"example_bisect_results.py","file_ext":"py","file_size_in_byte":6634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"295292942","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nMINERS = ['F2Pool', \n 'BTC Guild', \n 'CloudHashing', \n 'EclipseMC', \n 'KnCMiner', \n 'Polmine', \n 'BitMinter', \n 'Slush', \n 'ASICMiner', \n '50BTC', \n 'AntPool',\n 'OzCoin', \n 'Eligius', \n 'GHash.IO', \n 'MegaBigPower', \n 'BTCC', \n 'TripleMining', \n 'BW.COM', \n 'TangPool', \n 'ckpool', \n 'Unknown', \n 'BitFury', \n 'HuoBi', \n 'BitcoinAffiliate', \n '8BAOCHI', \n '21 Inc.', \n 'Telco 214']\n\n\n\nWALLETS = [{'tag':'796', 'addrs':['1Mg4i5e3YkM7WKFXmimzjgGjjiozQgGKwv',]},\n {'tag':'YUNBI', 'addrs':['18tyHn56GCmgp1H3wYyvkcCcTvrbRZGCMF', '1Q3vVgawXfaMhQt33h5yR8Pa7CGxQvZpEd', '1BsPALmKmZKZ1on6yrQSF1bc1QgPNRVorg', '1fzKAaPiZKEekhA4JzRMR3KH8CCd1xPZj']},\n {'tag':'JUA', 'addrs':['1CyAr95iiyPMDEfe48NZGQti3BSSwBsUsw', '1Zz1iN9QaxaiBM735nQLRGxtV46cWqWxT', '13k5KUK2vswXRdjgjxgCorGoY2EFGMFTnu']},\n ]\nMARKETS = ['Bitstamp', 'BTC-e', 'OKCoin', 'Huobi', 'BTCC']\n\n#stat\nKNOWN_STATS = ['blockchain', 'tx', 'block', 'address']\n\n#charts\nKNOWN_CHARTS = ['block', 'chain', 'node', 'address']\nCHAIN_CHARTS = ['totalbtc', 'difficulty', 'hashrate', 'chainsize', 'price', 'newaddress', 'txs', 'txs_ex']\nBLOCK_CHARTS = ['count', 'size', 'fee', 'avg_time', 'tx', 'coindd', 'orphancount']\nADDRESS_CHARTS = ['txs', 'received', 'sent', 'balance']\nBLOCK_INDEX_CHARTS = ['interval']\n\n\n\n ","sub_path":"blockmeta/tags.py","file_name":"tags.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"302074900","text":"# -*- coding: utf-8 -*-\n\"\"\"\nwbt_mini_cw_complex_3sector_conversions_test\n\nThis test reads data collected using a WBT-Mini with a 3 sector 38 kHz\nchannel and 1 sector 200 channel. The system was operated in CW mode\nwith a 1024 us pulse length. Data were recorded in complex form.\n\npower, Sv, Sp/TS, and angle data (38 kHz only) are compared with the\nsame data exported from Echoview. Ranges and ping times are also compared.\nThe data are also written to disk, then the re-writen data is read and\nthe power and angle data are compared to Echoview to ensure that the\nwrite methods are working properly.\n\nWhen the test is passing:\n\nPower values will match Echoview values\nSv and TS values will be within +-0.01 dB of Echoview values\nAngle values will be within +-0.01 deg. of Echoview values\nRange values will match\nPing time values will match\n\n\"\"\"\n\nimport os\nimport sys\nimport unittest\nimport unittest.runner\nimport itertools\nimport numpy as np\nfrom echolab2.instruments import EK80\nfrom echolab2.processing import processed_data\n\n\n\n# Set the max absolute differences allowed between echolab and echoview\n# for certain data types. For CW data, power values should match but differences\n# in the implementation of the conversion methods result in minor differences\nconvert_atol = 1e-02\nrewrite_atol = 12e-03\n\n# For Sv and TS values, pyEcholab and Echoview differ most in the first 13 samples\n# or so and so we skip comparing them.\nstart_sample = 13\n\n\n# Specify the data files for this test\n\n\nin_file = './data/EK80_WBAT_FM_std-cal_55-90(4)_test.raw'\nout_file = './data/test_write.raw'\n\n# Echoview power, Sv, TS, and angles data exports of above raw file\nev_Sv_filename = {}\nev_Sv_filename[72500] = './data/EK80_WBAT_FM_std-cal_EV-55-90_pc.Sv.mat'\n\nev_TS_filename = {}\nev_TS_filename[72500] = './data/EK80_WBAT_FM_std-cal_EV-55-90_pc.ts.csv'\n\nev_power_filename = {}\nev_power_filename[72500] = './data/EK80_WBAT_FM_std-cal_EV-55-90_pc.power.csv'\n\nev_angles_filename = {}\nev_angles_filename[72500] = './data/EK80_WBAT_FM_std-cal_EV-55-90_pc.angles.csv'\n\n\nclass wbt_fm_std_cal_test(unittest.TestCase):\n\n @classmethod\n def setUpClass(self):\n '''\n setUpClass is executed once, before all tests are conducted\n '''\n\n # Create an instance of EK80 and read the test data file\n self.ek80 = EK80.EK80()\n self.ek80.read_raw(in_file)\n\n self.progress_index = 0\n\n # Store a list of our channels for convienience\n self.channels = list(self.ek80.raw_data.keys())\n\n print()\n print('wbt_fm_std_cal_test')\n\n\n def test_TS_conversion(self):\n\n for chan in self.channels:\n # Get a reference to the first data object\n raw_data = self.ek80.raw_data[chan][0]\n\n # Get the frequency of this channel.\n this_freq = raw_data.get_frequency()[0]\n\n ev_file = ev_TS_filename.get(this_freq, None)\n if ev_file is not None:\n sys.stdout.write(('%i kHz ' % this_freq))\n\n # Get the Sp data\n Sp = raw_data.get_Sp()\n\n # Read the Echoview export file containing TS.\n ev_TS = processed_data.read_ev_csv('', 0, ev_file, data_type='TS')\n\n # Compare TS values\n self.assertTrue(np.allclose(Sp[:,start_sample:], ev_TS[:,start_sample:],\n atol=convert_atol, equal_nan=True))\n\n # Compare ranges\n self.assertTrue(np.allclose(Sp.range, ev_TS.range, equal_nan=True))\n\n # Compare times\n self.assertTrue(np.allclose(Sp.ping_time.view(dtype=np.uint64),\n ev_TS.ping_time.view(dtype=np.uint64), equal_nan=True))\n\n\n def test_power_conversion(self):\n\n for chan in self.channels:\n # Get a reference to the first data object\n raw_data = self.ek80.raw_data[chan][0]\n\n # Get the frequency of this channel.\n this_freq = raw_data.get_frequency()[0]\n\n ev_file = ev_power_filename.get(this_freq, None)\n if ev_file is not None:\n sys.stdout.write(('%i kHz ' % this_freq))\n\n # Get the power data\n power = raw_data.get_power()\n\n # Read the Echoview export file containing power.\n ev_power = processed_data.read_ev_csv('', 0, ev_file, data_type='power')\n\n # Compare power values\n self.assertTrue(np.allclose(power[:,:], ev_power[:,:], equal_nan=True))\n\n # Compare ranges\n self.assertTrue(np.allclose(power.range, ev_power.range, equal_nan=True))\n\n # Compare times\n self.assertTrue(np.allclose(power.ping_time.view(dtype=np.uint64),\n ev_power.ping_time.view(dtype=np.uint64), equal_nan=True))\n\n\n def test_Sv_conversion(self):\n\n for chan in self.channels:\n\n # Get a reference to the first data object\n raw_data = self.ek80.raw_data[chan][0]\n\n # Get the frequency of this channel.\n this_freq = raw_data.get_frequency()[0]\n\n ev_file = ev_Sv_filename.get(this_freq, None)\n if ev_file is not None:\n sys.stdout.write(('%i kHz ' % this_freq))\n\n # Get Sv\n Sv = raw_data.get_Sv()\n\n # Read the Echoview export file containing Sv.\n ev_Sv = processed_data.read_ev_mat('', 0, ev_file, data_type='Sv')\n\n # Compare Sv values\n self.assertTrue(np.allclose(Sv[:,start_sample], ev_Sv[:,start_sample],\n atol=convert_atol, equal_nan=True))\n\n # Compare ranges\n self.assertTrue(np.allclose(Sv.range, ev_Sv.range, equal_nan=True))\n\n # Compare times\n self.assertTrue(np.allclose(Sv.ping_time.view(dtype=np.uint64),\n ev_Sv.ping_time.view(dtype=np.uint64), equal_nan=True))\n\n\n def test_angle_conversion(self):\n\n for chan in self.channels:\n\n # Get a reference to the first data object\n raw_data = self.ek80.raw_data[chan][0]\n\n # Get the frequency of this channel. CW data will\n # have the frequency property\n this_freq = raw_data.get_frequency()[0]\n\n ev_file = ev_angles_filename.get(this_freq, None)\n if ev_file is not None:\n sys.stdout.write(('%i kHz ' % this_freq))\n\n # Get the angle data\n alongship, athwartship = raw_data.get_physical_angles()\n\n # Read the Echoview export file containing angles.\n ev_alongship, ev_athwartship = processed_data.read_ev_csv('', 0,\n ev_file, data_type='angles')\n\n # Compare angles\n self.assertTrue(np.allclose(alongship[:,:], ev_alongship[:,:],\n atol=convert_atol, equal_nan=True))\n self.assertTrue(np.allclose(athwartship[:,:], ev_athwartship[:,:],\n atol=convert_atol, equal_nan=True))\n\n # Compare ranges\n self.assertTrue(np.allclose(alongship.range, ev_alongship.range,\n equal_nan=True))\n self.assertTrue(np.allclose(athwartship.range, ev_athwartship.range,\n equal_nan=True))\n\n # Compare times\n self.assertTrue(np.allclose(alongship.ping_time.view(dtype=np.uint64),\n ev_alongship.ping_time.view(dtype=np.uint64), equal_nan=True))\n self.assertTrue(np.allclose(athwartship.ping_time.view(dtype=np.uint64),\n athwartship.ping_time.view(dtype=np.uint64), equal_nan=True))\n\n\n def test_write_raw(self):\n\n # Write the raw data to disk - provide a dict to map input filename\n # to output file name so we have full control of name.\n fname = os.path.split(in_file)[1]\n out_name = {fname:out_file}\n self.ek80.write_raw(out_name, overwrite=True)\n\n # The read this re-written data\n ek80rewrite = EK80.EK80()\n ek80rewrite.read_raw(out_file)\n\n # Get a list of the rewritten channels\n rewrite_channels = list(ek80rewrite.raw_data.keys())\n\n for chan in rewrite_channels:\n # Get a reference to the first data object\n raw_data = ek80rewrite.raw_data[chan][0]\n\n # Get the frequency of this channel.\n this_freq = raw_data.get_frequency()[0]\n\n ev_file = ev_power_filename.get(this_freq, None)\n if ev_file is not None:\n sys.stdout.write(('%i kHz ' % this_freq))\n\n # Get the power data\n power = raw_data.get_power()\n\n # Read the Echoview export file containing power.\n ev_power = processed_data.read_ev_csv('', 0, ev_file, data_type='power')\n\n # Compare power values\n self.assertTrue(np.allclose(power[:,:], ev_power[:,:], equal_nan=True))\n\n # Compare ranges\n self.assertTrue(np.allclose(power.range, ev_power.range, equal_nan=True))\n\n # Compare times\n self.assertTrue(np.allclose(power.ping_time.view(dtype=np.uint64),\n ev_power.ping_time.view(dtype=np.uint64), equal_nan=True))\n\n ev_file = ev_angles_filename.get(this_freq, None)\n if ev_file is not None:\n\n # Get the angle data\n alongship, athwartship = raw_data.get_physical_angles()\n\n # Read the Echoview export file containing angles\n ev_alongship, ev_athwartship = processed_data.read_ev_csv('', 0,\n ev_file, data_type='angles')\n\n # Compare angles\n self.assertTrue(np.allclose(alongship[:,:], ev_alongship[:,:],\n atol=convert_atol, equal_nan=True))\n self.assertTrue(np.allclose(athwartship[:,:], ev_athwartship[:,:],\n atol=convert_atol, equal_nan=True))\n\n\n\n'''\nCustomTextTestResult and CustomTextTestRunner adapted from code provided by StackOverflow\nuser Ken 'Joey' Mosher (https://stackoverflow.com/users/2887603/ken-joey-mosher)\n\nhttps://stackoverflow.com/questions/11532882/show-progress-while-running-python-unittest\n'''\nclass CustomTextTestResult(unittest.runner.TextTestResult):\n \"\"\"Extension of TextTestResult to support numbering test cases\"\"\"\n\n def __init__(self, stream, descriptions, verbosity):\n \"\"\"Initializes the test number generator, then calls super impl\"\"\"\n\n self.test_numbers = itertools.count(1)\n\n return super(CustomTextTestResult, self).__init__(stream, descriptions, verbosity)\n\n\n def startTest(self, test):\n \"\"\"Writes the test number to the stream if showAll is set, then calls super impl\"\"\"\n\n if self.showAll:\n progress = '[{0}/{1}] '.format(next(self.test_numbers), self.test_case_count)\n self.stream.write(progress)\n test.progress_index = progress\n\n return super(CustomTextTestResult, self).startTest(test)\n\n\n def _exc_info_to_string(self, err, test):\n \"\"\"Gets an exception info string from super, and prepends 'Test Number' line\"\"\"\n\n info = super(CustomTextTestResult, self)._exc_info_to_string(err, test)\n\n if self.showAll:\n info = 'Test number: {index}\\n{info}'.format(\n index=test.progress_index,\n info=info\n )\n\n return info\n\n\nclass CustomTextTestRunner(unittest.runner.TextTestRunner):\n \"\"\"Extension of TextTestRunner to support numbering test cases\"\"\"\n\n resultclass = CustomTextTestResult\n\n def run(self, test):\n \"\"\"Stores the total count of test cases, then calls super impl\"\"\"\n\n self.test_case_count = test.countTestCases()\n return super(CustomTextTestRunner, self).run(test)\n\n def _makeResult(self):\n \"\"\"Creates and returns a result instance that knows the count of test cases\"\"\"\n\n result = super(CustomTextTestRunner, self)._makeResult()\n result.test_case_count = self.test_case_count\n return result\n\n\nif __name__ == \"__main__\":\n\n test_funcs = ['test_power_conversion', 'test_Sv_conversion', 'test_TS_conversion',\n 'test_angle_conversion', 'test_write_raw']\n\n test_suite = unittest.TestSuite()\n tests = [wbt_fm_std_cal_test(func) for func in test_funcs]\n test_suite.addTests(tests)\n\n CustomTextTestRunner(verbosity=2).run(test_suite)\n\n","sub_path":"test/wbt_fm_std_cal_test.py","file_name":"wbt_fm_std_cal_test.py","file_ext":"py","file_size_in_byte":12594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345637426","text":"from tests import run_async\nfrom tests.unit.storage.user_repo import (\n TestUserRepo,\n user_data\n)\n\nfrom micro_tcg.storage.user_repo import get_by_id\n\n\nclass TestGetById(TestUserRepo):\n\n @run_async\n async def test_get_user_by_id(self):\n expected_id = user_data['_id']\n expected_name = user_data['name']\n db = TestGetById._db\n result = await get_by_id(db, expected_id)\n _id = result['_id']\n name = result['name']\n self.assertIsNotNone(result)\n self.assertEqual(name, expected_name)\n self.assertEqual(_id, expected_id)\n\n\n\n","sub_path":"tests/unit/storage/user_repo/test_get_by_id.py","file_name":"test_get_by_id.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"549240571","text":"\"\"\"5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.\nПрограмма должна подсчитывать сумму чисел в файле и выводить ее на экран.\n\"\"\"\n\nimport os\n\nDIR = 'files'\nfile_to_read_path = os.path.join(DIR, 'task5.txt')\nfile_to_write_path = os.path.join(DIR, 'task5.txt')\nnums_list_to_write = []\n\nwhile True:\n try:\n num = float(input('Введите число: '))\n nums_list_to_write.append(str(num))\n except ValueError:\n print('Ввод чисел прерван.')\n break\n\nwith open(file_to_write_path, 'w', encoding='utf-8') as file_write:\n print(f'{\" \".join(nums_list_to_write)}', file=file_write)\n\nwith open(file_to_read_path, 'r', encoding='utf-8') as file_read:\n nums_list = file_read.readline().split()\n nums_sum = 0\n for num in nums_list:\n nums_sum += float(num)\n\nprint(f'Сумма чисел:{nums_sum}')\n","sub_path":"lesson5/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"619349490","text":"'''\nFLAG PROJECT\n---------------\nMake your flag 260 pixels tall\nUse the scaling image on the website to determine other dimensions\nThe hexadecimal colors for the official flag are red:#BF0A30 and blue:#002868\nTitle the window, \"The Stars and Stripes\"\nI used a draw_text command and used 20 pt. asterisks for the stars.\nWe will have a competition to see who can make this flag in the least lines of code.\nThe record is 16! You will have to use some loops to achieve this.\n'''\n\nimport arcade\n\n#Height of flag 260 pixels, Fly of flag 494 pixels?\n#Red = (191, 10, 48)\n#Blue = (0, 40, 104)\n\narcade.open_window(500, 500, \"American Flag\") #Background\narcade.set_background_color(arcade.color.WHITE)\narcade.start_render()\nfor x_offset in range(0, 250, 40): #Stripes\n arcade.draw_rectangle_filled(250, 20+x_offset, 20, 494, (191, 10, 48), 90)\narcade.draw_rectangle_filled(94, 200, 182, 140, (0, 40, 104)) #Union\nfor x_offset in range(90, 210, 28): #Stars\n arcade.draw_text(\"* * * * * *\", 10, 40+x_offset, arcade.color.WHITE, 20)\nfor x_offset in range(90, 200, 28):\n arcade.draw_text(\"* * * * *\", 25, 55+x_offset, arcade.color.WHITE, 20)\narcade.finish_render()\narcade.run()\n\n\n\n","sub_path":"7.1_Flag.py","file_name":"7.1_Flag.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"531030984","text":"from flask import render_template, request, redirect, url_for\nfrom flask.ext.login import login_required, current_user\nfrom flask.views import MethodView\nfrom werkzeug.security import gen_salt\n\nfrom . import schemas, models\nfrom . import oauth, app\n\n\nclass ClientView(MethodView):\n decorators = [login_required]\n\n def get(self):\n return render_template('oauth2/client.html')\n\n def post(self):\n client_schema = schemas.ClientSchema()\n c, errors = client_schema.load(request.form)\n c = models.Client(\n client_id=gen_salt(40),\n client_secret=gen_salt(50),\n owner=current_user._get_current_object(),\n **c\n ).save()\n return redirect(url_for('.client_list'))\napp.add_url_rule('/client/new/', view_func=ClientView.as_view('client_new'))\n\n\n@app.route('/clients/')\n@login_required\ndef client_list():\n clients = models.Client.objects(\n owner=current_user._get_current_object()\n ).all()\n return render_template('oauth2/client_list.html', clients=clients)\n\n\n@app.route('/client//delete/')\n@login_required\ndef client_delete(client_id):\n try:\n models.Client.objects.get(\n client_id=client_id,\n owner=current_user._get_current_object()\n ).delete()\n except models.Client.DoesNotExist:\n pass\n return redirect(url_for('.client_list'))\n\n\nclass AuthorizeView(MethodView):\n decorators = [login_required, oauth.authorize_handler]\n\n def get(self, client_id, **kwargs):\n client = models.Client.objects.get(client_id=client_id)\n return render_template('oauth2/authorize.html', client=client, **kwargs)\n\n def post(self, *args, **kwargs):\n return True\napp.add_url_rule('/authorize/', view_func=AuthorizeView.as_view('authorize'))\n\n\n@app.route('/oauth/token/', methods=['POST'])\n@oauth.token_handler\ndef access_token():\n return None\n\n\n@app.route('/oauth/revoke/', methods=['POST'])\n@oauth.revoke_handler\ndef revoke_token():\n pass\n","sub_path":"note_redefined/oauth2/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"614853154","text":"#!/usr/bin/python3\n\nimport argparse\nimport sys\nimport os\nimport csv\nimport glob\n\nANNOTATION_DIR='/home/prj_gralign/data/BMC-exp-sim/NewAnnos/'\nRESULTS_DIR='/home/prj_gralign/data/BMC-exp-sim/Results/'\n\nEVENT_TYPES = ('A5', 'A3', 'IR', 'ES')\n\nspladder_ev_map = {'alt_5prime' : 'A5',\n 'alt_3prime' : 'A3',\n 'exon_skip' : 'ES',\n 'intron_retention' : 'IR',\n 'mult_exon_skip' : 'NA'}\n\nrmats_ev_map = { 'A5SS' : 'A5',\n 'A3SS' : 'A3',\n 'SE' : 'ES',\n 'RI' : 'IR'}\n\nsuppa_ev_map = {'A5' : 'A5',\n 'A3' : 'A3',\n 'SE' : 'ES',\n 'RI' : 'IR'}\n\ndef evaluate_asgal_annot(args, gene_events):\n asgal_introns = {ev_type : () for ev_type in EVENT_TYPES}\n with open(os.path.join(RESULTS_DIR, args.sample, args.chromosome, 'asgal_annot',\n args.gene, args.gene + '.events.csv'),\n newline='') as asgal_csv:\n results = csv.reader(asgal_csv)\n next(results, None) # Drop header\n for row in results:\n asgal_introns[row[0]] += ((int(row[1]) - 1, int(row[2]) + 1),)\n\n results = {ev_type : {} for ev_type in EVENT_TYPES}\n for ev_type in EVENT_TYPES:\n nelems = len(set(gene_events[ev_type]))\n tp=len(set(asgal_introns[ev_type]) & set(gene_events[ev_type].values()))\n fp=len(set(asgal_introns[ev_type]) - set(gene_events[ev_type].values()))\n fn=len(set(gene_events[ev_type].values()) - set(asgal_introns[ev_type]))\n results[ev_type] = {'nelems' : nelems, 'tp' : tp, 'fp' : fp, 'fn' : fn}\n return results\n\ndef evaluate_spladder_annot(args, gene_events):\n spladder_introns = {ev_type : () for ev_type in EVENT_TYPES}\n spladder_files_list = glob.glob(os.path.join(RESULTS_DIR, args.sample,\n args.chromosome, 'spladder_annot',\n args.gene, '*.txt'))\n for spladder_file in spladder_files_list:\n with open(spladder_file) as spladder_current_event_file:\n next(spladder_current_event_file, None) # Drop header\n for row in spladder_current_event_file:\n _, strand, event_id, _, *positions = row.strip('\\n').split('\\t')\n if event_id.startswith('mult'):\n # here spladder outputs multiple positions in columns 2 and 3\n # We can set them to 0 and avoid problems later on\n positions[2], positions[3] = 0, 0\n positions = tuple(int(p) for p in positions[:6])\n spladder_introns = spladder_parse_line(spladder_introns,\n event_id,\n strand,\n positions)\n results = {ev_type : {} for ev_type in EVENT_TYPES}\n for ev_type in EVENT_TYPES:\n nelems = len(set(gene_events[ev_type].values()))\n tp=len(set(spladder_introns[ev_type]) & set(gene_events[ev_type].values()))\n fp=len(set(spladder_introns[ev_type]) - set(gene_events[ev_type].values()))\n fn=len(set(gene_events[ev_type].values()) - set(spladder_introns[ev_type]))\n results[ev_type] = {'nelems' : nelems, 'tp' : tp, 'fp' : fp, 'fn' : fn}\n return results\n\ndef evaluate_rmats_annot(args, gene_events):\n # We do not consider MXE\n rmats_introns = {ev_type : () for ev_type in EVENT_TYPES}\n rmats_files_list = glob.glob(os.path.join(RESULTS_DIR, args.sample, args.chromosome,\n 'rMATS_annot', args.gene,\n 'fromGTF.[!(n,M)]*.txt'))\n for rmats_file in rmats_files_list:\n with open(rmats_file) as rmats_current_event_file:\n next(rmats_current_event_file, None) # Drop header\n rmats_ev_type = rmats_file[rmats_file.rfind('.', 0, rmats_file.rfind('.')) + 1:\n rmats_file.rfind('.')]\n ev_type = rmats_ev_map[rmats_ev_type]\n for row in rmats_current_event_file:\n _, _, _, _, strand, *positions = row.strip('\\n').split('\\t')\n positions = tuple(int(p) for p in positions)\n rmats_introns = rmats_parse_line(rmats_introns,\n ev_type,\n strand,\n positions)\n results = {ev_type : {} for ev_type in EVENT_TYPES}\n for ev_type in EVENT_TYPES:\n nelems = len(set(gene_events[ev_type].values()))\n tp=len(set(rmats_introns[ev_type]) & set(gene_events[ev_type].values()))\n fp=len(set(rmats_introns[ev_type]) - set(gene_events[ev_type].values()))\n fn=len(set(gene_events[ev_type].values()) - set(rmats_introns[ev_type]))\n results[ev_type] = {'nelems' : nelems, 'tp' : tp, 'fp' : fp, 'fn' : fn}\n return results\n\ndef evaluate_suppa_annot(args, gene_events):\n # We do not consider: MX (mutually exclusive), AF (alternative first exon), AL (alternative last exon)\n suppa_introns = {ev_type : () for ev_type in EVENT_TYPES}\n with open(os.path.join(RESULTS_DIR, args.sample, args.chromosome, 'suppa_annot',\n args.gene, 'iso_tpm.psi')) as suppa_file:\n next(suppa_file, None) # Drop header\n for line in suppa_file:\n info, _, positions1, positions2, strand, *_ = line.split('\\t')[0].split(':')\n _, event_id = info.split(';')\n if event_id in ['MX', 'AF', 'AL']:\n continue\n ev_type = suppa_ev_map[event_id]\n positions = tuple(int(p) for p in positions1.split('-') + positions2.split('-'))\n suppa_introns = suppa_parse_line(suppa_introns,\n ev_type,\n strand,\n positions)\n results = {ev_type : {} for ev_type in EVENT_TYPES}\n for ev_type in EVENT_TYPES:\n nelems = len(set(gene_events[ev_type].values()))\n tp=len(set(suppa_introns[ev_type]) & set(gene_events[ev_type].values()))\n fp=len(set(suppa_introns[ev_type]) - set(gene_events[ev_type].values()))\n fn=len(set(gene_events[ev_type].values()) - set(suppa_introns[ev_type]))\n results[ev_type] = {'nelems' : nelems, 'tp' : tp, 'fp' : fp, 'fn' : fn}\n return results\n\ndef spladder_parse_line(spladder_introns, event_id, strand, positions):\n ev_type = spladder_ev_map[event_id[0:event_id.rfind('_')]]\n if ev_type in ['ES', 'IR']:\n # Exon skipping, mult exon skipping, intron retention\n spladder_introns[ev_type] += ((positions[1], positions[4]),)\n elif ev_type is 'A5':\n if strand is '+':\n spladder_introns[ev_type] += ((positions[3], positions[0]),\n (positions[5], positions[0]))\n elif strand is '-':\n spladder_introns[ev_type] += ((positions[1], positions[2]),\n (positions[1], positions[4]))\n elif ev_type is 'A3':\n if strand is '+':\n spladder_introns[ev_type] += ((positions[1], positions[2]),\n (positions[1], positions[4]))\n elif strand is '-':\n spladder_introns[ev_type] += ((positions[3], positions[0]),\n (positions[5], positions[0]))\n return spladder_introns\n\ndef rmats_parse_line(rmats_introns, ev_type, strand, positions):\n if ev_type in ['ES', 'IR']:\n # Exon skipping, mult exon skipping, intron retention\n rmats_introns[ev_type] += ((positions[3], positions[4] + 1),)\n elif ev_type is 'A5':\n if strand is '+':\n rmats_introns[ev_type] += ((positions[1], positions[4] + 1),\n (positions[3], positions[4] + 1))\n elif strand is '-':\n rmats_introns[ev_type] += ((positions[5], positions[0] + 1),\n (positions[5], positions[2] + 1))\n elif ev_type is 'A3':\n if strand is '+':\n rmats_introns[ev_type] += ((positions[5], positions[0] + 1),\n (positions[5], positions[2] + 1))\n elif strand is '-':\n rmats_introns[ev_type] += ((positions[1], positions[4] + 1),\n (positions[3], positions[4] + 1))\n return rmats_introns\n\ndef suppa_parse_line(suppa_introns, ev_type, strand, positions):\n if ev_type is 'ES':\n suppa_introns[ev_type] += ((positions[0], positions[3]),)\n elif ev_type is 'IR':\n suppa_introns[ev_type] += ((positions[1], positions[2]),)\n elif ev_type in ['A3', 'A5']:\n suppa_introns[ev_type] += ((positions[0], positions[1]),\n (positions[2], positions[3]))\n return suppa_introns\n\ndef add_alternative_donor_acceptor(gene_events, ev_type, ev_num, positions):\n if positions[0] < positions[1] < positions[2]:\n gene_events[ev_type][(ev_type, ev_num, 'i')] = (positions[0], positions[2])\n gene_events[ev_type][(ev_type, ev_num, 'e')] = (positions[1], positions[2])\n else:\n gene_events[ev_type][(ev_type, ev_num, 'e')] = (positions[0], positions[2])\n gene_events[ev_type][(ev_type, ev_num, 'i')] = (positions[1], positions[2])\n return gene_events\n\ndef parse_gene_events(args):\n gene_events = {ev_type : {} for ev_type in EVENT_TYPES}\n with open(os.path.join(ANNOTATION_DIR,\n args.chromosome,\n args.gene + '.events')) as gene_events_file:\n for line in gene_events_file:\n _, ev_type, *positions, ev_id = line.strip('\\n').split(' ')\n positions = tuple(int(p) for p in positions)\n _, ev_num = ev_id[:2], ev_id[2:]\n if not ev_type.startswith('A'):\n gene_events[ev_type][(ev_type, ev_num)] = (positions[0], positions[1])\n else:\n gene_events = add_alternative_donor_acceptor(gene_events, ev_type,\n ev_num, positions)\n return gene_events\n\ndef main():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-c', '--chr', dest='chromosome', help='Chromosome name', required=True)\n parser.add_argument('-g', '--gene', dest='gene', help='Gene name', required=True)\n parser.add_argument('-s', '--sample-size', dest='sample', help='Sample Size', required=True)\n\n args = parser.parse_args()\n\n gene_events = parse_gene_events(args)\n\n print(\"SIZE,GENOME,GENE,TOOL,EV_TYPE,NELEMS,TP,FP,FN\")\n\n results = evaluate_asgal_annot(args, gene_events)\n for ev_type in EVENT_TYPES:\n print(\"{},{},{},asgal-annot,{},{},{},{},{}\".format(args.sample, args.chromosome,\n args.gene,\n ev_type,\n results[ev_type]['nelems'],\n results[ev_type]['tp'],\n results[ev_type]['fp'],\n results[ev_type]['fn']))\n\n results = evaluate_spladder_annot(args, gene_events)\n for ev_type in EVENT_TYPES:\n print(\"{},{},{},spladder-annot,{},{},{},{},{}\".format(args.sample, args.chromosome,\n args.gene,\n ev_type,\n results[ev_type]['nelems'],\n results[ev_type]['tp'],\n results[ev_type]['fp'],\n results[ev_type]['fn']))\n\n results = evaluate_rmats_annot(args, gene_events)\n for ev_type in EVENT_TYPES:\n print(\"{},{},{},rmats-annot,{},{},{},{},{}\".format(args.sample, args.chromosome,\n args.gene,\n ev_type,\n results[ev_type]['nelems'],\n results[ev_type]['tp'],\n results[ev_type]['fp'],\n results[ev_type]['fn']))\n\n results = evaluate_suppa_annot(args, gene_events)\n for ev_type in EVENT_TYPES:\n print(\"{},{},{},suppa-annot,{},{},{},{},{}\".format(args.sample, args.chromosome,\n args.gene,\n ev_type,\n results[ev_type]['nelems'],\n results[ev_type]['tp'],\n results[ev_type]['fp'],\n results[ev_type]['fn']))\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"comparANNOT.py","file_name":"comparANNOT.py","file_ext":"py","file_size_in_byte":13601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"14443810","text":"from collections import deque\nd = deque()\n\nn = int(input())\n\nfor i in range(n):\n \n ins = input().strip().split()\n \n if ins[0] == 'append':\n d.append(ins[1])\n elif ins[0] == 'pop':\n d.pop()\n elif ins[0] == 'popleft':\n d.popleft()\n elif ins[0] == 'appendleft':\n d.appendleft(ins[1])\n \nprint(*d)","sub_path":"python/Hackerrrank/deque.py","file_name":"deque.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"564050914","text":"\nfrom perso_lib.transaction.trans_base import *\nfrom perso_lib.transaction.trans_pse import PseTrans,PpseTrans\nfrom perso_lib import utils\nfrom perso_lib import algorithm\nfrom perso_lib.apdu import Crypto_Type\nfrom perso_lib.log import Log\nfrom perso_lib.transaction.utils import terminal,auth,tools\nfrom perso_lib.transaction.utils.property import App_Master_Key,PROCESS_STEP,TransTag\n\nclass VisaTrans(TransBase):\n def __init__(self):\n super().__init__()\n\n def application_selection(self,aid):\n resp = super().application_selection(aid)\n tools.output_apdu_info(resp)\n self.store_tag_group(PROCESS_STEP.SELECT,utils.parse_tlv(resp.response))\n self.run_case('case_application_selection','run_visa',resp)\n return resp\n\n def gpo_VSDC(self):\n tag9F38 = self.get_tag(PROCESS_STEP.SELECT,'9F38')\n data = ''\n if tag9F38:\n data = tools.assemble_dol(tag9F38)\n resp = super().gpo(data)\n if resp.sw == 0x9000:\n tools.output_not_tlv_gpo_info(resp)\n self.store_tag(PROCESS_STEP.GPO,'82',resp.response[4:8])\n self.store_tag(PROCESS_STEP.GPO,'94',resp.response[8:])\n self.run_case('case_gpo','run_visa',resp)\n return resp\n\n def gpo_qVSDC(self):\n tag9F38 = self.get_tag(PROCESS_STEP.SELECT,'9F38')\n data = ''\n if tag9F38:\n data = tools.assemble_dol(tag9F38)\n resp = super().gpo(data)\n if resp.sw == 0x9000:\n tools.output_apdu_info(resp)\n self.store_tag_group(PROCESS_STEP.GPO,utils.parse_tlv(resp.response))\n # self.run_case('case_gpo','run_visa',resp)\n return resp\n\n def read_record(self):\n resps = None\n tag94 = self.get_tag(PROCESS_STEP.GPO,'94')\n if tag94:\n resps = super().read_record(tag94)\n for resp in resps:\n self.store_tag_group(PROCESS_STEP.READ_RECORD,utils.parse_tlv(resp.response))\n self.run_case('case_read_record','run_visa',resps)\n return resps\n\n def first_gac(self):\n tag8C = self.get_tag(PROCESS_STEP.READ_RECORD,'8C')\n data = tools.assemble_dol(tag8C)\n resp = super().gac(Crypto_Type.ARQC,data)\n if resp.sw != 0x9000:\n Log.info('send gac1 failed.')\n return\n tlvs = utils.parse_tlv(resp.response)\n if len(tlvs) != 1 and tlvs[0].tag != '80':\n Log.info('gac1 response data error')\n data = tlvs[0].value\n self.store_tag(PROCESS_STEP.FIRST_GAC,'9F27',data[0:2])\n self.store_tag(PROCESS_STEP.FIRST_GAC,'9F36',data[2:6])\n self.store_tag(PROCESS_STEP.FIRST_GAC,'9F26',data[6:22])\n self.store_tag(PROCESS_STEP.FIRST_GAC,'9F10',data[22:])\n return resp\n\n def divert_key(self):\n if self.key_flag == App_Master_Key.MDK:\n tag5A = self.get_tag(PROCESS_STEP.READ_RECORD,'5A')\n tag5F34 = self.get_tag(PROCESS_STEP.READ_RECORD,'5F34')\n self.key_ac = auth.gen_udk(self.key_ac,tag5A,tag5F34)\n self.key_mac = auth.gen_udk(self.key_mac,tag5A,tag5F34)\n self.key_enc = auth.gen_udk(self.key_enc,tag5A,tag5F34)\n tag9F36 = self.get_tag('9F36')\n self.session_key_ac = auth.gen_udk_session_key_emv(self.key_ac,tag9F36)\n self.session_key_mac = auth.gen_udk_session_key_emv(self.key_mac,tag9F36)\n self.session_key_enc = auth.gen_udk_session_key_emv(self.key_enc,tag9F36)\n \n def issuer_auth(self):\n tag9F26 = self.get_tag(PROCESS_STEP.FIRST_GAC,'9F26')\n if not self.cvn:\n Log.error('can not get CVN, check tag9F10 wether existed.')\n return\n if self.cvn == '0A': # CVN10处理流程\n arc = '3030'\n key = self.key_ac\n if self.key_flag == App_Master_Key.MDK:\n tag5A = self.get_tag(PROCESS_STEP.READ_RECORD,'5A')\n tag5F34 = self.get_tag(PROCESS_STEP.READ_RECORD,'5F34')\n key = auth.gen_udk(key,tag5A,tag5F34)\n arpc = auth.gen_arpc_by_des3(key,tag9F26,arc)\n resp = apdu.external_auth(arpc,arc)\n if resp.sw == 0x9000:\n return True\n elif self.cvn == '12': # CVN18处理流程\n csu = '00820000' \n self.divert_key() #需要使用AC session key\n arpc = auth.gen_arpc_by_mac(self.session_key_ac,tag9F26,csu)\n terminal.set_terminal('91',arpc + csu)\n return True\n return False\n\n\n def second_gac(self):\n tag8D = self.get_tag(PROCESS_STEP.READ_RECORD,'8D')\n data = tools.assemble_dol(tag8D)\n resp = super().gac(Crypto_Type.TC,data)\n if resp.sw != 0x9000:\n Log.info('send gac1 failed.')\n return\n return resp\n\n def get_data(self):\n tags = ['9F75','9F72']\n super().get_data(tags)\n self.run_case('case_get_data','run_visa')\n\n def put_data(self,tag,value):\n tag9F36 = self.get_tag('9F36')\n tag9F26 = self.get_tag(PROCESS_STEP.FIRST_GAC,'9F26')\n key_input = '000000000000' + tag9F36 + '000000000000' + algorithm.xor(tag9F36,'FFFF')\n if len(tag) == 2:\n tag = '00' + tag\n data_len = utils.int_to_hex_str(len(value) // 2 + 8)\n mac_input = '04DA' + tag + data_len + tag9F36 + tag9F26 + value\n key_mac = algorithm.xor(key_input,self.key_mac)\n mac = algorithm.des3_mac(key_mac,mac_input)\n apdu.put_data(tag,value,mac)\n\n def unlock_app(self):\n tag9F36 = self.get_tag('9F36')\n tag9F26 = self.get_tag(PROCESS_STEP.FIRST_GAC,'9F26')\n key_input = '000000000000' + tag9F36 + '000000000000' + algorithm.xor(tag9F36,'FFFF')\n mac_input = '8418000008' + tag9F36 + tag9F26\n key_mac = algorithm.xor(key_input,self.key_mac)\n mac = algorithm.des3_mac(key_mac,mac_input)\n apdu.unlock_app(mac)\n\n def lock_app(self):\n tag9F36 = self.get_tag('9F36')\n tag9F26 = self.get_tag(PROCESS_STEP.FIRST_GAC,'9F26')\n key_input = '000000000000' + tag9F36 + '000000000000' + algorithm.xor(tag9F36,'FFFF')\n mac_input = '841E000008' + tag9F36 + tag9F26\n key_mac = algorithm.xor(key_input,self.key_mac)\n mac = algorithm.des3_mac(key_mac,mac_input)\n apdu.lock_app(mac)\n\n\n def do_contact_trans(self,do_pse=True,aid=\"A0000000031010\"):\n '''\n Visa借记/贷记接触交易主流程\n '''\n if do_pse:\n self.pse = PseTrans()\n self.pse.application_selection()\n aids = self.pse.read_record()\n for index,aid in enumerate(aids):\n print(\"{0}: {1}\".format(index,aid))\n aid_index = input('select app to do transaction:')\n self.application_selection(aids[int(aid_index)])\n else:\n self.application_selection(aid)\n self.gpo_VSDC()\n self.read_record()\n self.get_data()\n self.do_dda()\n self.first_gac()\n self.issuer_auth()\n self.second_gac()\n\n def do_contactless_trans(self):\n self.ppse = PpseTrans()\n aids = self.ppse.application_selection()\n if aids:\n for index,aid in enumerate(aids):\n print(\"{0}: {1}\".format(index,aid))\n aid_index = input('select app to do transaction:')\n self.application_selection(aids[int(aid_index)])\n self.gpo_qVSDC()\n self.read_record()\n self.get_data()\n self.do_dda(fDDA=True)\n\n\nif __name__ == '__main__':\n from perso_lib.pcsc import get_readers,open_reader\n from perso_lib.transaction.utils import terminal\n from perso_lib.transaction.trans_pse import PseTrans,PpseTrans\n from perso_lib.transaction.utils.property import App_Master_Key\n from perso_lib.log import Log\n import time\n\n Log.init()\n terminal.set_terminal(App_Master_Key.UDK,'5856D35E3405B7C2D97B65809468C2D31C71E2AE1EED4377603877A357428DBAF6241FCA77459F62ACB2CA38CDFD7175')\n trans = VisaTrans()\n readers = get_readers()\n for index,reader in enumerate(readers):\n print(\"{0}: {1}\".format(index,reader))\n index = input('select readers: ')\n if open_reader(readers[int(index)]):\n #================= contactless trans ==================\n # terminal.set_offline_only()\n # terminal.set_currency_code('0446')\n # trans.do_contactless_trans()\n #=================== contact trans ====================\n trans.do_contact_trans()\n trans.put_data('9F79','000000010000')\n resp = apdu.get_data('9F79')\n print(resp.response)\n trans.lock_app()\n trans.unlock_app()\n","sub_path":"perso_lib/transaction/trans_visa.py","file_name":"trans_visa.py","file_ext":"py","file_size_in_byte":8690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602840473","text":"import numpy as np\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport tensorflow as tf \nimport xlrd\nimport matplotlib.pyplot as plt #imports\n\n#read the xls file\nDATAFILE = \"C:/Users/Akshit/Desktop/HUL2.csv\"\n\nbook = xlrd.open_workbook(DATAFILE, encoding_override=\"utf-8\")\nsheet = book.sheet_by_index(0)\ndata = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])\nn_samples = sheet.nrows - 1\n\nX = tf.placeholder(tf.float32, name = 'X')\nY = tf.placeholder(tf.float32, name = 'Y')\n\nw = tf.Variable(0.0, name = \"weights\")\nb = tf.Variable(0.0, name = \"bias\")\n\nY_predicted = X * w + b\n\nloss = tf.square(Y - Y_predicted, name=\"loss\")\n\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n for i in range(100):\n for x, y in data:\n sess.run(optimizer, feed_dict={X:x , Y:y})\n w_value, b_value = sess.run([w , b])\n print(w_value)\n print(b_value)\n for i in range(100):\n for x,y in data:\n plt.plot(x,y,'g-')\n plt.show()\n \n","sub_path":"Data Analytics-Python Codes/tf2.py","file_name":"tf2.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"223166569","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom utils import list_ds, get_gray_image, plot_matches, save_images\n\n\ndef compute_threshold(matcherType, method, ROOTSIFT):\n if matcherType == \"BFMatcher\":\n \n if method == \"SIFT\":\n if ROOTSIFT == False:\n th = 90 \n # Min number of matches to considerer a good retrieval\n descsMin = 15\n else:\n th = 0.15\n descsMin = 5\n \n elif method==\"ORB\":\n th = 25\n descsMin = 5\n \n elif method==\"KAZE\":\n th = 0.3\n descsMin = 5\n elif method ==\"HOG\":\n th = 1\n descsMin = 5\n elif method==\"FREAK\":\n th = 25\n descsMin = 5\n\n elif method==\"SURF\":\n th = 0.35\n descsMin = 5\n \n else: \n print(\"invalid method: \", method)\n \n # if Flann \n else:\n if method==\"DAISY\":\n th = 0.5\n descsMin = 3\n \n elif method == \"SIFT\":\n # valor distancia min\n th = 0.7 \n # Min number of matches to considerer a good retrieval\n descsMin = 50\n \n elif method==\"ORB\":\n th = 0.5\n descsMin = 5\n \n elif method==\"KAZE\":\n th = 0.3\n descsMin = 5\n\n elif method==\"SURF\":\n th = 0.35\n descsMin = 5\n\n \n elif method ==\"HOG\":\n th = 0.3\n descsMin = 5\n else: \n print(\"invalid method: \", method)\n \n return th, descsMin\n\ndef feature_detection(featureType, im):\n \n if featureType==\"SURF\":\n minHessian = 100\n detector = cv2.xfeatures2d.SURF_create(hessianThreshold=minHessian)\n return detector.detect(im)\n \n elif featureType==\"FAST\":\n # Initiate FAST object with default values\n fast = cv2.FastFeatureDetector_create()\n return fast.detect(im,None)\n \n\ndef compute_kp_desc(im, method, descriptor):\n \"\"\"\n Compute kps and desc depending of the chosen method\n \"\"\"\n \n if method == \"DAISY\" or method==\"FREAK\":\n # FAST / SURF\n keypoints = feature_detection(\"SURF\", im)\n desc = descriptor.compute(im, keypoints) \n return keypoints, desc\n \n elif method == \"HOG\":\n locs = []\n\n ders = descriptor.compute(im)\n return (locs, ders)\n \n else:\n return descriptor.detectAndCompute(im, None) \n \n\ndef init_method(method):\n if method == \"SIFT\":\n return cv2.xfeatures2d.SIFT_create()\n \n elif method == \"ORB\":\n return cv2.ORB_create(nfeatures=500,scoreType=cv2.ORB_HARRIS_SCORE)\n \n elif method == \"HOG\":\n winSize = (64,64)\n blockSize = (32,32)\n blockStride = (16,16)\n cellSize = (16,16)\n nbins = 9\n return cv2.HOGDescriptor(winSize, blockSize, blockStride, cellSize, nbins )\n\n elif method == \"DAISY\":\n return cv2.xfeatures2d.DAISY_create()\n\n elif method == \"FREAK\":\n return cv2.xfeatures2d.FREAK_create()\n elif method==\"KAZE\":\n return cv2.KAZE_create(extended=True, upright=True, threshold=0.001)\n \n elif method == \"SURF\":\n return cv2.xfeatures2d.SURF_create(1200)\n\n \ndef define_measurement(method):\n \n if method == \"SIFT\":\n return cv2.NORM_L2\n \n elif method == \"ORB\":\n return cv2.NORM_HAMMING\n \n elif method == \"SURF\": #set to NORM_L1 or NORM_L2.\n return cv2.NORM_L1\n \n elif method == \"HOG\":\n return cv2.NORM_L2\n \n else: \n return cv2.NORM_L2\n \n\n\ndef define_prepared_image(method, imName, path, resize):\n if method == \"HOG\":\n return get_gray_image(imName, path, resize, 256)\n else:\n return get_gray_image(imName, path, resize)\n\n \n \ndef compute_sift(path, method, resize = False, rootSift = False, eps = 1e-7, save = False):\n sift_result = {}\n # Get DS images names list \n im_list = list_ds(path)\n \n # Creates SIFT object\n desc_init = init_method(method)\n\n for imName in im_list:\n print(imName)\n # Load Gray version of each image\n imSource = define_prepared_image(method, imName, path, resize)\n \n # Find KeyLpoints and Sift Descriptors, info about KeyPoint objects -> https://docs.opencv.org/3.3.1/d2/d29/classcv_1_1KeyPoint.html\n (kps, descs) = compute_kp_desc(imSource, method, desc_init)\n \n if save == True:\n save_images(kps, imName, imSource)\n \n if method == 'HOG':\n descs = descs.ravel()\n # In case no kps were found\n elif len(kps) == 0:\n (kps, descs) = ([], None)\n \n # RootSift descriptor, sift improvement descriptor\n elif(rootSift == True):\n descs /= (descs.sum(axis=1, keepdims=True) + eps)\n descs = np.sqrt(descs) \n \n # Append results \n sift_result[imName] = [imName, kps, descs] \n \n return sift_result\n\ndef BFMatcher(N, siftA, siftB, method, pathA = '', pathB = '', plot = False, resize = False):\n imNameA, kpsA, descsA = siftA \n imNameB, kpsB, descsB = siftB \n \n # fix how data is stored\n if method==\"FREAK\":\n descsA=descsA[1]\n descsB=descsB[1]\n \n # create a BFMatcher object which will match up the SIFT features\n # select measurement for the BFMatcher \n distance_type = define_measurement(method)\n \n\n # Useful info about DMatch objects -> https://docs.opencv.org/java/2.4.9/org/opencv/features2d/DMatch.html\n \n # Declare objects\n if method == \"SURF\" or method == \"HOG\":\n bf = cv2.BFMatcher(distance_type)\n else:\n bf = cv2.BFMatcher(distance_type, crossCheck=True)\n \n # Generate matches \n if method == \"HOG\":\n match = bf.knnMatch(descsA, descsB, 1)\n matches = [item for sublist in match for item in sublist]\n \n else:\n \n matches = bf.match(descsA, descsB)\n \n # Sort the matches in the order of their distance.\n matches = sorted(matches, key = lambda x:x.distance)\n\n # keep N top matches\n matches = matches[0:N]\n if(plot == True):\n # Plots both images + theirs coincident matches\n plot_matches(siftA, siftB, pathA, pathB, matches, resize)\n \n return matches\n\n\ndef retreive_image(siftDs, siftQueries, paths, k, th = 60, descsMin = 3, method=\"SIFT\", plot = False, resize = False): \n queriesResult = []\n distancesResult = []\n finalMatch=[]\n i = 0\n l = len(siftQueries)\n for imNameQuery in siftQueries:\n matches = []\n siftQuery = siftQueries[imNameQuery]\n print('Query', str(i+1)+'/'+str(l),'started.')\n i+=1 \n for imNameDs in siftDs:\n siftIm = siftDs[imNameDs]\n \n # As a default just return 100 best matches per image, could be incresed\n matchesBF = BFMatcher(100, siftQuery, siftIm, method, pathA=paths['pathQueriesValidation'], \n pathB = paths['pathDS'], plot = plot, resize = resize)\n \n \n distance = [o.distance for o in matchesBF if o.distance <= th]\n \n matches.append([imNameDs, distance])\n\n # Sort images per number of matches under threshold level\n matches = sorted(matches, key = lambda x:len(x[1]), reverse = True)\n \n if(len(matches) > k):\n matches = matches[0:k]\n \n # Detect if image is not present in the Dataset\n tots=0\n for index,row in enumerate(matches):\n # Comprobar si tots son mes petits a un threshold\n if len(row[1]) < descsMin:\n tots+=1\n \n # Contruct query result to be returend\n distancesResult.append([ row[1] for row in matches ])\n queriesResult.append([ row[0] for row in matches ] if tots<10 else [-1])\n \n finalMatch.append(matches)\n \n \n return queriesResult, distancesResult, finalMatch\n\n# Computes distances taking into account GT pairs\ndef get_gt_distance(N, sift_ds, sift_validation, gt_list, paths, method,resize = False):\n validationMatches = []\n \n for i,imName in enumerate(sift_validation):\n imQuery = gt_list[i][0]\n \n print(\"\\n Query: \", imQuery)\n if(imQuery == -1): \n # Image not in the DS\n pass\n \n else:\n siftA = sift_validation[imName]\n siftB = sift_ds[imQuery]\n matchesBF = BFMatcher(N, siftA, siftB, method,pathA=paths['pathQueriesValidation'], \n pathB = paths['pathDS'], plot = True, resize = resize) \n \n \n validationMatches.append([imName, [o.distance for o in matchesBF] ])\n \n return validationMatches\n\n# Creates Stats from Distances Results\ndef get_distances_stats(N, matches, plot = False):\n distances = []\n for n in range(N):\n for i in range(len(matches)):\n try:\n if(i == 0):\n distances.append([matches[i][1][n]])\n else:\n distances[n].append(matches[i][1][n])\n except IndexError:\n if(i == 0):\n distances.append([None])\n else:\n distances[n].append(None)\n stats = []\n for entry in distances:\n try:\n entry = [x for x in entry if x != None]\n except ValueError:\n pass \n stats.append([np.min(entry),np.max(entry),np.mean(entry),np.std(entry)])\n\n result = np.array(stats)\n if(plot == True):\n plt.errorbar(np.arange(N), result[:,2], result[:,3], fmt='ok', lw=3)\n plt.errorbar(np.arange(N), result[:,2], [result[:,2] - result[:,0], \n result[:,1] - result[:,2]],fmt='.k', ecolor='gray', lw=1)\n plt.xlim(-1, N) \n plt.ylabel('Distance')\n plt.xlabel('Ordered descritor #')\n plt.title('GT BFMatcher')\n plt.show() \n \n return result\n\ndef remove_kps(siftDict, area):\n# area dictionary of list => [tlx, tly, brx, bry]\n# key same as for SiftDicts, image names.\n for entry in siftDict:\n name, kps, descs = siftDict[entry]\n \n if len(area[name]) >0: \n tlx, tly, brx, bry = area[name]\n i = len(kps)\n for kp in reversed(kps):\n kpx, kpy = kp.pt\n if(kpy < bry and kpy > tly):\n if(kpx < brx and kpx > tlx):\n # KPs withing forgiben area\n kps.pop(i-1)\n descs = np.delete(descs,i-1,0) \n i -= 1\n siftDict[entry] = [name, kps, descs]\n return siftDict","sub_path":"painting_retrieval - week 3/sift.py","file_name":"sift.py","file_ext":"py","file_size_in_byte":10995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"114117124","text":"import tensorflow as tf\nimport numpy as np\nimport numpy.linalg as npla\nimport sys\n\n\ndef prepare_adj(adj):\n I = np.identity(adj.shape[0])\n adj_bar = adj + I\n D = np.sum(adj_bar, axis = 1)\n return np.diag(D**(-0.5)) @ adj_bar @ np.diag(D**(-0.5))\n\ndef sgc_layer(numhop, W, A, H):\n layer = tf.matmul(A, H)\n for i in range(numhop - 1):\n layer = tf.matmul(A, layer)\n layer = tf.matmul(layer, W)\n return layer\n\ndef sgc_autoencoder(X, We, Wx, Wk, Wd, A):\n '''\n input:\n X: f*n array of flows\n A: n*n array of edge adj\n output:\n X': f*n array\n '''\n I = sgc_layer(numhop=4, W = We, A=A, H=X)\n E = tf.matmul(Wx, I)\n E = tf.nn.relu(tf.math.subtract(E, Wk))\n x_bar = tf.transpose(tf.matmul(E, Wd))\n return x_bar\n\ndef load_data(path):\n flows = np.load(path+'flows.npy')\n edge_adj = np.load(path+'adj.npy')\n return flows, edge_adj\n\npath = '/home/zhaotang/Documents/eigen_path/gcn/data/3/'\n\nflows, edge_adj = load_data(path)\nn_edges = flows.shape[1]\nn_flows = 1\nn_paths = 1\nprint('H dim', flows.shape)\nweights = {\n 'encoder': tf.Variable(tf.random_normal([n_flows, n_paths])),\n 'extra': tf.Variable(tf.random_normal([n_flows, n_edges])),\n 'const': tf.Variable(tf.random_normal([n_flows, n_paths])),\n 'decoder': tf.Variable(tf.random_normal([n_paths, n_edges]))\n}\n\ntraining_epochs = 3000\nbatch_size = 1\ndropout = tf.placeholder(\"float\")\n\nX = tf.placeholder(\"float\", [n_edges, n_flows])\nA = tf.constant(prepare_adj(edge_adj), dtype = \"float\" , shape = [n_edges, n_edges])\n\npred_flows = sgc_autoencoder(X, weights['encoder'], weights['extra'], weights['const'], weights['decoder'], A)\nloss = tf.nn.l2_loss(tf.math.subtract(pred_flows, X))\noptimizer = tf.train.AdamOptimizer(learning_rate=0.0003).minimize(loss)\nWe_print = tf.print(\"encoder:\", weights['encoder'], output_stream=sys.stdout)\nWd_print = tf.print(\"decoder:\", weights['decoder'], output_stream=sys.stdout)\n\n#path_val = '/home/zhaotang/Documents/eigen_path/gcn/data/2/'\n\n#flows_val, edge_adj_val = load_data(path_val)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n prev_loss = 0.1\n for epoch in range(training_epochs):\n avg_loss = 0.0\n total_batch = int(len(flows) / batch_size)\n for i in range(total_batch-1):\n batch_X = flows[i*batch_size:(i+1)*batch_size]\n _, c = sess.run([optimizer, loss], \n feed_dict={\n X: batch_X.T,\n dropout: 0.2\n })\n avg_loss += c / total_batch\n print('epoch', epoch,'avgloss', avg_loss)\n if(avg_loss < 0.5) and epoch > 1:\n break\n prev_loss = avg_loss\n sess.run([We_print, Wd_print])\n \n '''\n avg_loss_val = 0.0\n total_batch_val = int(len(flows_val) / batch_size)\n for i in range(total_batch_val-1):\n batch_X_val = flows_val[i*32:(i+1)*32]\n [c] = sess.run([loss],\n feed_dict={\n X: batch_X_val,\n dropout: 0.2\n })\n avg_loss_val += c / total_batch_val\n print(\"Validation loss:\", avg_loss_val)\n '''\n","sub_path":"gcn/sgc_autoencoder/sgc_autoencoder.py","file_name":"sgc_autoencoder.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"7004654","text":"# coding:utf-8\nimport numpy as np\nimport lda\nimport lda.datasets\nimport jieba\nimport codecs\n\n\nclass LDA_v20161130():\n def __init__(self, topics=2):\n self.n_topic = topics\n self.corpus = None\n self.vocab = None\n self.ppCountMatrix = None\n self.stop_words = [u',', u'。', u'、', u'(', u')', u'·', u'!', u' ', u':', u'“', u'”', u'\\n']\n self.model = None\n\n def loadCorpusFromFile(self, fn):\n # 中文分词\n f = open(fn, 'r')\n text = f.readlines()\n text = r' '.join(text)\n\n seg_generator = jieba.cut(text)\n seg_list = [i for i in seg_generator if i not in self.stop_words]\n seg_list = r' '.join(seg_list)\n # 切割统计所有出现的词纳入词典\n seglist = seg_list.split(\" \")\n self.vocab = []\n for word in seglist:\n if (word != u' ' and word not in self.vocab):\n self.vocab.append(word)\n\n CountMatrix = []\n f.seek(0, 0)\n # 统计每个文档中出现的词频\n for line in f:\n # 置零\n count = np.zeros(len(self.vocab), dtype=np.int)\n text = line.strip()\n # 但还是要先分词\n seg_generator = jieba.cut(text)\n seg_list = [i for i in seg_generator if i not in self.stop_words]\n seg_list = r' '.join(seg_list)\n seglist = seg_list.split(\" \")\n # 查询词典中的词出现的词频\n for word in seglist:\n if word in self.vocab:\n count[self.vocab.index(word)] += 1\n CountMatrix.append(count)\n f.close()\n # self.ppCountMatrix = (len(CountMatrix), len(self.vocab))\n self.ppCountMatrix = np.array(CountMatrix)\n\n print(\"load corpus from %s success!\",fn)\n\n def setStopWords(self, word_list):\n self.stop_words = word_list\n\n def fitModel(self, n_iter=1500, _alpha=0.1, _eta=0.01):\n self.model = lda.LDA(n_topics=self.n_topic, n_iter=n_iter, alpha=_alpha, eta=_eta, random_state=1)\n self.model.fit(self.ppCountMatrix)\n\n def printTopic_Word(self, n_top_word=8):\n for i, topic_dist in enumerate(self.model.topic_word_):\n topic_words = np.array(self.vocab)[np.argsort(topic_dist)][:-(n_top_word + 1):-1]\n print(\"Topic:\", i, \"\\t\")\n for word in topic_words:\n print (word,)\n print\n\n def printDoc_Topic(self):\n for i in range(len(self.ppCountMatrix)):\n print (\"Doc %d:((top topic:%s) topic distribution:%s)\" % (\n i, self.model.doc_topic_[i].argmax(), self.model.doc_topic_[i]))\n\n def printVocabulary(self):\n print(\"vocabulary:\")\n for word in self.vocab:\n print(word,)\n print\n\n def saveVocabulary(self, fn):\n f = codecs.open(fn, 'w', 'utf-8')\n for word in self.vocab:\n f.write(\"%s\\n\" % word)\n f.close()\n\n def saveTopic_Words(self, fn, n_top_word=-1):\n if n_top_word == -1:\n n_top_word = len(self.vocab)\n f = codecs.open(fn, 'w', 'utf-8')\n for i, topic_dist in enumerate(self.model.topic_word_):\n topic_words = np.array(self.vocab)[np.argsort(topic_dist)][:-(n_top_word + 1):-1]\n f.write(\"Topic:%d\\t\" % i)\n for word in topic_words:\n f.write(\"%s \" % word)\n f.write(\"\\n\")\n f.close()\n\n def saveDoc_Topic(self, fn):\n f = codecs.open(fn, 'w', 'utf-8')\n for i in range(len(self.ppCountMatrix)):\n f.write(\"Doc %d:((top topic:%s) topic distribution:%s)\\n\" % (\n i, self.model.doc_topic_[i].argmax(), self.model.doc_topic_[i]))\n f.close()\n\nif __name__==\"__main__\":\n _lda = LDA_v20161130(topics=20)\n stop = [u'!', u'@', u'#', u',',u'.',u'/',u';',u' ',u'[',u']',u'$',u'%',u'^',u'&',u'*',u'(',u')',\n u'\"',u':',u'<',u'>',u'?',u'{',u'}',u'=',u'+',u'_',u'-',u'''''''']\n _lda.setStopWords(stop)\n _lda.loadCorpusFromFile(u'../input/BBC_news.txt')\n _lda.fitModel(n_iter=1500)\n _lda.printTopic_Word(n_top_word=10)\n _lda.printDoc_Topic()\n _lda.saveVocabulary(u'../output/vocab.txt')\n _lda.saveTopic_Words(u'../output/topic_word.txt')\n _lda.saveDoc_Topic(u'../output/doc_topic.txt')","sub_path":"LearnIR/LDA1.py","file_name":"LDA1.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"503853139","text":"# -*- coding: utf-8 -*-\nfrom lxml import etree\nfrom ..items import YoutubedetailItem\nfrom scrapy_redis.spiders import RedisSpider\nfrom razerdateresolution import parse_date_str\nimport datetime\n\nclass YoutubedetailSpider(RedisSpider):\n name = 'youtubedetail'\n allowed_domains = ['youtube.com']\n\n def parse(self, response):\n if response.status == 200:\n html = etree.HTML(response.body)\n try:\n items = html.xpath(\n '//ytd-comments[@id=\"comments\"]/ytd-item-section-renderer[@id=\"sections\"]/div[@id=\"contents\"]')\n for item in items:\n ites = item.xpath('.//ytd-comment-thread-renderer')\n for ite in ites:\n try:\n youtubeItem = YoutubedetailItem()\n strdate = ''.join(\n ite.xpath('.//*[@id=\"header-author\"]/yt-formatted-string/a/text()')).strip()\n youtubeItem['DateofComplaint'], youtubeItem['ID'] = parse_date_str(strdate)\n youtubeItem['FromUser'] = ''.join(ite.xpath('.//*[@id=\"author-text\"]/span/text()')).strip()\n youtubeItem['Source'] = response.url\n youtubeItem['CustomerFeedback'] = ''.join(\n ite.xpath('.//*[@id=\"content-text\"]/text()')).strip()\n youtubeItem['Remarks'] = ''\n youtubeItem['Source'] = response.url\n youtubeItem['DateofAdd'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n yield youtubeItem\n except:\n continue\n except:\n return {}\n","sub_path":"Youtube/YoutubeDetail/YoutubeDetail/spiders/youtubedetail.py","file_name":"youtubedetail.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"43991519","text":"from django.urls import path\nfrom .views import home, add_todo, edit_todo, delete_todo\n\napp_name = 'Todo'\n\nurlpatterns = [\n path('', home, name='home'),\n path('add_todo/', add_todo, name=\"add_todo\"),\n path('edit_todo//', edit_todo, name=\"edit_todo\"),\n path('delete_todo//', delete_todo),\n\n]\n","sub_path":"Todo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"379264531","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/python3\n\n# импортируйте необходимые пакеты\nimport cv2,sys\n\nfrom PyQt5.QtWidgets import QMainWindow, QAction, qApp, QApplication\n\ndef find_books(path):\n# загрузите изображение, смените цвет на оттенки серого и уменьшите резкость\n\timage = cv2.imread(path)\n\tgray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\tgray = cv2.GaussianBlur(gray, (3, 3), 0)\n\tcv2.imwrite(\"gray.jpg\", gray)\n\n\t# распознавание контуров\n\tedged = cv2.Canny(gray, 10, 250)\n\tcv2.imwrite(\"edged.jpg\", edged)\n\n\n\t# создайте и примените закрытие\n\tkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 7))\n\tclosed = cv2.morphologyEx(edged, cv2.MORPH_CLOSE, kernel)\n\tcv2.imwrite(\"closed.jpg\", closed)\n\n\t# найдите контуры в изображении и подсчитайте количество книг\n\tcnts = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]\n\ttotal = 0\n\n\t# цикл по контурам\n\tfor c in cnts:\n\t\t# аппроксимируем (сглаживаем) контур\n\t\tperi = cv2.arcLength(c, True)\n\t\tapprox = cv2.approxPolyDP(c, 0.02 * peri, True)\n\n\t\t# если у контура 4 вершины, предполагаем, что это книга\n\t\tif len(approx) == 4:\n\t\t\tcv2.drawContours(image, [approx], -1, (0, 255, 0), 4)\n\t\t\ttotal += 1\n\n\t#\n\n\tcv2.imwrite(\"output.jpg\", image)\n\n\treturn total\n\nclass MyWin(QMainWindow):\n\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n\n def initUI(self):\n\n exitAction = QAction('&Выход', self)\n exitAction.setShortcut('Ctrl+Q')\n exitAction.setStatusTip('Выход из программы')\n exitAction.triggered.connect(qApp.quit)\n\n openAction = QAction('&Открыть...',self)\n openAction.setShortcut('Ctrl+O')\n openAction.setStatusTip('Открывает графический файл')\n openAction.triggered.connect(self.on_openFile)\n\n self.statusBar()\n\n menubar = self.menuBar()\n fileMenu = menubar.addMenu('&File')\n fileMenu.addAction(openAction)\n fileMenu.addAction(exitAction)\n\n self.setGeometry(300, 300, 300, 200)\n self.setWindowTitle('Ищем книгу на картинке')\n self.show()\n \n def on_openFile(self):\n \treturn \n\t\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n ex = MyWin()\n sys.exit(app.exec_())\n\n\n","sub_path":"find-books/src/qt_findbooks.py","file_name":"qt_findbooks.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"94968144","text":"from keras.layers.core import Dense, Flatten\nfrom keras.layers import Input, merge\nfrom keras.models import Model\nfrom keras.layers.embeddings import Embedding\nimport load_data\n\ndef noise_model(gen_train):\n \n input = Input(shape=(1,), dtype='int32')\n ne = gen_train.get_layer('noise_embeddings')\n shape = ne.trainable_weights[0].shape.eval()\n emb = Embedding(shape[0], shape[1], input_length = 1, name='noise_embeddings',\n trainable = False, weights=[ne.get_weights()[0]])(input) \n flt = Flatten()(emb)\n dense1 = Dense(shape[-1], activation = 'tanh')(flt)\n dense = Dense(3, activation='softmax')(dense1)\n \n model = Model(input=[input], output=dense)\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model \n\ndef generator(train, batch_size, split, trainable):\n size = split if trainable else len(train[0]) - split\n while True:\n mb = load_data.get_minibatches_idx(size, batch_size, shuffle=trainable)\n for _, train_index in mb:\n if not train:\n train_index += split\n \n yield [train_index], train[2][train_index]\n\ndef train(model, train):\n split = int(len(train[0]) * 0.95)\n tgen = generator(train, 64, split, True)\n dgen = generator(train, 64, split, False)\n model.fit_generator(tgen, 25600, 20, validation_data = dgen, \n nb_val_samples = len(train[0]) - split)\n \n \n\n\ndef noise_test(gen_train):\n\n ne = gen_train.get_layer('noise_embeddings')\n shape = ne.trainable_weights[0].shape.eval()\n\n noise_input = Input(shape=(shape[-1],))\n class_input = Input(shape=(3,))\n dense1 = Dense(shape[-1], activation = 'tanh')(merge([noise_input, class_input], mode = 'concat'))\n dense = Dense(1, activation='sigmoid')(dense1)\n\n model = Model(input=[noise_input, class_input], output=dense)\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n","sub_path":"noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"77759745","text":"# Return the prime numbers between 2 and 'to'\n#\n# \n#\n#\ndef prime_generator(prime, to):\n for i in xrange(2,to):\n count = 2\n for j in range(2,i):\n if (i%j) == 0 and i != 2:\n count+=1\n if count > 2:\n prime.remove(i)\n break\n","sub_path":"sirc_v2/prime_generator.py","file_name":"prime_generator.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216212853","text":"# -*- encoding=utf8 -*-\n\"\"\"\ntime:2021/4/2\nweblink : https://portal.deepmotion.com\n\n功能:\n视频上传及处理后下载,\n\"\"\"\n\nimport os\nimport time\nimport shutil\nimport pywinauto\nfrom selenium import webdriver\nfrom pywinauto.keyboard import send_keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\nclass upload(object):\n\n # 视频地址\n path = r'C:\\Users\\v_fxfxfang\\Desktop\\deepmotion\\1'\n # 账号地址\n account_path = r'C:\\Users\\v_fxfxfang\\Desktop\\account.txt'\n # 视频下载完后会移动该文件夹中\n end_path = r'C:\\Users\\v_fxfxfang\\Desktop\\success'\n # 密码\n password = 'F1a1n0g0'\n\n\n\n def __init__(self):\n ##设置接管理管Chrome浏览器\n chrome_options = Options()\n chrome_options.add_experimental_option(\"debuggerAddress\", \"127.0.0.1:9222\")\n # chromdriver = r'D:\\Python\\Python38\\Scripts\\chromedriver.exe'\n self.driver = webdriver.Chrome(options=chrome_options)\n self.wait = WebDriverWait(self.driver, 100)\n\n\n # 执行上传\n def uploadbtn(self):\n\n print(self.driver.title) #标题\n\n # 视频名字\n video_list = []\n\n\n #遍历账号\n for account in open(self.account_path, 'r', encoding='utf-8'):\n\n # 遍历视频\n videos = os.listdir(self.path)\n for video in videos:\n if '.mp4' in video:\n video_list.append(video)\n\n #登入\n self.sigin_in(account)\n\n print('已经登入%s....' % account)\n time.sleep(10)\n #上传视频,一个账号上传5次\n for a in range(4):\n # 上传视频\n self.up_process(video_list[a])\n # 移动视频\n self.move_file(video_list[a])\n print('%s视频移动完毕' % video_list[a])\n\n #上传完了清空视频名字\n video_list.clear()\n #退出\n self.out_info()\n\n\n #上传过程\n def up_process(self,video_name):\n #关闭下载界面\n try:\n #home\n self.driver.find_element(By.XPATH,'//*[@id=\"anim-fadein\"]/ul[1]/li[1]/a[text()=\"{}\"]'.format('Home')).click()\n except:\n self.driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[3]/div[1]/div/aside/div[2]/ul/li[1]/a').click()\n time.sleep(1.5)\n\n # Create Animation\n self.wait.until(EC.presence_of_element_located((By.XPATH,'//div[@class=\"tile is-ancestor\"]')))\n try:\n self.driver.find_element_by_xpath('//*[@id=\"app\"]/div/div[3]/div[2]/div[3]/div[2]/div/div/div/div[1]/article[1]').click()\n except:\n ...\n # time.sleep(2)\n #Default\n self.wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class=\"column mgTop-0\"]')))\n self.driver.find_element_by_xpath('//div[@class=\"column mgTop-0 anim-fadein\"]/div[3]//div[@class=\"columns is-centered\"]/div[1]').click()\n time.sleep(2)\n #Select File上传\n self.driver.find_element_by_xpath('//p[@class=\"control\"]/button').click()\n\n self.up_video(video_name)\n\n # self.wait.until(EC.presence_of_element_located((By.XPATH,'//div[@class=\"column bShadow\"]//div[@class=\"columns rounded-corners-bottom dm-brand\"]/div[2]')))\n time.sleep(2)\n #Create Animations\n self.driver.find_element_by_xpath('//div[@class=\"column bShadow\"]//div[@class=\"columns rounded-corners-bottom dm-brand\"]/div[2]').click()\n\n ##等待上传后下载\n time.sleep(125)\n self.wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class=\"column no-bottom-margin\"]')))\n try:\n self.driver.find_element(By.XPATH,'//*[@id=\"app\"]/div/div[3]/div[2]/div[4]/div/button/span[text()=\"{}\"]'.format('Download Animations')).click()\n except:\n time.sleep(10)\n self.driver.find_element_by_xpath('//div[@class=\"column\"]//button[@class=\"button download-btn is-large\"]').click()\n time.sleep(3)\n #点击下载FBX文件\n self.driver.find_element_by_xpath('//div[@class=\"columns has-text-left mgTop-0\"]//div[@class=\"columns\"]/div[2]/div/div[2]//span[@class=\"no-side-margins\"]').click()\n time.sleep(3)\n\n try:\n self.driver.find_element_by_xpath('//div[@id=\"app\"]/div/div[3]//button[@aria-label=\"close\"]').click()\n except:\n ...\n\n #上传文件\n def up_video(self,file):\n\n app = pywinauto.Desktop()\n # 选择文件上传的窗口\n dlg = app[\"打开\"]\n\n # 选择文件地址输入框,点击激活\n dlg[\"Toolbar3\"].click()\n # 键盘输入上传文件的路径\n\n # send_keys(r\"D:\\video\")\n # 键盘输入回车,打开该路径\n\n send_keys(\"{VK_RETURN}\")\n\n # 选中文件名输入框,输入文件名\n # dlg[\"文件名(&N):Edit\"].type_keys(\"12.mp4\")\n dlg[\"文件名(&N):Edit\"].type_keys(file)\n # 点击打开\n try:\n for i in range(1, 11):\n dlg[\"打开(&O)\"].click()\n except:\n ...\n\n\n\n\n\n #登入\n def sigin_in(self,account):\n self.driver.find_element_by_xpath('//span[@data-se=\"o-form-input-username\"]/input').clear()\n\n self.driver.find_element_by_xpath('//span[@data-se=\"o-form-input-username\"]/input').send_keys(account)\n time.sleep(1)\n\n self.driver.find_element_by_xpath('//*[@id=\"okta-signin-password\"]').send_keys('F1a1n0g0')\n time.sleep(1)\n # self.driver.find_element_by_xpath('//*[@id=\"input7\"]').click()\n time.sleep(1)\n self.driver.find_element_by_xpath('//*[@id=\"okta-signin-submit\"]').click()\n\n\n\n #退出\n def out_info(self):\n # self.wait.until(EC.presence_of_element_located((By.CLASS_NAME,\"fas fa-user-circle fa-2x\")))\n\n self.driver.find_element_by_xpath('//div[@class=\"dropdown-trigger\"]//i').click()\n time.sleep(2)\n try:\n self.driver.find_element(By.XPATH,'//*[@id=\"logout\"]/h4[text()=\"{}\"]'.format('Sign out')).click()\n except:\n time.sleep(2)\n self.driver.find_element(By.XPATH,'//*[@id=\"logout\"]/h4[text()=\"{}\"]'.format('Sign out')).click()\n time.sleep(2)\n self.driver.find_element_by_xpath('//div[@class=\"columns has-text-left mgTop-0\"]//div[@class=\"columns\"]/button[2]').click()\n\n #移动\n def move_file(self,video):\n start_path = os.path.join(self.path,video)\n shutil.move(start_path,self.end_path)\n\n\n\n\nif __name__ == '__main__':\n pq = upload()\n\n pq.uploadbtn()\n\n","sub_path":"3D.py","file_name":"3D.py","file_ext":"py","file_size_in_byte":6766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"103190578","text":"from django.contrib import admin\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n\nfrom accounts.models import Account, AccountTeam, AccountTier, AccountUser\nfrom accounts.tasks import set_image_from_socialaccounts\n\n\n@admin.register(Account)\nclass AccountAdmin(admin.ModelAdmin):\n \"\"\"Admin interface for accounts.\"\"\"\n\n list_display = [\"name\", \"creator\", \"created\", \"is_personal\", \"tier\"]\n list_select_related = [\"creator\"]\n list_filter = [\"tier\"]\n search_fields = [\"name\"]\n actions = [\"set_image_from_socialaccounts\", \"downgrade_to_tier1\"]\n\n def is_personal(self, instance):\n \"\"\"Field to display `is_personal` as a boolean.\"\"\"\n return instance.is_personal\n\n is_personal.boolean = True # type: ignore\n is_personal.short_description = \"Personal\" # type: ignore\n\n @admin.action(description=\"Set image from social accounts\")\n def set_image_from_socialaccounts(self, request, queryset):\n \"\"\"Set image from social accounts.\"\"\"\n for account in queryset:\n set_image_from_socialaccounts.delay(account.id)\n\n @admin.action(description=\"Downgrade to Tier 1\")\n def downgrade_to_tier1(self, request, queryset):\n \"\"\"\n Downgrades the selected accounts to Tier 1 (Free).\n\n Uses a confirmation page to make sure the\n staff member wants to do that!.\n \"\"\"\n if \"apply\" in request.POST:\n # Downgrades to tier 1\n queryset.update(tier_id=1)\n\n # Redirect to admin view with message\n self.message_user(\n request, \"Downgraded {} accounts to tier 1\".format(queryset.count())\n )\n return HttpResponseRedirect(request.get_full_path())\n\n return render(\n request,\n \"accounts/admin/accounts_downgrade_confirm.html\",\n context={\"accounts\": queryset},\n )\n\n\n@admin.register(AccountUser)\nclass AccountUserAdmin(admin.ModelAdmin):\n \"\"\"Admin interface for account users.\"\"\"\n\n list_display = [\"account\", \"user\", \"role\"]\n list_filter = [\"account\", \"user\", \"role\"]\n search_fields = [\"account__name\", \"user__username\"]\n\n\n@admin.register(AccountTeam)\nclass AccountTeamAdmin(admin.ModelAdmin):\n \"\"\"Admin interface for account teams.\"\"\"\n\n list_display = [\"account\", \"name\"]\n list_filter = [\"account\"]\n search_fields = [\"account__name\", \"name\"]\n\n\n@admin.register(AccountTier)\nclass AccountTierAdmin(admin.ModelAdmin):\n \"\"\"Admin interface for account tiers.\"\"\"\n\n list_display = [\n \"id\",\n \"name\",\n \"product\",\n \"active\",\n \"account_users\",\n \"account_teams\",\n \"projects_public\",\n \"projects_private\",\n \"file_downloads_month\",\n \"job_runtime_month\",\n \"dois_created_month\",\n ]\n","sub_path":"manager/accounts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"13505378","text":"'''\n MapReduce job to identify the most lucrative type of scam,\n track how this changes with time and whether this correlates with\n scams going offline\n\n Author: Harvey Randall\n Date: 1/12/19\n'''\nfrom mrjob.job import MRJob\nfrom mrjob.step import MRStep\nimport json, traceback\n\nclass Scams(MRJob):\n\n def mapper_init_sub(self):\n self.scams = dict()\n with open('scams.json') as f:\n scams_json = json.load(f)\n for k, v in scams_json['result'].items():\n if v.get('subcategory'):\n self.scams[k] = v['subcategory'].lower()\n\n def mapper_sub(self, _, line):\n try:\n fields = line.split(',')\n scam_address = fields[2]\n amount = int(fields[3])\n if scam_address in self.scams:\n yield (self.scams.get(scam_address), amount)\n except:\n #print(traceback.format_exc())\n pass\n\n def combiner_sub(self, key, val):\n yield (key, sum(val))\n\n def reducer_sub(self, key, val):\n yield (None, (key, sum(val)))\n\n def reducer_order(self, _, subcategories):\n sorted_vals = sorted(subcategories, key=lambda x: x[1], reverse=True)\n for val in sorted_vals:\n yield (val[0], val[1])\n\n def steps(self):\n return [MRStep(mapper_init=self.mapper_init_sub,\n mapper=self.mapper_sub,\n combiner=self.combiner_sub,\n reducer=self.reducer_sub),\n MRStep(reducer=self.reducer_order)]\n\nif __name__ == \"__main__\":\n Scams.run()","sub_path":"Coursework/Submission/Scam_Analysis/mrscams_subcategory.py","file_name":"mrscams_subcategory.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"308410671","text":"import import_files as MrtRecommendationDependencies\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import Normalizer\nimport pickle5 as pickle\n\nclass TrainOperationsModel:\n\n def __init__(self,field='num_train_running',build_from_scratch=False):\n self._field = field\n if build_from_scratch or not MrtRecommendationDependencies.model_exists(f\"{field}_model.sav\"):\n self.init_training_data()\n self.init_model()\n self.train_model()\n else:\n self._model = pickle.load(open(MrtRecommendationDependencies.get_model_path(f\"{self._field}_model.sav\"), \"rb\"))\n\n def dump_model(self):\n pickle.dump(self._model, open(MrtRecommendationDependencies.get_model_path(f\"{self._field}_model.sav\"), \"wb\"))\n\n def init_training_data(self):\n\n self._train_df = pd.read_csv(MrtRecommendationDependencies.get_dataset_path(\"train_updates_with_ridership.csv\"))\n self._train_x = self.prep_data(self._train_df)\n self._train_y = self._train_df[self._field]\n\n def init_model(self):\n estimator_count = {\n 'num_train_running':52,\n 'headway':59\n }\n self._model = Pipeline([('scaler', Normalizer()),('regressor', RandomForestRegressor(n_estimators=estimator_count[self._field],random_state=35))])\n\n def train_model(self):\n self._model.fit(self._train_x, self._train_y)\n\n def prep_data(self,data,training=True):\n fields_to_drop = []\n if training:\n fields_to_drop = ['num_dalian_train_running', 'num_dalian_train_operational', 'headway']\n if self._field == \"num_train_running\":\n fields_to_drop.append('num_train_operational')\n fields_to_drop.append('num_train_running')\n else:\n fields_to_drop.append('weather_main')\n fields_to_drop.append('datetime')\n\n return data.drop(fields_to_drop, axis=1)\n\n def predict(self,df):\n return self._model.predict(self.prep_data(df,False))\n","sub_path":"ml_model/train_operations_model.py","file_name":"train_operations_model.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"442832415","text":"import tests\n\n\nclass TestApp(tests.AgileTest):\n config_file = 'tests/configs/python.json'\n\n async def test_task(self):\n agile = await self.executor()\n self.assertTrue(agile.context)\n self.assertFalse(agile.cfg.push)\n self.assertEqual(agile.eval('cfg.push'), False)\n","sub_path":"tests/test_executor.py","file_name":"test_executor.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"219900053","text":"\"\"\"\nGiven a non-empty array of integers, every element \nappears twice except for one. Find that single one.\n\nNote:\n\nYour algorithm should have a linear runtime complexity. \nCould you implement it without using extra memory?\n\nExample 1:\n\nInput: [2,2,1]\nOutput: 1\nExample 2:\n\nInput: [4,1,2,1,2]\nOutput: 4\n\"\"\"\ndef single_number(nums):\n num_count = {}\n for num in nums:\n num_count[num] = num_count.get(num, 0) + 1\n\n for pair in num_count.items():\n if pair[1] == 1:\n return pair[0]\n\n ","sub_path":"single_number.py","file_name":"single_number.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41258916","text":"import os\nimport sys\nsys.path.append(os.getcwd())\nimport data_preprocess.assemble as assemble\npathdirect=os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nrnet_postive_file = pathdirect+'/anno_store/pos_24.txt'\nrnet_part_file = pathdirect+'/anno_store/part_24.txt'\nrnet_neg_file = pathdirect+'/anno_store/neg_24.txt'\nrnet_landmark_file = pathdirect+'/anno_store/landmark_24.txt'\nimglist_filename = pathdirect+'/anno_store/imglist_anno_24.txt'\n\nif __name__ == '__main__':\n\n anno_list = []\n\n anno_list.append(rnet_postive_file)\n anno_list.append(rnet_part_file)\n anno_list.append(rnet_neg_file)\n # anno_list.append(pnet_landmark_file)\n\n chose_count = assemble.assemble_data(imglist_filename ,anno_list)\n print(\"PNet train annotation result file path:%s\" % imglist_filename)\n","sub_path":"data_preprocess/assemble_rnet_imglist.py","file_name":"assemble_rnet_imglist.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"214057334","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\ndef save(audio_file_type, feature_type, channels, config_path,\n sampling_rate=16000, window=0.025, slide=0.01,\n energy=True, delta=True, deltadelta=True):\n \"\"\"Save a configuration file for HTK.\n Args:\n audio_file_type (string): nist or wav\n feature_type (string): the type of features, logmelfbank or mfcc\n channels (int): the number of frequency channels\n config_path (string): path to save the config file\n sampling_rate (float, optional):\n window (float, optional): window width to extract features\n slide (float, optional): extract features per 'slide'\n energy (bool, optional): if True, add the energy feature\n delta (bool, optional): if True, delta features are also extracted\n deltadelta (bool, optional): if True, double delta features are also extracted\n\"\"\"\n with open(config_path, 'w') as f:\n if audio_file_type not in ['nist', 'wav']:\n raise ValueError('audio_file_type must be nist or wav.')\n f.write('SOURCEFORMAT = %s\\n' % audio_file_type.upper())\n\n # Sampling rate\n if sampling_rate == 16000:\n f.write('SOURCERATE = 625\\n')\n elif sampling_rate == 8000:\n f.write('SOURCERATE = 1250\\n')\n\n # Target features\n if feature_type == 'logmelfbank':\n feature_type = 'FBANK'\n elif feature_type == 'mfcc':\n feature_type = 'MFCC'\n # elif feature_type == 'linearmelfbank':\n # feature_type = 'MELSPEC'\n else:\n raise ValueError('feature_type must be logmelfbank or mfcc.')\n\n if energy:\n feature_type += '_E'\n if delta:\n feature_type += '_D'\n if deltadelta:\n feature_type += '_A'\n f.write('TARGETKIND = %s\\n' % feature_type)\n\n # f.write('DELTAWINDOW = 2')\n # f.write('ACCWINDOW = 2')\n\n # Extract features per slide\n f.write('TARGETRATE = %.1f\\n' % (slide * 10000000))\n\n f.write('SAVECOMPRESSED = F\\n')\n f.write('SAVEWITHCRC = F\\n')\n\n # Window size\n f.write('WINDOWSIZE = %.1f\\n' % (window * 10000000))\n\n f.write('USEHAMMING = T\\n')\n f.write('PREEMCOEF = 0.97\\n')\n f.write('NUMCHANS = %d\\n' % channels)\n f.write('ENORMALISE = F\\n')\n f.write('ZMEANSOURCE = T\\n')\n","sub_path":"utils/inputs/htk.py","file_name":"htk.py","file_ext":"py","file_size_in_byte":2402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535290009","text":"import socket\nimport selectors\n\ndef getIP():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect((\"8.8.8.8\", 80))\n ip = str(s.getsockname()[0])\n s.close()\n return ip\nprint(getIP())","sub_path":"back/ex.py","file_name":"ex.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"563478325","text":"from iLAB_US_Framework.Global import Global_Variables\r\nfrom iLAB_US_Framework.Global import Objects\r\nfrom iLAB_US_Framework.iLAB_Selenium import Browser_Management\r\nfrom iLAB_US_Framework.iLAB_Selenium import Login\r\nfrom iLAB_US_Framework.iLAB_Selenium.Locator import Locators\r\nfrom iLAB_US_Framework.iLAB_Selenium import Wait_Until\r\nfrom iLAB_US_Framework.iLAB_Selenium.Login import Login_Class\r\nimport time\r\nimport unittest\r\nimport allure\r\nimport allure_commons\r\nimport pytest\r\nimport pandas as pd\r\nfrom pandas import DataFrame\r\nimport random\r\n\r\n\r\n\r\n'''\r\nCreated by Chris Dewing\r\n\r\nLast Edited: 6/26/19\r\n\r\nVersion 4.1:\r\n-Added additional Allure Decorators.\r\n-Six new test cases were added to test the failed, skipped, and blocking features of the Allure Report.\r\n-Spelling was checked.\r\n-Pandas was implemented to pull data from Excel sheet for user login. \r\n\r\nDetails:\r\nThe program runs through various actions that can be performed on the iLINK Dev website. In addition, \r\nthe program will output an Allure report that details what tests were performed and the results of those tests.\r\n\r\nNote that when using unittest, the methods have to be in numerical or alphabetic order.\r\nIf they are not in numerical or alphabetic order, the methods will run out of order in the class. This is why each\r\nmethod in the class starts off as test_'letter'...\r\n'''\r\n\r\n\r\n#@allure.story('[Conversation] - Automate the Signin screen across all three apps')\r\n#@allure.feature('Web App SigninPage Tests')\r\n\r\n#There are 9 functions in this class that test different actions of iLINK Dev\r\nclass MainTest(unittest.TestCase):\r\n\r\n #This function logs the user into iLINK Dev\r\n\r\n\r\n @allure.testcase(\"Test1\")\r\n @allure.description(\"This function logs the user into iLINK Dev\")\r\n @allure.title(\"Login\")\r\n @allure.severity(\"Blocker\")\r\n @allure.feature(\"Login Test Case\")\r\n @allure.story(\"Test Story For Test Case\")\r\n @allure.epic(\"Login Test\")\r\n @allure.tag(\"Main Login\")\r\n @allure.label(\"Main Login\")\r\n @allure.testcase(\"Validate Login\")\r\n @allure.step(\"Login to iLINK Dev using username and password\")\r\n def test_a_login(self):\r\n data = pd.read_excel(r'C:\\Users\\chris.dewing\\PycharmProjects\\iLINKDEVTesting2\\Data\\username_password.xlsx')\r\n username = data.at[0, \"Username\"]\r\n password = data.at[0, \"Password\"]\r\n Browser_Management.open_browser(\"gc\", \"http://ilinkdev.ilabquality.com/\")\r\n Login = Login_Class(Global_Variables.global_Driver)\r\n Login.input_username(\"xpath\", '//*[@id=\"user\"]', username)\r\n Login.input_password(\"xpath\", '//*[@id=\"pass\"]', password)\r\n Login.click_login_button(\"xpath\", '//*[@id=\"wp-submit\"]')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n #This function clicks through each menu button option with a 2 second pause in between\r\n #The test then scrolls to the bottom of the page after clicking the Chat button\r\n @allure.testcase(\"Test2\")\r\n @allure.description(\"This function clicks through each menu button option with a 2 second pause in between \\n\"\r\n \" The test then scrolls to the bottom of the page after clicking the Chat button\")\r\n @allure.title(\"Menu Navigation\")\r\n @allure.severity(\"Trivial\")\r\n @allure.epic(\"Menu Navigation\")\r\n @allure.tag(\"Navigation\")\r\n @allure.label(\"Navigation\")\r\n @allure.step(\"Click through the Menu Buttons on the iLINK Dev website\")\r\n \r\n def test_b_menu_navigation(self):\r\n locator = Locators(Global_Variables.global_Driver)\r\n locator.click_element(\"linktext\", \"Global Events\")\r\n time.sleep(2)\r\n locator.click_element(\"linktext\", \"Groups\")\r\n time.sleep(2)\r\n locator.click_element(\"linktext\", \"Chat\")\r\n time.sleep(2)\r\n locator.scroll_to_bottom_of_page()\r\n time.sleep(2)\r\n locator.click_element(\"linktext\", \"Members\")\r\n time.sleep(2)\r\n locator.click_element(\"linktext\", \"Posts\")\r\n time.sleep(2)\r\n locator.click_element(\"linktext\", \"Wiki\")\r\n time.sleep(2)\r\n locator.click_element(\"linktext\", \"Dashboard\")\r\n time.sleep(2)\r\n\r\n #This function uses the iLINK Dev main search to search for iTEST.\r\n #The function then navigates through 9 pages of the iTEST method description.\r\n #Lastly, the function clicks the revision button, scrolls to the bottom of the page,and clicks on the Dashbaord page\r\n @allure.testcase(\"Test3\")\r\n @allure.severity(\"Minor\")\r\n \r\n @allure.description(\"This function uses the iLINK Dev main search to search for iTEST.\\n\"\r\n \" The function then navigates through 9 pages of the iTEST method description. \\n \"\r\n \"Lastly, the function clicks the revision button, scrolls to the bottom of the page,and \"\r\n \"clicks on the Dashbaord page\")\r\n @allure.title(\"Search For iTEST Description\")\r\n @allure.epic(\"Search Option\")\r\n @allure.tag(\"Search\")\r\n @allure.label(\"Search\")\r\n @allure.step(\"Search for iTEST and then click through 9 of the Read Me slides\")\r\n def test_c_search_itest(self):\r\n locator = Locators(Global_Variables.global_Driver)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/header/nav/div[2]/a[1]/i\")\r\n locator.send_text(\"id\", \"s\", \"iTEST\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/header/div[3]/div/form/button/i\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article[1]/div[2]/div[2]/a\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div[2]/div[1]/div/a[2]\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div[2]/div[1]/div/a[2]\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div[2]/div[1]/div/a[2]\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div[2]/div[1]/div/a[2]\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div[2]/div[1]/div/a[2]\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div[2]/div[1]/div/a[2]\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div[2]/div[1]/div/a[2]\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div[1]/div/ul/li[4]/a\")\r\n locator.scroll_to_bottom_of_page()\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/footer/div[1]/div/div/div[2]/div/ul/li[1]/a\")\r\n\r\n\r\n #This function searches for a member in iLINK and clicks through the menu options for that selected user.\r\n #The function then clicks on message button and sends a message to the same user that was searched for.\r\n #A Gmail email will then be sent to that user informing them that a message was sent via iLINK Dev.\r\n #The last test case in this class will open Gmail so the user can see if an email was received.\r\n @allure.testcase(\"Test4\")\r\n @allure.description(\"This function searches for a member in iLINK and clicks through the menu options for that\"\r\n \" selected user. \\n The function then clicks on message button and sends a message to the same\"\r\n \" user that was searched for. \\n A Gmail email will then be sent to that user informing them \"\r\n \"that a message was sent via iLINK Dev.\")\r\n @allure.title(\"Search for an iLAB Employee\")\r\n @allure.severity(\"Blocker\")\r\n @allure.epic(\"Employee Lookup\")\r\n @allure.tag(\"Text Entry\")\r\n @allure.label(\"Text Entry\")\r\n @allure.step(\"Search for an iLAB employee and send a message to that same employee \")\r\n def test_d_member_search(self):\r\n locator = Locators(Global_Variables.global_Driver)\r\n locator.click_element(\"linktext\", \"Members\")\r\n locator.send_text(\"id\", \"members_search\", \"Chris Dewing\")\r\n time.sleep(1)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/header/div[1]/form/button/i\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/article/div/form/div/div/ul/li/div\"\r\n \"[2]/div[1]/a/h3\")\r\n time.sleep(2)\r\n locator.click_element(\"id\", \"user-xprofile\")\r\n time.sleep(2)\r\n locator.click_element(\"id\", \"user-notifications\")\r\n time.sleep(2)\r\n locator.click_element(\"id\", \"user-messages\")\r\n time.sleep(2)\r\n locator.click_element(\"id\", \"user-groups\")\r\n time.sleep(2)\r\n locator.click_element(\"id\", \"user-activity\")\r\n time.sleep(3)\r\n locator.click_element(\"id\", \"user-messages\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\",\"/html/body/div[2]/section/div/div/div/article/div/div[1]/div[2]/div/div[2]\"\r\n \"/div[2]/a\")\r\n time.sleep(2)\r\n locator.send_text(\"xpath\", \"//*[@id='subject']\", \"Test Subject Line\")\r\n time.sleep(2)\r\n locator.send_text(\"xpath\", \"//*[@id='message_content']\", \"Test message line\")\r\n time.sleep(2)\r\n locator.click_element(\"id\", \"send\")\r\n\r\n\r\n #This function edits a selected users's profile by adding a new cell phone number\r\n @allure.testcase(\"Test5\")\r\n @allure.description(\"This function edits a selected users's profile by adding a new cell phone number\")\r\n @allure.title(\"Edit iLAB Employee Profile\")\r\n @allure.severity(\"Normal\")\r\n @allure.tag(\"Editing\")\r\n @allure.label(\"Editing\")\r\n @allure.epic(\"Edit Employee Profile\")\r\n @allure.step(\"Click the edit view of the employee profile and change the phone number to (555)555-5555\")\r\n def test_e_user_profile(self):\r\n locator = Locators(Global_Variables.global_Driver)\r\n locator.click_element(\"id\", \"user-thumb\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/header/div[1]/div[1]/div/nav/ul/li[2]/a\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/header/div[1]/div[1]/div/nav/ul/li[2]/ul/li[2]/a\")\r\n time.sleep(2)\r\n locator.send_text(\"xpath\", \"//*[@id='field_12']\", \"(555)-555-5555\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"//*[@id='profile-group-edit-submit']\")\r\n time.sleep(2)\r\n locator.click_element(\"linktext\", \"Dashboard\")\r\n \r\n #This function checks to see if the user has any notifications.\r\n @allure.testcase(\"Test6\")\r\n @allure.description(\"This function checks to see if the user has any notifications.\")\r\n @allure.title(\"Check Notifications\")\r\n @allure.severity(\"Normal\")\r\n @allure.epic(\"Icon Select\")\r\n @allure.tag(\"Navigation\")\r\n @allure.label(\"Navigation\")\r\n @allure.step(\"Click the bell icon and see if there are any notifications\")\r\n def test_f_menu_navigation2(self):\r\n locator = Locators(Global_Variables.global_Driver)\r\n locator.click_element(\"linktext\", \"Posts\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/div[1]/div[2]/div[1]/a/picture/img\")\r\n locator.scroll_to_bottom_of_page()\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/footer/div[1]/div/div/div[2]/div/ul/li[1]/a\")\r\n time.sleep(1)\r\n locator.click_element(\"id\", \"nav-notification-trigger\")\r\n time.sleep(2)\r\n locator.click_element(\"id\", \"nav-notification-trigger\")\r\n\r\n\r\n #This functions attempts to submit a survey and IT help desk request without filling out all information.\r\n #The system should highlight red indicating what fields need to still be filed out before submitting.\r\n @allure.testcase(\"Test7\")\r\n @allure.description(\"This functions attempts to submit a survey and IT help desk request without filling out all \"\r\n \"information.\\n The system should highlight red indicating what fields need to still be filed \"\r\n \"out before submitting.\")\r\n @allure.title(\"Submit Incomplete Survey and IT Help Desk Request\")\r\n @allure.severity(\"Normal\")\r\n @allure.epic(\"Form Submit\")\r\n @allure.tag(\"Submitting\")\r\n @allure.label(\"Submitting\")\r\n @allure.step(\"On the main page, fill out one line of the survey and IT support box, then click submit on both\")\r\n def test_g_submit_issue_error(self):\r\n locator = Locators(Global_Variables.global_Driver)\r\n time.sleep(1)\r\n locator.click_element(\"xpath\", \"//*[@id='fld_8949845_2']\")\r\n time.sleep(2)\r\n locator.send_text(\"xpath\", \"//*[@id='fld_185917_1']\", \"Test\")\r\n time.sleep(3)\r\n locator.click_element(\"xpath\", \"//*[@id='fld_7167496_1']\")\r\n time.sleep(2)\r\n locator.click_element(\"xpath\", \"/html/body/div[2]/section/div/div/div/div/div[7]/div/ul/li[5]/div[2]/div[1]/a\")\r\n locator.scroll_to_bottom_of_page()\r\n locator.scroll_to_element(\"linktext\", \"Dashboard\")\r\n locator.click_element(\"linktext\", \"Wiki\")\r\n locator.click_element(\"linktext\", \"Dashboard\")\r\n\r\n \r\n #This function opens up the Gmail account that the iLINK message was sent to\r\n #The inbox of that Gmail account should show that a message was received from iLINK DEV\r\n @allure.testcase(\"Test8\")\r\n @allure.description(\"This function opens up the Gmail account that the iLINK message was sent to \\n\"\r\n \" The inbox of that Gmail account should show that a message was received from iLINK DEV\")\r\n @allure.title(\"Open Gmail\")\r\n @allure.severity(\"Critical\")\r\n @allure.epic(\"Open Gmail\")\r\n @allure.tag(\"Verification\")\r\n @allure.label(\"Verification\")\r\n @allure.step(\"Open Gmail and verify that the email was received from iLINK \")\r\n def test_h_check_gmail(self):\r\n Browser_Management.open_browser(\"gc\", \"https://gmail.com\")\r\n Login = Login_Class(Global_Variables.global_Driver)\r\n Login.input_username(\"id\",\"identifierId\",\"chris.dewing@ilabquality.com\")\r\n Login.click_login_button(\"xpath\", \"/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div[1]\"\r\n \"/div/span/span\")\r\n Login.input_password(\"xpath\", \"//*[@id='password']/div[1]/div/div[1]/input\", \"The199329hill\")\r\n Login.click_login_button(\"xpath\", \"/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div\"\r\n \"[1]/div/span/span\")\r\n time.sleep(3)\r\n\r\n #This function will attempt to click the xpath of an element that doesn't exist on the homepage of Gmail\r\n @allure.testcase(\"Test9\")\r\n @allure.title(\"Fail Test Case\")\r\n @allure.severity(\"Trivial\")\r\n @allure.tag(\"Fail\")\r\n @allure.label(\"Fail\")\r\n @allure.epic(\"Fail Test One\")\r\n @allure.description(\"This function will attempt to click the xpath of an element that doesn't exist on the \"\r\n \"homepage of Gmail\")\r\n @allure.step(\"Test case will automatically fail\")\r\n def test_i_fail(self):\r\n locator = Locators(Global_Variables.global_Driver)\r\n locator.click_element(\"xpath\", \"/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div[1]\"\r\n \"/div/span/span\" )\r\n time.sleep(2)\r\n\r\n # This function will attempt to click the xpath of an element that doesn't exist on the homepage of Gmail\r\n @allure.testcase(\"Test10\")\r\n @allure.title(\"Fail Test Case Two\")\r\n @allure.severity(\"Trivial\")\r\n @allure.epic(\"Fail Test Two\")\r\n @allure.tag(\"Fail\")\r\n @allure.label(\"Fail\")\r\n @allure.description(\"This function will attempt to click the xpath of an element that doesn't exist on the \"\r\n \"homepage of Gmail\")\r\n @allure.step(\"Test case will automatically fail\")\r\n def test_j_fail(self):\r\n locator = Locators(Global_Variables.global_Driver)\r\n locator.click_element(\"xpath\", \"/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[2]/div/div[2]\"\r\n \"/div/span/span\" )\r\n\r\n @allure.testcase(\"Skip Test Case 1\")\r\n @allure.title(\"Skip Test Case 1\")\r\n @allure.severity(\"Blocker\")\r\n @allure.description(\"Intentional Skip\")\r\n @allure.label(\"Skip\")\r\n @allure.tag(\"Skip\")\r\n @allure.epic(\"Skip One\")\r\n @pytest.mark.skipif('2 + 2 != 5', reason='This test is skipped by a triggered condition in @pytest.mark.skipif')\r\n def test_k_skip_by_triggered_condition(self):\r\n pass\r\n\r\n @allure.severity(\"Critical\")\r\n @allure.title(\"Skip Test Case 2\")\r\n @allure.testcase(\"Skip Test Case 2\")\r\n @allure.label(\"Skip\")\r\n @allure.epic(\"Skip Two\")\r\n @allure.tag(\"Skip\")\r\n @allure.description(\"Intentional Skip\")\r\n @pytest.mark.skipif('2 + 2 != 5', reason='This test is skipped by a triggered condition in @pytest.mark.skipif')\r\n def test_l_skip_by_triggered_condition2(self):\r\n pass\r\n\r\n @pytest.mark.skipif('2 + 2 != 5', reason='This test is skipped by a triggered condition in @pytest.mark.skipif')\r\n def test_m_skip_by_triggered_condition2(self):\r\n pass\r\n\r\n @allure.testcase(\"Minor\")\r\n @allure.title(\"Skip Test Case 3\")\r\n @allure.testcase(\"Skip Test Case 3\")\r\n @allure.label(\"Skip\")\r\n @allure.tag(\"Skip\")\r\n @allure.epic(\"Skip Three\")\r\n @allure.description(\"Intentional Skip\")\r\n @pytest.mark.skipif('2 + 2 != 5', reason='This test is skipped by a triggered condition in @pytest.mark.skipif')\r\n def test_n_kip_by_triggered_condition3(self):\r\n pass\r\n\r\n @allure.testcase(\"Minor\")\r\n @allure.title(\"Broken Test Case One\")\r\n @allure.testcase(\"Broken Test Case One\")\r\n @allure.label(\"Broken\")\r\n @allure.tag(\"Broken\")\r\n @allure.epic(\"Broken One\")\r\n @allure.description(\"Intentional Break\")\r\n @pytest.mark.skipif(\"Unknown\")\r\n def test_o_broken(self):\r\n print(\"test\")\r\n\r\n @allure.testcase(\"Minor\")\r\n @allure.title(\"Broken Test Case Two\")\r\n @allure.testcase(\"Broken Test Case Two\")\r\n @allure.label(\"Broken\")\r\n @allure.tag(\"Broken\")\r\n @allure.epic(\"Broken One\")\r\n @allure.description(\"Intentional Break\")\r\n @pytest.mark.skipif(\"Unknown\")\r\n def test_p_number(self):\r\n print(\"test\")\r\n\r\n\r\n if __name__ == '__main__':\r\n unittest.main(verbosity=2)\r\n","sub_path":"Tests/iLinkDevTesting.py","file_name":"iLinkDevTesting.py","file_ext":"py","file_size_in_byte":18558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"259509277","text":"'''\r\nDiffie-Hellman Key Exchange\r\nJakob Mckinney\r\n17/01/2019\r\n'''\r\nfrom alice import Alice\r\nfrom bob import Bob\r\nfrom primes import big_primes\r\nfrom math import gcd as bltin_gcd\r\nimport time\r\n\r\ndef egcd(a, b):\r\n '''\r\n Uses euclidean algorithm to recursively calculate \r\n gcd of a and b\r\n '''\r\n if a == 0:\r\n return (b, 0, 1)\r\n else:\r\n g, y, x = egcd(b % a, a)\r\n return (g, x - (b // a) * y, y) #g is the gcd\r\n\r\n\r\ndef get_public_keys_egcd():\r\n '''\r\n Calculates p and n which are the public keys used\r\n p and n must be relativley prime for it to work securely\r\n p is almost always 2 and n is a randomly generated large\r\n prime, they are then put through the euclidean algorithm\r\n to see if they are relativley prime.\r\n '''\r\n are_coprime = False\r\n \r\n while not are_coprime:\r\n p = 2\r\n n = big_primes()\r\n \r\n a, _, _ = egcd(p, n) # a is the gcd(p, n)\r\n \r\n # Checks if p and n are co-prime\r\n if a == 1:\r\n are_coprime = True\r\n else:\r\n p += 1 # If p and n aren't co-prime then p+1 and n will always be co-prime\r\n \r\n # p and n must be co-prime\r\n return p, n\r\n\r\n\r\ndef get_public_keys_bltin():\r\n '''\r\n Same as above but uses builtin gcd method instead of \r\n euclidean algorithm, bit more effecient\r\n '''\r\n p = 2\r\n while True:\r\n n = big_primes()\r\n \r\n gcd_pn = bltin_gcd(p, n)\r\n if gcd_pn == 1:\r\n return p, n\r\n else:\r\n p += 1\r\n \r\n\r\ndef main():\r\n '''\r\n Performs the Key Exchange between and instance of class Alice and \r\n an instance of class Bob, it prints the private keys, A and B, of\r\n Alice and Bob and also the shared Public key twice, once for the \r\n instance of Alice and once for the instance of Bob\r\n '''\r\n start1 = time.time()\r\n #g, p = get_public_keys_egcd()\r\n #end1 = time.time()\r\n #print(\"p: {}, n: {}, time taken: {}\".format(str(p1), str(n1), str(end1-start1)))\r\n \r\n #start = time.time()\r\n g, p = get_public_keys_bltin()\r\n #end = time.time()\r\n #print(\"g: {}, p: {}, time taken: {}\".format(str(g), str(p), str(end1-start1)))\r\n #print(\"p: {}, n: {}, time taken: {}\".format(str(g1), str(p1), str(end-start))) '''\r\n \r\n alice = Alice(g, p) #g, p\r\n bob = Bob(g, p)\r\n \r\n public_alice = alice.A\r\n public_bob = bob.B\r\n print(\"A = \" + str(public_alice))\r\n print(\"B = \" + str(public_bob))\r\n \r\n alice.B = public_bob\r\n bob.A = public_alice\r\n \r\n alice.calc_key()\r\n bob.calc_key()\r\n \r\n end = time.time()\r\n print(\"Time taken: {}\".format(end-start1))\r\n \r\n \r\n # Time taken with normal exponentiation: 0.001996278762817383 (8-bit number)\r\n # Time taken with pow() exponentiation: 0.003019094467163086 (256-bit number)\r\n # Time taken with pow() and more effecient prime test and get_public_keys_egcd(): 0.001024484634399414 (256-bit number)\r\n # Time taken with pow() and more effecient prime test and get_public_keys_bltin(): 0.0 (256-bit number) - negligible time i guess\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"public.py","file_name":"public.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"467769512","text":"\n#ZADATCI(riješite, dokumentirajte I zatim pročitajte docstring): \n#Kreirajte funkciju koja računa zbroj svih znamenaka nekog cijelog broja\ndef zbroj_znamenki(a):\n '''funkcija koja računa broj znamenaka cijelog broja'''\n L=list(str(a))\n b=0\n for i in L:\n b+=int(i)\n return b\nx=int(input('Upiši cijeli broj:'))\nprint(zbroj_znamenki(x))","sub_path":"vjezbe/1_zadatak.py","file_name":"1_zadatak.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"16168555","text":"from os.path import join\n\nfrom joblib import Parallel, delayed\nfrom sklearn.model_selection import ParameterGrid\n\nfrom cogspaces.datasets.utils import get_data_dir, get_output_dir\nfrom cogspaces.utils.sacred import get_id, OurFileStorageObserver\nfrom exps.train import exp\n\n\ndef factored():\n system = dict(\n device=-1,\n seed=0,\n verbose=50,\n )\n data = dict(\n source_dir=join(get_data_dir(), 'reduced_512'),\n studies='all'\n )\n\n model = dict(\n normalize=True,\n estimator='factored',\n study_weight='study',\n max_iter=500,\n )\n factored = dict(\n shared_embedding_size=100,\n batch_size=32,\n dropout=0.75,\n lr=1e-3,\n input_dropout=0.25,\n )\n\n\ndef run_exp(output_dir, config_updates, _id):\n \"\"\"Boiler plate function that has to be put in every multiple\n experiment script, as exp does not pickle.\"\"\"\n exp.run_command('print_config', config_updates=config_updates, )\n # run = exp._create_run(config_updates=config_updates, )\n # run._id = _id\n # observer = OurFileStorageObserver.create(basedir=output_dir)\n # run.observers.append(observer)\n # run()\n\n\nif __name__ == '__main__':\n output_dir = join(get_output_dir(), 'factored')\n exp.config(factored)\n config_updates = []\n config_updates += list(\n ParameterGrid({'data.studies': [['archi'],\n ['archi', 'hcp'],\n ['brainomics'],\n ['brainomics', 'hcp'],\n ['camcan'],\n ['camcan', 'hcp'],\n ['la5c'],\n ['la5c', 'hcp']],\n }))\n _id = get_id(output_dir)\n Parallel(n_jobs=1, verbose=100)(delayed(run_exp)(output_dir,\n config_update,\n _id=_id + i)\n for i, config_update\n in enumerate(config_updates))\n","sub_path":"exps/grids/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"99832715","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 31 15:39:22 2018\ncalcGamma and smart downlooking\n\nSaves fine_diff.int files in respective ifg directories used to make the gamma0 \nfile (they can be deleted after it is made)\n\nSaves a file called gamma0 in the tsdir (TS directory)\nSaves downlooked ifgs in the respective ifg directories.\n\n@author: kdm95\n\"\"\"\n\nimport numpy as np\nimport isceobj\nfrom matplotlib import pyplot as plt\nimport cv2\nimport os\n#from mroipac.filter.Filter import Filter\n\nparams = np.load('params.npy').item()\nlocals().update(params)\n\n\n# Make the gaussian filter we'll convolve with ifg\nskip = 3 # how many redundant pairs did you make?\nrx = 5\nry = 5\nrx2 = np.floor(rx*3)\nry2 = np.floor(ry*3)\ngausx = np.exp( np.divide( -np.square(np.arange(-rx2,rx2)), np.square(rx)));\ngausy = np.exp( np.divide( -np.square(np.arange(-ry2,ry2)), np.square(ry)));\ngaus = gausx[:, np.newaxis] * gausy[np.newaxis, :]\ngaus -= gaus.min()\ngaus /= np.sum(gaus.flatten())\n\n\nfor pair in params['pairs'][0:len(params['pairs']):skip]: \n if not os.path.isfile(params['intdir'] + '/' + pair + '/fine_diff.int'):\n print('working on ' + pair)\n #load ifg real and imaginary parts\n f = params['intdir'] +'/'+ pair + '/fine.int'\n intImage = isceobj.createIntImage()\n intImage.load(f + '.xml')\n ifg_real = np.real(intImage.memMap()[:,:,0] )\n ifg_imag = np.imag(intImage.memMap()[:,:,0] )\n ifg_real = ifg_real.copy() # mmap is readonly, so we need to copy it.\n ifg_imag = ifg_imag.copy()\n ifg_real[np.where(ifg_real==0)] = np.nan\n ifg_imag[np.where(ifg_real==0)] = np.nan\n# phs = np.angle(ifg_real+(1j*ifg_imag))\n phs = np.arctan2(ifg_imag, ifg_real).astype(np.float32)\n \n #filter real and imaginary parts \n ifg_real_filt = cv2.filter2D(ifg_real,-1, gaus)\n ifg_imag_filt = cv2.filter2D(ifg_imag,-1, gaus) \n# phs_filt = np.angle(ifg_real_filt+(1j*ifg_imag_filt))\n phs_filt = np.arctan2(ifg_imag_filt, ifg_real_filt).astype(np.float32)\n\n # Difference them \n cpx0 = ifg_real + 1j*ifg_imag\n cpxf = ifg_real_filt + 1j * ifg_imag_filt\n cpx0 /= abs(cpx0)\n cpxf /= abs(cpxf)\n phsdiff = np.multiply(cpx0, np.conj(cpxf))\n \n #save diff ifg\n out = intImage.clone() # Copy the interferogram image from before\n out.scheme = 'BIP' #'BIP'/ 'BIL' / 'BSQ' \n out.filename = params['intdir'] + '/' + pair + '/fine_diff.int'\n out.dump(params['intdir'] + '/' + pair + '/fine_diff.int.xml') # Write out xml\n phsdiff.tofile(params['intdir'] + '/' + pair+'/fine_diff.int') # Write file out\n\n\ndel(ifg_imag,ifg_imag_filt,ifg_real,ifg_real_filt,phs,cpx0,cpxf,phs_filt,phsdiff)\n\ngamma0 =list()\n# Make a stack of the diff images (memory mapped )\n# We have to do this in 20 subsections to save on memory\nchunks = np.linspace(0,params['ny'],20,dtype=int)\nfor ii in np.arange(0,len(chunks)-1):\n diff_stack = list()\n for pair in params['pairs'][0:len(params['pairs']):skip]: #loop through each ifg and save to \n diff_file = params['intdir'] + '/' + pair + '/fine_diff.int'\n diffImage = isceobj.createIntImage()\n diffImage.load(diff_file + '.xml')\n diff_stack.append(diffImage.memMap()[chunks[ii]:chunks[ii+1],:,0])\n # Find phase variance \n gamma0.append(np.abs( np.nansum( np.asarray(diff_stack), axis=0)/len(dates))) \n\na=np.empty((params['ny'],params['nx']))\nfor ii in np.arange(0,len(chunks)-1):\n a[chunks[ii]:chunks[ii+1]]=gamma0[ii]\ngamma0 = a\ngamma0 = np.asarray(gamma0)\ngamma0=np.reshape(np.asarray(gamma0),(params['ny'],params['nx']))\ngamma0[np.where(gamma0==0)]=np.nan\ngamma0=gamma0.astype(np.float32)\n\n\n# Save gamma0 file\nout = intImage.clone() # Copy the interferogram image from before\nout.dataType = 'FLOAT'\nout.filename = params['tsdir'] + '/gamma0.int'\nout.dump(params['tsdir'] + '/gamma0.int.xml') # Write out xml\ngamma0.tofile(out.filename) # Write file out\n\nplt.imshow(gamma0,vmin=0.1,vmax=.8)\nplt.figure()\nplt.hist( gamma0.flatten()[~np.isnan(gamma0.flatten())], 40, edgecolor='black', linewidth=.2)\nplt.title('Phase stability histogram')\nplt.xlabel('Phase stability (1 is good, 0 is bad)')\n\n\n","sub_path":"makeGamma0.py","file_name":"makeGamma0.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"599905635","text":"import NetworkManager\nfrom aiohttp import web\nimport dbus\nimport json\nimport subprocess\nimport time\nimport threading\nimport dbus.mainloop.glib\nfrom gi.repository import GObject\nimport asyncio\nfrom os import system\n\n\nHOTSPOT_TIME = 30\nGATEWAY = '192.168.42.1'\nDHCP_RANGE = '192.168.42.2,192.168.42.254'\nIFACE = 'wlan0'\nDNSMASQ = '/usr/sbin/dnsmasq'\nREDIR = True\n\nclass TestDaemon(threading.Thread):\n def run(self):\n self.__loop = GObject.MainLoop()\n self.__loop.run()\n\n def __init__(self):\n GObject.threads_init()\n dbus.mainloop.glib.threads_init()\n dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n\n threading.Thread.__init__(self)\n self.setDaemon(True)\n\n\nclass WifiConnector():\n\n def __init__(self):\n dbus.mainloop.glib.threads_init()\n dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n # NetworkManager.NetworkManager.OnPropertiesChanged(nmHandler)\n print('running main loop')\n self.daemon = TestDaemon()\n self.daemon.start()\n\n self._hotspotTimer = None\n self._hotspotActive = False\n NetworkManager.NetworkManager.OnStateChanged(self._onStateChanged)\n if NetworkManager.NetworkManager.State != NetworkManager.NM_STATE_CONNECTED_GLOBAL:\n self._startHotspotTimer()\n\n def scan(self):\n wireless = NetworkManager.NetworkManager.GetDeviceByIpIface(IFACE)\n # wireless.OnPropertiesChanged(nmHandler)\n # wireless.OnAccessPointAdded(nmHandler)\n print('scanning APs...')\n try:\n wireless.RequestScan({})\n except dbus.exceptions.DBusException as e:\n print('RequestScan failed', e)\n aps = wireless.AccessPoints\n access_points = []\n objects = []\n print('wireless.AccessPoints: {}'.format(len(aps)))\n i = 1\n for a in aps: \n try: \n print(\"{}. {}: {} {} {} {} flags={:#x} wpa={:#x} rsn={:#x}\"\n .format(i, a.Ssid, a.Frequency, a.HwAddress, a.Strength, a.Mode, a.Flags, a.WpaFlags, a.RsnFlags))\n if a.Flags & NetworkManager.NM_802_11_AP_FLAGS_PRIVACY \\\n and a.WpaFlags == NetworkManager.NM_802_11_AP_SEC_NONE \\\n and a.RsnFlags == NetworkManager.NM_802_11_AP_SEC_NONE:\n security = 'wep'\n elif a.WpaFlags & NetworkManager.NM_802_11_AP_SEC_KEY_MGMT_802_1X \\\n or a.WpaFlags & NetworkManager.NM_802_11_AP_SEC_KEY_MGMT_802_1X:\n security = 'enterprise'\n elif a.WpaFlags != NetworkManager.NM_802_11_AP_SEC_NONE or a.RsnFlags != NetworkManager.NM_802_11_AP_SEC_NONE:\n security = 'wpa'\n else:\n security = 'none'\n\n access_points.append({\n 'ssid': a.Ssid,\n 'strength': a.Strength,\n 'security': security,\n 'frequency': a.Frequency,\n 'hwaddress': a.HwAddress,\n 'mode': {\n NetworkManager.NM_802_11_MODE_INFRA: 'infra', \n NetworkManager.NM_802_11_MODE_ADHOC: 'adhoc',\n NetworkManager.NM_802_11_MODE_UNKNOWN: 'unknown'}[a.Mode]\n }) \n i += 1\n except NetworkManager.ObjectVanished: \n pass\n self.access_points = access_points\n return self.access_points\n\n def _startHotspotTimer(self):\n if self._hotspotActive:\n return\n\n print('*** STARTING HOTSPOT TIMER ***')\n if self._hotspotTimer: \n self._hotspotTimer.cancel()\n self._hotspotTimer = threading.Timer(HOTSPOT_TIME, self._hotspot)\n self._hotspotTimer.start() \n \n def _hotspot(self, b=True):\n if b == self._hotspotActive:\n return\n\n if b:\n print('*** ACTIVATING HOTSPOT ***')\n if self._hotspotTimer:\n self._hotspotTimer.cancel()\n self._hotspotTimer = None\n self._hotspotActive = True\n self._startHotspot()\n else:\n print('*** DEACTIVATING HOTSPOT ***')\n self._hotspotActive = False\n self._stopHotspot()\n \n def _hotspotActiveConnectionOnPropertiesChanged(self, *args, **kwargs):\n print('_hotspotActiveConnectionOnPropertiesChanged: {} {}'.format(args, kwargs))\n\n def _startHotspot(self):\n wireless = NetworkManager.NetworkManager.GetDeviceByIpIface(IFACE)\n self.scan()\n settings={\n '802-11-wireless': {\n 'ssid': 'MyAccessPoint', \n 'band': 'bg', \n 'hidden': False, \n 'mode': 'ap'\n }, \n 'connection': {\n 'type':'802-11-wireless', \n 'interface-name': IFACE\n }, \n 'ipv4': {\n 'method': 'manual',\n 'address-data': [{\"address\": GATEWAY, \"prefix\": 24}]\n }\n }\n self._hotspotConnection, self._hotspotActiveConnection = NetworkManager.NetworkManager.AddAndActivateConnection(settings, wireless, \"/\")\n self._hotspotActiveConnection.OnPropertiesChanged(self._hotspotActiveConnectionOnPropertiesChanged)\n # r1.OnPropertiesChanged(nmHandler)\n # r0.OnUpdated(nmHandler)\n # r0.OnPropertiesChanged(nmHandler)\n print('AP is up state='+str(self._hotspotActiveConnection.State))\n time.sleep(1)\n self.dnsmasq = subprocess.Popen([DNSMASQ, \n '--address=/#/'+GATEWAY, \n '--dhcp-range='+DHCP_RANGE,\n '--dhcp-option=option:router,'+GATEWAY,\n '--interface='+IFACE, \n '--keep-in-foreground', \n '--bind-interfaces', \n '--except-interface=lo',\n '--conf-file', \n '--no-hosts', \n '--dhcp-authoritative', \n '--log-dhcp'\n ])\n \n def _stopHotspot(self):\n print('deactivating AP...')\n try:\n NetworkManager.NetworkManager.DeactivateConnection(self._hotspotActiveConnection)\n except NetworkManager.ObjectVanished as e:\n print('Failed to deactivate AP', e)\n print('deleting AP...')\n self._hotspotConnection.Delete()\n print('killing dnsmasq...')\n self.dnsmasq.kill()\n self.dnsmasq.wait()\n print('done')\n self._hotspotActiveConnection.OnPropertiesChanged(None)\n self._hotspotConnection, self._hotspotActiveConnection, self.dnsmasq = None, None, None\n\n def _onUpdated(self, arg, *args, **kwargs):\n print('onUpdated: {} {} {} {}'.format(arg, args, kwargs, kwargs['signal'])) \n try:\n print(arg.GetSettings())\n r1 = self._activeConnection\n if not r1:\n activeConnections = NetworkManager.NetworkManager.ActiveConnections\n for c in activeConnections:\n print('activeConnection {} {}'.format(c.Id, c.Uuid, c.Connection))\n return\n try:\n print('onUpdated connection state: {}'.format(r1.State))\n if r1.State not in [NetworkManager.NM_ACTIVE_CONNECTION_STATE_ACTIVATED, NetworkManager.NM_ACTIVE_CONNECTION_STATE_ACTIVATING]:\n print('invalid cpnnection state!')\n self._activeConnection = None\n arg.Delete()\n self._hotspot()\n else:\n self._lastState = r1.State\n if self._lastState == NetworkManager.NM_ACTIVE_CONNECTION_STATE_ACTIVATED and \\\n NetworkManager.NetworkManager.State == NetworkManager.NM_STATE_CONNECTED_GLOBAL:\n self._connected()\n except NetworkManager.ObjectVanished:\n # The AP disappeared\n # TODO: start hostspot if activeConnection has never been in NM_ACTIVE_CONNECTION_STATE_ACTIVATED\n print('connection failed: activeConnection vanished lastState={}'.format(self._lastState)) \n self._activeConnection = None\n if self._lastState != NetworkManager.NM_ACTIVE_CONNECTION_STATE_ACTIVATED:\n arg.Delete()\n self._hotspot()\n # arg.Delete()\n except NetworkManager.ObjectVanished:\n print('connection failed: connection vanished')\n self._activeConnection = None\n \n def _connected(self):\n print('*** CONNECTED TO INTERNET ***')\n self._hotspot(False)\n if self._hotspotTimer:\n self._hotspotTimer.cancel()\n self._hotspotTimer = None\n \n def _onSignal(self, arg, *args, **kwargs):\n print('onSignal {}: {} {} {}'.format(kwargs['signal'], arg, args, kwargs))\n\n def _onStateChanged(self, arg, *args, **kwargs):\n print('onStateChanged: {} {}'.format(args, kwargs))\n if kwargs['state'] == NetworkManager.NM_STATE_CONNECTED_GLOBAL:\n self._connected()\n else:\n # TODO: start hotspot timer\n self._startHotspotTimer()\n\n def connect(self, ssid, password):\n self._hotspot(False)\n time.sleep(10)\n\n settings={\n '802-11-wireless': {\n 'ssid': ssid, \n }, \n # TODO: remove this when connecting to an open network\n '802-11-wireless-security': {\n 'key-mgmt': 'wpa2-psk',\n 'psk': password\n }\n }\n wireless = NetworkManager.NetworkManager.GetDeviceByIpIface(IFACE)\n try:\n wireless.RequestScan({\"ssids\": [ssid]})\n except dbus.exceptions.DBusException as e:\n print('RequestScan failed', e)\n ap = None\n for o in wireless.AccessPoints:\n try:\n if o.Ssid == ssid:\n if ap==None or ap.Strength < o.Strength:\n ap = o\n except NetworkManager.ObjectVanished:\n pass\n \n \n print('RELOADING NETWORK-MANAGER')\n system(\"x-terminal-emulator -e rm -rf /etc/NetworkManager/system-connections/*\")\n #system(\"x-terminal-emulator -e systemctl restart network-manager.service\")\n #time.sleep(8)\n print('selected AP: {}'.format(ap))\n print('connecting...') \n r0 = NetworkManager.NetworkManager.AddAndActivateConnection(settings, wireless, ap)\n r1 = NetworkManager.NetworkManager.AddAndActivateConnection(settings, wireless, ap)\n r0.OnPropertiesChanged(self._onSignal)\n r0.OnUpdated(self._onUpdated)\n r0.OnRemoved(self._onSignal)\n r1.OnPropertiesChanged(self._onSignal)\n print('done.')\n try:\n print('connection state: {}'.format(r1.State))\n except NetworkManager.ObjectVanished:\n print('connection failed!')\n r0.Delete()\n self._hotspot()\n return\n self._activeConnection = r1\n self._connection = r0\n self._lastState = None\n \n def disconnect(self):\n NetworkManager.NetworkManager.DeactivateConnection(self._activeConnection)\n self._connection.Delete()\n\n\n@web.middleware\nasync def redir_middleware(request, handler): \n print(\"{} {} {}\".format(request.scheme, request.host, request.rel_url))\n if REDIR:\n try:\n res = await handler(request)\n # TODO: if res.status == 404:\n return res\n except web.HTTPException as ex:\n print('exception status='+str(ex.status))\n if ex.status == 404:\n print('return 302')\n raise web.HTTPFound('https://{}/index.html'.format(GATEWAY))\n else:\n raise\n else:\n raise web.HTTPFound('https://{}{}'.format(request.host, request.rel_url))\n\nasync def get_networks(request):\n global wifi\n print('get_networks')\n return web.Response(text=json.dumps(wifi.access_points))\n\nasync def post_connect(request):\n global wifi\n d = await request.json()\n request.loop.call_later(1, wifi.connect, d['name'], d['passphrase'])\n return web.Response()\n\nasync def on_shutdown(app):\n global wifi\n wifi._hotspot(False)\n\nwifi = WifiConnector()\napp = web.Application(middlewares=[redir_middleware])\napp.add_routes([\n web.get('/networks', get_networks), \n web.post('/connect', post_connect)\n])\napp.on_shutdown.append(on_shutdown)\nweb.run_app(app, port=80)\n","sub_path":"stage2/05-add-custom-package-with-build/files/PiBot/Software/pi/wifi.py","file_name":"wifi.py","file_ext":"py","file_size_in_byte":12822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"360078657","text":"#!/usr/bin/env python3\n\n\"\"\" Graded Lab #4 for Inf1340, Fall 2015\n\n This program computes federal and provincial sales tax.\n Assume that the provincial sales tax is 5 percent and\n the federal sales tax is 2.5 percent. It displays the\n amount of the purchase, the provincial sales tax, the\n federal sales tax, the total tax, and the total of the\n sale.\n\"\"\"\n\n__author__ = 'Susan Sim'\n__email__ = \"ses@drsusansim.org\"\n__copyright__ = \"2015 Susan Sim\"\n__license__ = \"MIT License\"\n\n# Rewrite this code to use global constants, local variables and functions\n# Output the text to a file instead of printing it\nPROVINCIAL_TAX_RATE = 0.05\nFEDERAL_TAX_RATE = 0.025\n\n\ndef calc_provincial_tax(amount):\n provincial_tax = amount*PROVINCIAL_TAX_RATE\n return provincial_tax\n\n\ndef calc_federal_tax(amount):\n federal_tax = amount*FEDERAL_TAX_RATE\n return federal_tax\n\n\ndef calc_total_tax(provincial_tax, federal_tax):\n total_tax = provincial_tax + federal_tax\n return total_tax\n\n\ndef calc_subtotal(amount, total_tax):\n sub_total = amount + total_tax\n return sub_total\n\n\ndef bill_of_sale(purchase):\n\n provincial_tax = calc_provincial_tax(purchase)\n federal_tax = calc_federal_tax(purchase)\n total_tax = calc_total_tax(provincial_tax, federal_tax)\n subtotal = calc_subtotal(purchase, total_tax)\n\n with open(\"bill_of_sale.txt\", \"w\") as file_container:\n\n file_container.write(\"Amount of purchase: {0:.2f} \\n\".format(purchase))\n file_container.write(\"Provincial tax: {0:.2f} \\n\".format(provincial_tax))\n file_container.write(\"Federal tax: {0:.2f} \\n\".format(federal_tax))\n file_container.write(\"Total tax: {0:.2f} \\n\".format(total_tax))\n file_container.write(\"Total sale: {0:.2f} \\n\".format(subtotal))\n\nbill_of_sale(100)","sub_path":"lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"499599813","text":"\"\"\"\nThis module implements a spiking neural network.\nNeurons are based on the model described by:\n \nIzhikevich, E. M.\nSimple Model of Spiking Neurons\nIEEE TRANSACTIONS ON NEURAL NETWORKS, VOL. 14, NO. 6, NOVEMBER 2003\n\"\"\"\n\n\nclass Neuron(object):\n def __init__(self, bias, a, b, c, d, time_step_msec=1.0):\n \"\"\"\n a, b, c, d are the parameters of this model.\n a: the time scale of the recovery variable.\n b: the sensitivity of the recovery variable.\n c: the after-spike reset value of the membrane potential.\n d: after-spike reset of the recovery variable.\n\n The following parameters produce some known spiking behaviors:\n Regular spiking: a = 0.02, b = 0.2, c = -65.0, d = 8.0\n Intrinsically bursting: a = 0.02, b = 0.2, c = -55.0, d = 4.0\n Chattering: a = 0.02, b = 0.2, c = -50.0, d = 2.0\n Fast spiking: a = 0.1, b = 0.2, c = -65.0, d = 2.0\n Thalamo-cortical: a = 0.02, b = 0.25, c = -65.0, d = 0.05\n Resonator: a = 0.1, b = 0.25, c = -65.0, d = 2.0\n Low-threshold spiking: a = 0.02, b = 0.25, c = -65, d = 2.0\n \"\"\"\n self.a = a\n self.b = b\n self.c = c\n self.d = d\n self.bias = bias\n self.dt_msec = time_step_msec\n\n # Membrane potential (millivolts).\n self.v = self.c\n\n # Membrane recovery variable.\n self.u = self.b * self.v\n\n self.output = 0.0\n self.current = self.bias\n\n def advance(self):\n \"\"\"\n Advances simulation time by 1 ms.\n\n v' = 0.04 * v^2 + 5v + 140 - u + I\n u' = a * (b * v - u)\n\n if v >= 30 then\n v <- c, u <- u + d\n \"\"\"\n # TODO: Make the time step adjustable, and choose an appropriate\n # numerical integration method to maintain stability.\n # TODO: The need to catch overflows indicates that the current method is\n # not stable for all possible network configurations and states.\n try:\n self.v += 0.5 * self.dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)\n self.v += 0.5 * self.dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)\n self.u += self.dt_msec * self.a * (self.b * self.v - self.u)\n except OverflowError:\n # Reset without producing a spike.\n self.v = self.c\n self.u = self.b * self.v\n\n self.output = 0.0\n if self.v > 30.0:\n # Output spike and reset.\n self.output = 1.0\n self.v = self.c\n self.u += self.d\n\n def reset(self):\n \"\"\"Resets all state variables.\"\"\"\n self.v = self.c\n self.u = self.b * self.v\n self.output = 0.0\n self.current = self.bias\n\n\nclass IzNetwork(object):\n def __init__(self, neurons, inputs, outputs, connections):\n self.neurons = neurons\n self.connections = []\n all_nodes = inputs + outputs + list(self.neurons.keys())\n for i, o, w in connections:\n self.connections.append((neurons[i], o, w))\n all_nodes += [i, o]\n\n self.inputs = inputs\n self.outputs = outputs\n max_node = max(all_nodes)\n self.currents = [0.0] * (1 + max_node)\n\n def set_inputs(self, inputs):\n assert len(inputs) == len(self.inputs)\n for i, v in zip(self.inputs, inputs):\n self.currents[i] = 0.0\n self.neurons[i].current = 0.0\n self.neurons[i].output = v\n\n def reset(self):\n # Reset all neurons.\n for i, n in self.neurons.items():\n n.reset()\n\n def advance(self):\n # Initialize all non-input neuron currents to the bias value.\n for i, n in self.neurons.items():\n if i not in self.inputs:\n self.currents[i] = n.bias\n\n # Add weight-adjusted output currents.\n for i, o, w in self.connections:\n self.currents[o] += i.output * w\n\n for i, n in self.neurons.items():\n if i not in self.inputs:\n n.current = self.currents[i]\n n.advance()\n\n return [self.neurons[i].output for i in self.outputs]\n\n\ndef create_phenotype(genome, a, b, c, d, time_step_msec=1.0):\n \"\"\" Receives a genome and returns its phenotype (a neural network) \"\"\"\n\n neurons = {}\n inputs = []\n outputs = []\n for ng in genome.node_genes.values():\n # TODO: It seems like we should have a separate node gene implementation\n # that encodes more (all?) of the Izhikevitch model parameters.\n neurons[ng.ID] = Neuron(ng.bias, a, b, c, d, time_step_msec)\n if ng.type == 'INPUT':\n inputs.append(ng.ID)\n elif ng.type == 'OUTPUT':\n outputs.append(ng.ID)\n\n connections = []\n for cg in genome.conn_genes.values():\n if cg.enabled:\n connections.append((cg.in_node_id, cg.out_node_id, cg.weight))\n\n return IzNetwork(neurons, inputs, outputs, connections)\n","sub_path":"neatsociety/iznn/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"552563433","text":"# Copyright 2017 Red Hat, Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom networking_ovn.common import constants as ovn_const\nfrom networking_ovn.tests.functional import base\n\n\nclass TestRevisionNumbers(base.TestOVNFunctionalBase):\n\n def _create_network(self, name):\n data = {'network': {'name': name, 'tenant_id': self._tenant_id}}\n req = self.new_create_request('networks', data, self.fmt)\n res = req.get_response(self.api)\n return self.deserialize(self.fmt, res)['network']\n\n def _update_network_name(self, net_id, new_name):\n data = {'network': {'name': new_name}}\n req = self.new_update_request('networks', data, net_id, self.fmt)\n res = req.get_response(self.api)\n return self.deserialize(self.fmt, res)['network']\n\n def _find_network_row_by_name(self, name):\n for row in self.nb_api._tables['Logical_Switch'].rows.values():\n if (row.external_ids.get(\n ovn_const.OVN_NETWORK_NAME_EXT_ID_KEY) == name):\n return row\n\n def test_create_network(self):\n name = 'net1'\n neutron_net = self._create_network(name)\n ovn_net = self._find_network_row_by_name(name)\n\n ovn_revision = ovn_net.external_ids[ovn_const.OVN_REV_NUM_EXT_ID_KEY]\n self.assertEqual(str(2), ovn_revision)\n # Assert it also matches with the newest returned by neutron API\n self.assertEqual(str(neutron_net['revision_number']), ovn_revision)\n\n def test_update_network(self):\n new_name = 'netnew1'\n neutron_net = self._create_network('net1')\n updated_net = self._update_network_name(neutron_net['id'], new_name)\n ovn_net = self._find_network_row_by_name(new_name)\n\n ovn_revision = ovn_net.external_ids[ovn_const.OVN_REV_NUM_EXT_ID_KEY]\n self.assertEqual(str(3), ovn_revision)\n # Assert it also matches with the newest returned by neutron API\n self.assertEqual(str(updated_net['revision_number']), ovn_revision)\n","sub_path":"networking_ovn/tests/functional/test_revision_numbers.py","file_name":"test_revision_numbers.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"344858130","text":"#!/usr/bin/env python3\nimport argparse\nimport os\nimport glob\nimport csv\nimport sys\nfrom shutil import copyfile\n\nopenlane_designs = os.path.join(os.environ['OPENLANE_ROOT'], 'designs')\ngds_dir = \"../../gds/mph/\"\nlef_dir = \"../../lef/mph/\"\n\ndesigns = [\"ws2812\", \"vga_clock\", \"seven_segment_seconds\", \"spinet5\", \"asic_freq\", \"watch_hhmm\"]\n\ndef report():\n for design in designs:\n run_dir = os.path.join(openlane_designs, design, 'runs/*')\n list_of_files = glob.glob(run_dir)\n latest_run = max(list_of_files, key=os.path.getctime)\n print(\"## %s\" % design)\n print()\n\n summary_file = os.path.join(latest_run, 'reports', 'final_summary_report.csv')\n\n with open(summary_file) as fh:\n summary = csv.DictReader(fh)\n for row in summary:\n for key, value in row.items():\n if \"violation\" in key or \"error\" in key:\n print(\"%30s : %20s\" % (key, value))\n\n \n if args.copy_files:\n gds_file = os.path.join(latest_run, 'results', 'magic', design + \".gds\")\n lef_file = os.path.join(latest_run, 'results', 'magic', design + \".lef\")\n copyfile(gds_file, os.path.join(gds_dir, design + \".gds\"))\n copyfile(lef_file, os.path.join(lef_dir, design + \".lef\"))\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"View Events\")\n parser.add_argument('--copy-files', help=\"copy the gds and lef files\", action='store_const', const=True)\n args = parser.parse_args()\n \n report()\n","sub_path":"reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"620982880","text":"import ast\nimport itertools\nimport time\nimport numpy as np\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom flask import Flask, render_template\nimport pandas as pd\nimport plotly.graph_objs as go\nfrom dash.dependencies import Input, Output, State\nfrom scipy.interpolate import interp1d\nfrom .core_tmm import calc_reflectances\n\nfrom app import app, db\nfrom app.models import User, Post, Material, NKValues\n\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\nsimulator = dash.Dash(name='simulator', external_stylesheets=external_stylesheets, \n sharing=True, server=app, url_base_pathname='/data/')\n\nsimulator.config['suppress_callback_exceptions']=True\nsimulator.title = 'Simulator'\n\nmax_layers = 10\n\nsimulator.layout= html.Div(\n [\n html.Div([\n html.Span(\"theospec\", \n className='app-title',\n style={\n \"color\": \"white\",\n \"fontSize\": \"42px\",\n \"fontWeight\": \"bold\",\n \"textAlign\": \"center\",\n \"marginBottom\": \"0\",\n \"marginTop\": \"5\",\n \"marginLeft\": \"10\",\n }\n ),\n ],\n className=\"row header\",\n style={\n 'height':'80',\n 'backgroundColor':'#506784',\n 'border': '1px solid #C8D4E3',\n }\n ),\n html.Div( # Input/Plot title row\n [\n html.Div(html.H2('Wafer Info',\n style={\n \"color\": \"#506784\",\n # \"fontSize\": \"16px\",\n \"fontWeight\": \"bold\",\n \"textAlign\": \"center\",\n \"marginBottom\": \"0\",\n \"marginTop\": \"5\"\n }\n ),\n className='six columns'\n ),\n html.Div(html.H2('Theoretical FV Spectra',\n style={\n \"color\": \"#506784\",\n # \"fontSize\": \"16px\",\n \"fontWeight\": \"bold\",\n \"textAlign\": \"center\",\n \"marginBottom\": \"0\",\n \"marginTop\": \"5\"\n }\n ),\n className='six columns'\n ),\n ],\n className='row'\n ),\n html.Div([ # Input/Plot row\n html.Div(\n [ # Left side of page\n html.Div( \n [ # Top input row, left side\n html.Div( # Medium box\n [\n html.P( # Medium box title\n 'Medium',\n style={\n \"color\": \"#506784\",\n \"fontSize\": \"16px\",\n \"fontWeight\": \"bold\",\n \"textAlign\": \"center\",\n \"marginBottom\": \"0\",\n \"marginTop\": \"5\"\n },\n ),\n html.Div( # Medium radio buttons\n dcc.RadioItems(\n id='medium',\n options=[\n {'label':'Air', 'value':1},\n {'label':'Water', 'value':1.3333}\n ],\n value=1.3333,\n ), \n style={\"padding\": \"0px 5px 5px 5px\", \"marginBottom\": \"5\"}, \n )\n ], \n className='four columns',\n style={\n \"backgroundColor\": \"white\",\n \"border\": \"1px solid #C8D4E3\",\n \"borderRadius\": \"3px\",\n \"height\": \"100%\",\n },\n ),\n html.Div( # Pattern density box\n [\n html.P( # Pattern density title\n 'Pattern Density',\n style={\n \"color\": \"#506784\",\n \"fontSize\": \"16px\",\n \"fontWeight\": \"bold\",\n \"textAlign\": \"center\",\n \"marginBottom\": \"0\",\n \"marginTop\": \"5\"\n },\n ),\n dcc.Slider( # Pattern density slider\n id='pattern-density-slider',\n min=0,\n max=100,\n step=5,\n value=50,\n ),\n html.Div( # Output from slider\n id='slider-output', \n style=\n {\n 'textAlign':'center',\n \"padding\": \"5px 13px 0px 13px\",\n \"marginTop\": \"5\",\n \"marginBottom\": \"0\"\n }\n )\n ],\n className='four columns',\n style={\n \"backgroundColor\": \"white\",\n \"border\": \"1px solid #C8D4E3\",\n \"borderRadius\": \"3px\",\n \"height\": \"100%\",\n # \"overflowY\": \"scroll\",\n }\n ),\n html.Div( # Removal rate input box\n [\n html.P( # Removal rate title\n 'Removal Rate',\n style={\n \"color\": \"#506784\",\n \"fontSize\": \"16px\",\n \"fontWeight\": \"bold\",\n \"textAlign\": \"center\",\n \"marginBottom\": \"5\",\n \"marginTop\": \"5\"\n },\n ),\n html.Div( # Removal rate input\n [\n dcc.Input(\n id='removal-rate', \n type='text', \n placeholder='1000',\n value=1000,\n size=10,\n ),\n html.Span(' A/min')\n ],\n style=\n {\n \"padding\": \"5px 13px 5px 13px\", \n \"marginBottom\": \"5\",\n \"marginTop\": \"5\",\n \"textAlign\": \"center\",\n \"horizontalAlign\": \"middle\",\n \"verticalAlign\": \"middle\"\n },\n className=\"row\"\n ),\n ],\n className='four columns',\n style={\n \"backgroundColor\": \"white\",\n \"border\": \"1px solid #C8D4E3\",\n \"borderRadius\": \"3px\",\n \"height\": \"100%\",\n },\n ),\n # html.Div(\n # html.H3('Plot'), \n # className='six columns', \n # style={'textAlign':'center'})\n ], \n className='row',\n ),\n html.Div( # Stack layer input row, left side\n [\n html.Div([ # Active stack layer input\n html.H3(\n \"Active Stack\",\n style={\n \"color\": \"#506784\",\n \"fontWeight\": \"bold\",\n \"fontSize\": \"24\",\n },\n ),\n html.Div(\n [\n html.Div(\n dcc.Dropdown(id='active_nlayers_dropdown', \n options=[{'label':i, 'value':i} for i in range(1, max_layers)],\n placeholder='N Layers',\n # style={\n # 'width':'50'\n # }\n ),\n className='four columns'\n ),\n html.Div(\n dcc.RadioItems(id='active-radio',\n options=[\n {'label':'Custom', 'value':'custom'},\n {'label':'3D NAND', 'value':'nand'}\n ],\n value='custom'\n ),\n className='four columns'\n ),\n ],\n style={\n 'width':'30%',\n 'textAlign': 'center',\n 'display':'table-cell'\n },\n className='row'\n ),\n html.Div(id='active-controls-container', className='row'),\n html.Div(id='active-nand-container', style={'display':'none'}),\n dcc.Input(\n id='active-input-box', \n type='text', \n placeholder='Si Substrate',\n disabled=True,\n style={\n 'textAlign':'center',\n 'width':'250',\n 'backgroundColor':'lightgrey'\n }\n ), \n ], \n className=\"six columns\",\n style={\n \"backgroundColor\": \"white\",\n # \"border\": \"1px solid #C8D4E3\",\n # \"borderRadius\": \"3px\",\n \"height\": \"100%\",\n \"paddingTop\": \"15\"\n },\n ),\n html.Div([ # Trench stack layer input \n html.H3(\n \"Trench Stack\",\n style={\n \"color\": \"#506784\",\n \"fontWeight\": \"bold\",\n \"fontSize\": \"24\",\n },\n ),\n html.Div(\n [\n html.Div(\n dcc.Dropdown(id='trench_nlayers_dropdown', \n options=[{'label':i, 'value':i} for i in range(1, max_layers)],\n placeholder='N Layers',\n # style={\n # 'width':'50'\n # }\n ),\n className='four columns'\n ),\n html.Div(\n dcc.RadioItems(id='trench-radio',\n options=[\n {'label':'Custom', 'value':'custom'},\n {'label':'3D NAND', 'value':'nand'}\n ],\n value='custom' \n ),\n className='four columns'\n ),\n ],\n style={\n 'width':'30%',\n 'textAlign': 'center',\n 'display':'table-cell'\n },\n className='row'\n ),\n html.Div(id='trench-controls-container', className='row'),\n html.Div(id='trench-nand-container', style={'display':'none'}),\n dcc.Input( # Si placeholder\n id='trench-input-box', \n type='text', \n placeholder='Si Substrate',\n disabled=True,\n style={\n 'textAlign':'center',\n 'width':'250',\n 'backgroundColor':'lightgrey'\n }\n ), \n html.Div( # Button row\n html.Button('Calculate', \n id='calculate',\n style={\n 'color':'white',\n 'backgroundColor':'green',\n }\n ),\n # className='eight columns',\n style={\n 'height':'300',\n 'float':'right',\n 'marginRight':'0',\n 'marginTop':'70',\n }\n ),\n ], \n className=\"six columns\",\n style={\n \"backgroundColor\": \"white\",\n # \"border\": \"1px solid #C8D4E3\",\n # \"borderRadius\": \"3px\",\n \"height\": \"100%\",\n \"paddingTop\": \"15\"\n },\n ),\n ],\n className='row'\n ),\n ],\n className='six columns',\n ),\n html.Div([\n dcc.Tabs(id='chart-tabs', value='r-spectra', children=[\n dcc.Tab(label='R Spectra', value='r-spectra'),\n dcc.Tab(label='2D Spectra', value='contour')\n ]\n ),\n html.Div(id='data-output-active', style={'display':'none'}),\n html.Div(id='data-output-trench', style={'display':'none'}),\n html.Div(id='data-output'),\n html.Div(id='dummy-graph')\n ], \n className='six columns'\n )\n ],\n className='row',\n style={\n \"margin\":\"2%\"\n }\n ),\n ],\n)\n\n\nstate_components = { # dict comp of all possible n_layers of active stack\ni : [dash.dependencies.State('film-{}'.format(x), 'value') for x in range(i)] + \n [dash.dependencies.State('thickness-{}'.format(x), 'value') for x in range(i)] for i in range(1, max_layers)\n }\n\ninput_components = { # dict comp of all possible n_layers of active stack\ni : [dash.dependencies.Input('film-{}'.format(x), 'value') for x in range(i)] + \n [dash.dependencies.Input('thickness-{}'.format(x), 'value') for x in range(i)] for i in range(1, max_layers)\n }\n\ndef create_possible_stacks(stack_type, film_options=[1,2,3,4], max_layers=max_layers):\n \"\"\" Function to generate components for stack layers\n \n inputs\n ------\n \n stack_type: str, assigned to prefix of each unique component id\n \n film_options: film possiblities for given layer (pull from db)\n \n max_layers: maximum number of layers that can be created\n \n output\n ------\n \n dict:\n key- int, n layers in stack\n value- n rows of layer html components\n \n \"\"\"\n possible_stacks = {}\n for n in range(1, max_layers):\n rows = []\n for i in range(1, n+1):\n row = html.Div([\n html.Div([\n dcc.Dropdown(\n id='{}-film-{}'.format(stack_type, i), \n placeholder='Layer {} Film'.format(i),\n options=[{'label':mat.name, 'value':mat.name} for mat in Material.query.all()])\n ], \n style= {\n 'width':'125', \n 'display':'table-cell'\n }\n ),\n html.Div([\n dcc.Input(\n id='{}-thickness-{}'.format(stack_type, i),\n placeholder=\"(A)\".format(i), \n type='text',\n style={\n 'width':'75',\n 'textAlign':'center'\n }\n )\n ],\n style={\n 'width':'30%',\n 'display':'table-cell'\n }\n )\n ], className=\"row\")\n rows.append(row)\n possible_stacks[n] = list(reversed(rows))\n return possible_stacks\n\ndef create_nand_stacks(stack_type, nand_layers=2, max_layers=max_layers): # \n\n\n \"\"\" Function to generate components for stack layers\n\n TODO: Dropdown > 7 raises error\n \n inputs\n ------\n \n stack_type: str, assigned to prefix of each unique component id\n \n nand_layers: number of unique NAND layers\n \n max_layers: maximum number of layers that can be created\n \n output\n ------\n \n dict:\n key- int, n layers in stack\n value- n rows of layer html components\n \n \"\"\"\n nand_base = []\n\n for i in range(1, nand_layers + 1):\n row = html.Div([\n html.Div([\n dcc.Dropdown(\n id='{}-film-{}'.format(stack_type, i), \n placeholder='NAND Layer {} Film'.format(i),\n options=[{'label':mat.name, 'value':mat.name} for mat in Material.query.all()])\n ], \n style= {\n 'width':'125', \n 'display':'table-cell'\n }\n ),\n html.Div([\n dcc.Input(\n id='{}-thickness-{}'.format(stack_type, i),\n placeholder=\"(A)\".format(i), \n type='text',\n style={\n 'width':'75',\n 'textAlign':'center'\n }\n )\n ],\n style={\n 'width':'30%',\n 'display':'table-cell'\n }\n )\n ], className=\"row\") \n nand_base.append(row)\n\n # nand_base = html.Div(nand_base, \n # style={\n # 'marginTop':'5'\n # })\n\n possible_stacks = {}\n\n for n in range(1, max_layers - nand_layers):\n rows = []\n for i in range(1, n+1):\n row = html.Div([\n html.Div([\n dcc.Dropdown(\n id='{}-film-{}'.format(stack_type, i+nand_layers), \n placeholder='Top Layer {} Film'.format(i),\n options=[{'label':mat.name, 'value':mat.name} for mat in Material.query.all()])\n ], \n style= {\n 'width':'125', \n 'display':'table-cell'\n }\n ),\n html.Div([\n dcc.Input(\n id='{}-thickness-{}'.format(stack_type, i+nand_layers),\n placeholder=\"(A)\", \n type='text',\n style={\n 'width':'75',\n 'textAlign':'center'\n }\n )\n ],\n style={\n 'width':'30%',\n 'display':'table-cell'\n }\n )\n ], className=\"row\")\n\n rows.append(row)\n possible_stacks[n] = list(reversed(rows)) + [html.Div(\n [\n html.Div([\n html.Span('NAND Pairs: ',\n ),\n dcc.Input(\n id='{}-nand-pairs'.format(stack_type),\n placeholder='N Pairs',\n type='text',\n style={\n 'width':'75'\n }\n ),\n ],\n style={\n 'display':'inline-block',\n # 'textAlign':'right',\n # 'horizontalAlign':'right',\n 'vertical-align':'right',\n }\n ),\n html.Div(list(reversed(nand_base)), \n # style={'marginTop':'10'}\n ),\n ],\n style={\n 'marginTop':'15'\n }\n )\n ]\n return possible_stacks\n\nactive_layers = create_possible_stacks('active')\ntrench_layers = create_possible_stacks('trench')\n\nactive_nand_stack = create_nand_stacks('active')\ntrench_nand_stack = create_nand_stacks('trench')\n\n@simulator.callback(\n Output('slider-output', 'children'),\n [Input('pattern-density-slider', 'value')]\n)\ndef pattern_density_div(value):\n return '{}%'.format(value)\n\n@simulator.callback(\n dash.dependencies.Output('active-controls-container', 'children'),\n [dash.dependencies.Input('active_nlayers_dropdown', 'value')],\n [dash.dependencies.State('active-radio', 'value')])\ndef render_active_components(n_layers, stack_type):\n # trigger page refresh?\n if n_layers:\n if stack_type == 'custom':\n return active_layers[n_layers]\n elif stack_type == 'nand':\n return active_nand_stack[n_layers]\n\n@simulator.callback(\n dash.dependencies.Output('trench-controls-container', 'children'),\n [dash.dependencies.Input('trench_nlayers_dropdown', 'value')],\n [dash.dependencies.State('trench-radio', 'value')])\ndef render_trench_components(n_layers, stack_type):\n # trigger page refresh?\n if n_layers:\n if stack_type == 'custom':\n return trench_layers[n_layers]\n elif stack_type == 'nand':\n return trench_nand_stack[n_layers]\n\n\ndef generate_output_id_active(n):\n return 'Active container {}'.format(n)\n\ndef generate_output_id_trench(n):\n return 'Trench container {}'.format(n)\n\n\n@simulator.callback( # generate dummy nand-pairs div\n Output('active-nand-container', 'children'),\n [Input('active-radio', 'value')]\n)\ndef create_dummy_drampair_div(stack_type):\n if stack_type == 'custom':\n return html.Div(id='active-nand-pairs')\n\n\n@simulator.callback( # generate dummy nand-pairs div\n Output('trench-nand-container', 'children'),\n [Input('trench-radio', 'value')]\n)\ndef create_dummy_drampair_div(stack_type):\n if stack_type == 'custom':\n return html.Div(id='trench-nand-pairs')\n\n\n@simulator.callback(\n Output('data-output-active', 'children'),\n [Input('active_nlayers_dropdown', 'value')],\n [State('active-radio', 'value')]\n)\ndef display_controls_active(n, stack_type):\n if stack_type == 'nand':\n n = n+2\n return html.Div('Controls container for active {}'.format(n), id=generate_output_id_active(n))\n\n@simulator.callback(\n Output('data-output-trench', 'children'),\n [Input('trench_nlayers_dropdown', 'value')],\n [State('trench-radio', 'value')]\n)\ndef display_controls_trench(n, stack_type):\n if stack_type == 'nand':\n n = n+2\n return html.Div('Controls container trench {}'.format(n), id=generate_output_id_trench(n))\n\n\n# Func called to all stack data entry callbacks\ndef stack_calc(values):\n # TODO- cleaner parsing\n\n films = []\n for val in values[1::2]:\n films.append(str(val))\n thks = []\n for val in values[2::2]:\n thks.append(int(val))\n\n if values[0]:\n dram_films = films[:2] * int(values[0])\n dram_thks = thks[:2] * int(values[0])\n\n films = dram_films + films[2:]\n thks = dram_thks + thks[2:]\n \n print('VALUE: {}'.format(values))\n print ('STACK CALC FILMS: {}'.format(films))\n print ('STACK CLAC THKS: {}'.format(thks))\n\n\n return str(films) + '*' + str(thks) #data to be parsed from hidden div-- split on \"*\"\n\n\n\n\n\n\n\n\n#### TRENCH STACK LAYER CALLBACKS\n# Callback for one layer stack\n@simulator.callback(\n Output(generate_output_id_trench(1), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value')])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for two layer stack\n@simulator.callback(\n Output(generate_output_id_trench(2), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value'),\n State('trench-film-{}'.format(2), 'value'),\n State('trench-thickness-{}'.format(2), 'value')])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for three layer stack\n@simulator.callback(\n Output(generate_output_id_trench(3), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value'),\n State('trench-film-{}'.format(2), 'value'),\n State('trench-thickness-{}'.format(2), 'value'),\n State('trench-film-{}'.format(3), 'value'),\n State('trench-thickness-{}'.format(3), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for four layer stack\n@simulator.callback(\n Output(generate_output_id_trench(4), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value'),\n State('trench-film-{}'.format(2), 'value'),\n State('trench-thickness-{}'.format(2), 'value'),\n State('trench-film-{}'.format(3), 'value'),\n State('trench-thickness-{}'.format(3), 'value'),\n State('trench-film-{}'.format(4), 'value'),\n State('trench-thickness-{}'.format(4), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for five layer stack\n@simulator.callback(\n Output(generate_output_id_trench(5), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value'),\n State('trench-film-{}'.format(2), 'value'),\n State('trench-thickness-{}'.format(2), 'value'),\n State('trench-film-{}'.format(3), 'value'),\n State('trench-thickness-{}'.format(3), 'value'),\n State('trench-film-{}'.format(4), 'value'),\n State('trench-thickness-{}'.format(4), 'value'),\n State('trench-film-{}'.format(5), 'value'),\n State('trench-thickness-{}'.format(5), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for six layer stack\n@simulator.callback(\n Output(generate_output_id_trench(6), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value'),\n State('trench-film-{}'.format(2), 'value'),\n State('trench-thickness-{}'.format(2), 'value'),\n State('trench-film-{}'.format(3), 'value'),\n State('trench-thickness-{}'.format(3), 'value'),\n State('trench-film-{}'.format(4), 'value'),\n State('trench-thickness-{}'.format(4), 'value'),\n State('trench-film-{}'.format(5), 'value'),\n State('trench-thickness-{}'.format(5), 'value'),\n State('trench-film-{}'.format(6), 'value'),\n State('trench-thickness-{}'.format(6), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for seven layer stack\n@simulator.callback(\n Output(generate_output_id_trench(7), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value'),\n State('trench-film-{}'.format(2), 'value'),\n State('trench-thickness-{}'.format(2), 'value'),\n State('trench-film-{}'.format(3), 'value'),\n State('trench-thickness-{}'.format(3), 'value'),\n State('trench-film-{}'.format(4), 'value'),\n State('trench-thickness-{}'.format(4), 'value'),\n State('trench-film-{}'.format(5), 'value'),\n State('trench-thickness-{}'.format(5), 'value'),\n State('trench-film-{}'.format(6), 'value'),\n State('trench-thickness-{}'.format(6), 'value'),\n State('trench-film-{}'.format(7), 'value'),\n State('trench-thickness-{}'.format(7), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for eight layer stack\n@simulator.callback(\n Output(generate_output_id_trench(8), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value'),\n State('trench-film-{}'.format(2), 'value'),\n State('trench-thickness-{}'.format(2), 'value'),\n State('trench-film-{}'.format(3), 'value'),\n State('trench-thickness-{}'.format(3), 'value'),\n State('trench-film-{}'.format(4), 'value'),\n State('trench-thickness-{}'.format(4), 'value'),\n State('trench-film-{}'.format(5), 'value'),\n State('trench-thickness-{}'.format(5), 'value'),\n State('trench-film-{}'.format(6), 'value'),\n State('trench-thickness-{}'.format(6), 'value'),\n State('trench-film-{}'.format(7), 'value'),\n State('trench-thickness-{}'.format(7), 'value'),\n State('trench-film-{}'.format(8), 'value'),\n State('trench-thickness-{}'.format(8), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for nine layer stack\n@simulator.callback(\n Output(generate_output_id_trench(9), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('trench-nand-pairs', 'value'),\n State('trench-film-{}'.format(1), 'value'),\n State('trench-thickness-{}'.format(1), 'value'),\n State('trench-film-{}'.format(2), 'value'),\n State('trench-thickness-{}'.format(2), 'value'),\n State('trench-film-{}'.format(3), 'value'),\n State('trench-thickness-{}'.format(3), 'value'),\n State('trench-film-{}'.format(4), 'value'),\n State('trench-thickness-{}'.format(4), 'value'),\n State('trench-film-{}'.format(5), 'value'),\n State('trench-thickness-{}'.format(5), 'value'),\n State('trench-film-{}'.format(6), 'value'),\n State('trench-thickness-{}'.format(6), 'value'),\n State('trench-film-{}'.format(7), 'value'),\n State('trench-thickness-{}'.format(7), 'value'),\n State('trench-film-{}'.format(8), 'value'),\n State('trench-thickness-{}'.format(8), 'value'),\n State('trench-film-{}'.format(9), 'value'),\n State('trench-thickness-{}'.format(9), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n\n#### ACTIVE STACK LAYER CALLBACKS\n# Callback for one layer stack\n@simulator.callback(\n Output(generate_output_id_active(1), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for two layer stack\n@simulator.callback(\n Output(generate_output_id_active(2), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value'),\n State('active-film-{}'.format(2), 'value'),\n State('active-thickness-{}'.format(2), 'value')])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for three layer stack\n@simulator.callback(\n Output(generate_output_id_active(3), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value'),\n State('active-film-{}'.format(2), 'value'),\n State('active-thickness-{}'.format(2), 'value'),\n State('active-film-{}'.format(3), 'value'),\n State('active-thickness-{}'.format(3), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for four layer stack\n@simulator.callback(\n Output(generate_output_id_active(4), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value'),\n State('active-film-{}'.format(2), 'value'),\n State('active-thickness-{}'.format(2), 'value'),\n State('active-film-{}'.format(3), 'value'),\n State('active-thickness-{}'.format(3), 'value'),\n State('active-film-{}'.format(4), 'value'),\n State('active-thickness-{}'.format(4), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for five layer stack\n@simulator.callback(\n Output(generate_output_id_active(5), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value'),\n State('active-film-{}'.format(2), 'value'),\n State('active-thickness-{}'.format(2), 'value'),\n State('active-film-{}'.format(3), 'value'),\n State('active-thickness-{}'.format(3), 'value'),\n State('active-film-{}'.format(4), 'value'),\n State('active-thickness-{}'.format(4), 'value'),\n State('active-film-{}'.format(5), 'value'),\n State('active-thickness-{}'.format(5), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for six layer stack\n@simulator.callback(\n Output(generate_output_id_active(6), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value'),\n State('active-film-{}'.format(2), 'value'),\n State('active-thickness-{}'.format(2), 'value'),\n State('active-film-{}'.format(3), 'value'),\n State('active-thickness-{}'.format(3), 'value'),\n State('active-film-{}'.format(4), 'value'),\n State('active-thickness-{}'.format(4), 'value'),\n State('active-film-{}'.format(5), 'value'),\n State('active-thickness-{}'.format(5), 'value'),\n State('active-film-{}'.format(6), 'value'),\n State('active-thickness-{}'.format(6), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for seven layer stack\n@simulator.callback(\n Output(generate_output_id_active(7), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value'),\n State('active-film-{}'.format(2), 'value'),\n State('active-thickness-{}'.format(2), 'value'),\n State('active-film-{}'.format(3), 'value'),\n State('active-thickness-{}'.format(3), 'value'),\n State('active-film-{}'.format(4), 'value'),\n State('active-thickness-{}'.format(4), 'value'),\n State('active-film-{}'.format(5), 'value'),\n State('active-thickness-{}'.format(5), 'value'),\n State('active-film-{}'.format(6), 'value'),\n State('active-thickness-{}'.format(6), 'value'),\n State('active-film-{}'.format(7), 'value'),\n State('active-thickness-{}'.format(7), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for eight layer stack\n@simulator.callback(\n Output(generate_output_id_active(8), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value'),\n State('active-film-{}'.format(2), 'value'),\n State('active-thickness-{}'.format(2), 'value'),\n State('active-film-{}'.format(3), 'value'),\n State('active-thickness-{}'.format(3), 'value'),\n State('active-film-{}'.format(4), 'value'),\n State('active-thickness-{}'.format(4), 'value'),\n State('active-film-{}'.format(5), 'value'),\n State('active-thickness-{}'.format(5), 'value'),\n State('active-film-{}'.format(6), 'value'),\n State('active-thickness-{}'.format(6), 'value'),\n State('active-film-{}'.format(7), 'value'),\n State('active-thickness-{}'.format(7), 'value'),\n State('active-film-{}'.format(8), 'value'),\n State('active-thickness-{}'.format(8), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n# Callback for nine layer stack\n@simulator.callback(\n Output(generate_output_id_active(9), 'children'),\n [Input('calculate', 'n_clicks')],\n [State('active-nand-pairs', 'value'),\n State('active-film-{}'.format(1), 'value'),\n State('active-thickness-{}'.format(1), 'value'),\n State('active-film-{}'.format(2), 'value'),\n State('active-thickness-{}'.format(2), 'value'),\n State('active-film-{}'.format(3), 'value'),\n State('active-thickness-{}'.format(3), 'value'),\n State('active-film-{}'.format(4), 'value'),\n State('active-thickness-{}'.format(4), 'value'),\n State('active-film-{}'.format(5), 'value'),\n State('active-thickness-{}'.format(5), 'value'),\n State('active-film-{}'.format(6), 'value'),\n State('active-thickness-{}'.format(6), 'value'),\n State('active-film-{}'.format(7), 'value'),\n State('active-thickness-{}'.format(7), 'value'),\n State('active-film-{}'.format(8), 'value'),\n State('active-thickness-{}'.format(8), 'value'),\n State('active-film-{}'.format(9), 'value'),\n State('active-thickness-{}'.format(9), 'value')\n ])\ndef callback_data(n_clicks, *values):\n if n_clicks:\n return stack_calc(values)\n\n\ndef generate_data_output_id(n1, n2):\n return 'Data Output for {} active layers and {} trench layers'.format(n1, n2)\n\n\n@simulator.callback(\n Output('data-output', 'children'),\n [Input('calculate', 'n_clicks'),\n Input('active_nlayers_dropdown', 'value'),\n Input('trench_nlayers_dropdown', 'value')],\n [State('active-radio', 'value'),\n State('trench-radio', 'value')]\n)\ndef create_data_container(n_clicks, n_active, n_trench, active_stack_type, trench_stack_type):\n if n_clicks:\n if active_stack_type == 'nand':\n n_active = n_active + 2\n if trench_stack_type == 'nand':\n n_trench = n_trench + 2\n print(generate_data_output_id(n_active, n_trench))\n return html.Div(id=generate_data_output_id(n_active, n_trench))\n\ndef get_nkvals(mat_name):\n mat_id = Material.query.filter_by(name=mat_name).first().id\n nk_vals = NKValues.query.filter_by(material_id=mat_id).all()\n df = pd.DataFrame([(d.wavelength, d.n_value, d.k_value) for d in nk_vals], \n columns=['wavelength', 'n', 'k'])\n df['nk'] = df['n'] + (1j * df['k'])\n ### Handle nm from data instead of Angstrom\n ## TODO- make more robust\n if df.wavelength.min() > 1000:\n df['wavelength'] = df.wavelength /10\n return df\n\ndef compute_reflectance_1d(mat_names, thicknesses, medium):\n \"\"\"\n Compute reflectances of given film stack for fixed stack thickness\n\n input\n ======\n\n mat_names: list\n string names of film type\n thicknesses: list\n int values of film thicknesses in Angstroms\n medium: float\n index of refraction of medium on top of stack (air, water, etc)\n\n output\n ======\n\n pandas DataFrame\n columns: wavelength, reflectance\n\n \"\"\"\n\n mat_fns = []\n for mat in mat_names:\n mat_df = get_nkvals(mat)\n mat_fn = interp1d(mat_df.wavelength, mat_df.nk, kind='linear')\n mat_fns.append(mat_fn)\n medium_fn = lambda wavelength: medium\n si_df = get_nkvals('Si') ## change to make film passable\n si_fn = interp1d(si_df.wavelength, si_df.nk, kind='linear')\n reflectance = calc_reflectances(n_fn_list=[medium_fn] + mat_fns + [si_fn], \n d_list=[np.inf] + thicknesses + [np.inf], \n th_0=0, \n spectral_range=(260, 1700))\n r_df = pd.DataFrame(reflectance, columns=['wavelength', 'r'])\n return r_df\n\ndef compute_reflectance_2d(active_names, active_thicknesses, trench_names, trench_thicknessness, \n rr, medium):\n \"\"\"\n Compute reflectances of given film stack for variable thicknesses\n\n input\n ======\n\n mat_names: list\n string names of film type\n thicknesses: list\n int values of film thicknesses in Angstroms\n rr: numeric\n removal rate in A/min\n medium: float\n index of refraction of medium on top of stack (air, water, etc)\n\n output\n ======\n\n pandas DataFrame\n columns: wavelength, reflectance\n\n \"\"\"\n a_s = rr / 60 # removal rate in A/s\n top_layer = active\n\n active_fns = []\n trench_fns = []\n for mat_names, n_fn_list in zip((active_names, trench_names), (active_fns, trench_fns)):\n for mat in mat_names:\n mat_df = get_nkvals(mat)\n mat_fn = interp1d(mat_df.wavelength, mat_df.nk, kind='linear')\n fns.append(mat_fn)\n medium_fn = lambda wavelength: medium\n si_df = get_nkvals('Si') ## change to make film passable\n si_fn = interp1d(si_df.wavelength, si_df.nk, kind='linear')\n\n reflectance = calc_reflectances(n_fn_list=[medium_fn] + mat_fns + [si_fn], \n d_list=[np.inf] + current_thicknesses + [np.inf], \n th_0=0, \n spectral_range=(260, 1700))\n r_df = pd.DataFrame(reflectance, columns=['wavelength', '0s'])\n\n\n for sec in range(active_thicknesses[-1]/a_s): #\n thk_by_pol_time = thicknesses[:-1] + [thicknesses[-1] - sec*a_s]\n r_by_pol_time = calc_reflectances(n_fn_list=[medium_fn] + mat_fns + [si_fn], \n d_list=[np.inf] + thk_by_pol_time + [np.inf], \n th_0=0, \n spectral_range=(260, 1700))\n r_df['{}s'.format(sec)] = r_by_pol_time[:,1]\n return r_df\n\ndef combine_spectra(active_r, trench_r, pattern_density, medium):\n \n \"\"\" \n Compute aggregate spectra from active and trench reflectance \n as a function of pattern_density\n\n input\n ------\n \n active_r: pandas Dataframe with columns wavelength and r\n\n trench_r: pandas Dataframe with columns wavelength and r\n\n pattern_density: float, fraction of pattern mask containing active sites\n (between 0 and 1)\n\n output\n -------\n numpy array, computed reflectance with columns 0 and 1 as wavelength \n and reflectance respectively\n \n \"\"\"\n\n base_reflectance = trench_r.copy().values\n ref_si = compute_reflectance_1d(['Si'], [50000], medium)\n\n np.multiply(base_reflectance[:,1], (1 - (pattern_density/100)), base_reflectance[:,1])\n np.add(base_reflectance[:,1], active_r.r*(pattern_density/100), base_reflectance[:,1])\n np.divide(base_reflectance[:,1], ref_si.r, base_reflectance[:,1])\n\n return base_reflectance\n\n\n\ndef generate_callback(n1, n2):\n def callback_data(x1, x2, tab, medium, pattern_density, rr):\n\n t_start = time.perf_counter()\n\n active_films = ast.literal_eval(x1.split('*')[0])\n active_thks = [x/10 for x in ast.literal_eval(x1.split('*')[1])] # convert to nm for calc\n active_r = compute_reflectance_1d(active_films, active_thks, medium)\n\n\n trench_films = ast.literal_eval(x2.split('*')[0]) # convert to nm for calc\n trench_thks = [x/10 for x in ast.literal_eval(x2.split('*')[1])] # convert to nm for calc\n trench_r = compute_reflectance_1d(trench_films, trench_thks, medium)\n\n combined_spectra = combine_spectra(active_r, trench_r, pattern_density, medium)\n\n\n if tab == 'r-spectra':\n\n # active_films = ast.literal_eval(x1.split('*')[0])\n # active_thks = ast.literal_eval(x1.split('*')[1])\n # active_r = compute_reflectance_1d(active_films, active_thks, medium)\n\n # trench_films = ast.literal_eval(x2.split('*')[0])\n # trench_thks = ast.literal_eval(x2.split('*')[1])\n # trench_r = compute_reflectance_1d(trench_films, trench_thks, medium)\n\n # combined_spectra = combine_spectra(active_r, trench_r, pattern_density, medium)\n\n\n t_end = time.perf_counter()\n print(\"CALC TIME: \", (t_end - t_start), \"SECONDS\")\n print('Active films: {}'.format(active_films))\n print('Active thks: {}'.format(active_thks))\n print('Combined spectra:{}'.format(combined_spectra[:,:5]))\n graph = html.Div([\n dcc.Graph(\n figure={\n 'data': [\n {\n 'x':combined_spectra[:,0],\n 'y':combined_spectra[:,1],\n 'mode': 'line',\n 'name': 'Reflectance'\n }\n ],\n 'layout': go.Layout(\n xaxis=dict(\n title='wavelength',\n # range=[200, 1000]\n ),\n yaxis=dict(\n title='computed intensity',\n # range=[0, 2]\n )\n )\n },\n )\n ])\n elif tab == 'contour':\n rr = int(rr)\n\n # active_films = ast.literal_eval(x1.split('*')[0]) # convert to nm for calc\n # active_thks = [x/10 for x in ast.literal_eval(x1.split('*')[1])] # convert to nm for calc\n # active_r = compute_reflectance_1d(active_films, active_thks, medium)\n\n\n # trench_films = ast.literal_eval(x2.split('*')[0]) # convert to nm for calc\n # trench_thks = [x/10 for x in ast.literal_eval(x2.split('*')[1])] # convert to nm for calc\n # trench_r = compute_reflectance_1d(trench_films, trench_thks, medium)\n\n # spectra_matrix = combine_spectra(active_r, trench_r, pattern_density, medium)\n \n rr_as = rr / 60 # removal rate in A/s\n rr_nm = (rr / 10) / 60 # removal rate in nm/s\n\n # setting rr for testing purposes\n rr_nms = 10000 / 10 / 60\n\n t_start = time.perf_counter()\n print(active_thks[-1])\n starting_thk_active = active_thks[-1] # in nm\n starting_thk_trench = trench_thks[-1] # in nm\n\n # pol_time = int(starting_thk_active/rr_nms)\n # setting explicit int for testing\n pol_time = 7\n\n full_matrix = np.zeros((combined_spectra.shape[0], pol_time))\n\n for sec in range(pol_time):\n active_thks_sim = active_thks[:-1] + [(starting_thk_active - sec*rr_nms)]\n active_r_sim = compute_reflectance_1d(active_films, active_thks_sim, medium)\n\n trench_thks_sim = trench_thks[:-1] + [(starting_thk_trench - sec*rr_nms)]\n trench_r_sim = compute_reflectance_1d(trench_films, trench_thks_sim, medium)\n\n combined_spectra = combine_spectra(active_r_sim, trench_r_sim, pattern_density, medium)\n # spectra_matrix = np.hstack((spectra_matrix, combined_spectra[:,1]))\n # full_matrix.append(combined_spectra[:,1])\n # full_matrix[:, sec] = active_r_sim.r.values\n full_matrix[:, sec] = combined_spectra[:,1]\n\n t_stop = time.perf_counter()\n\n print('Comp time: {:.2f}'.format(t_stop - t_start))\n\n # for x axis labels\n pol_time = active_thks[-1] / rr_nm\n print('Active thks: {}'.format(active_thks[-1]))\n print('RR nm/s: {}'.format(rr_nm))\n print('pol time: {}'.format(pol_time))\n x_labels = list(range(0, int(pol_time), full_matrix.shape[1])),\n print('x-labels: {}'.format(x_labels))\n print('full-matrix-shape: {}'.format(full_matrix.shape))\n\n graph = html.Div([\n dcc.Graph(\n figure={\n 'data': [\n go.Contour(\n z=np.array(full_matrix),\n # x=list(range(int((active_thks[-1]/rr_as) * 60))), # testing rr_nms\n # x=list(range(0, int(pol_time), full_matrix.shape[1])),\n x=[0, 10, 20, 30, 40, 50],\n y=combined_spectra[:,0],\n colorscale='Jet',\n contours=dict(\n coloring='heatmap'\n )\n )\n ],\n 'layout': go.Layout(\n xaxis=dict(\n title='Polish Time (s)',\n # range=[200, 1000]\n ),\n yaxis=dict(\n title='Wavelength',\n # range=[0, 2]\n )\n )\n },\n )\n ])\n pd.DataFrame(full_matrix).to_csv('spectra_matrix.csv')\n \n return graph\n return callback_data\n\n\n@simulator.callback(\n Output('dummy-graph', 'style'),\n [Input('data-output', 'children')]\n)\ndef turnoff_dummy_plot(output):\n if output:\n return {'display':'none'}\n\n@simulator.callback(\n Output('dummy-graph', 'children'),\n [Input('chart-tabs', 'value')]\n)\ndef tab_callback(tab):\n if tab == 'r-spectra':\n return dcc.Graph(\n figure={\n 'data':[],\n 'layout': go.Layout(\n xaxis=dict(\n title='wavelength',\n range=[200, 1500]\n ),\n yaxis=dict(\n title='computed intensity',\n range=[0, 2]\n )\n )\n },\n ),\n elif tab == 'contour':\n return dcc.Graph(\n figure=go.Figure(\n data=[\n go.Contour(\n )\n ],\n # layout=go.Layout(\n # plot_bgcolor='midnightblue'\n )\n )\n\n@simulator.callback(\n Output('removal-rate', 'disabled'),\n [Input('chart-tabs', 'value')]\n)\ndef disable_rr_input_for_2dplot(tab):\n if tab == 'r-spectra':\n return True\n\n\n@simulator.callback(\n Output('removal-rate', 'style'),\n [Input('chart-tabs', 'value')]\n)\ndef disable_rr_input_for_2dplot(tab):\n if tab == 'r-spectra':\n return {'color':'grey', 'textAlign':'center', 'width':'75'}\n else:\n return {'textAlign':'center', 'width':'75'}\n\n\n@simulator.callback(\n Output('removal-rate', 'value'),\n [Input('chart-tabs', 'value')]\n)\ndef disable_rr_input_for_2dplot(tab):\n if tab == 'r-spectra':\n return \"n/a\"\n elif tab == 'contour':\n return 1000\n\n\n## Callback to put all input data into one div \nfor val1, val2 in itertools.product(np.arange(1, max_layers), np.arange(1, max_layers)):\n simulator.callback(\n Output(generate_data_output_id(val1, val2), 'children'),\n [Input(generate_output_id_active(val1), 'children'), \n Input(generate_output_id_trench(val2), 'children'),\n Input('chart-tabs', 'value')],\n [State('medium', 'value'),\n State('pattern-density-slider', 'value'),\n State('removal-rate', 'value')])(\n generate_callback(val1, val2)\n )\n # simulator.callback(\n # Output('graph', 'figure'),\n # [Input(generate_data_output_id(val1, val2), 'children')])(\n # callback_plot(val1, val2)\n # )\n","sub_path":"app/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":59076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"299255067","text":"from sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\n\n\ndef preprocess(dataset):\n X = dataset.iloc[:, 3:13].values\n y = dataset.iloc[:, 13].values\n\n label_encoder_X_1 = LabelEncoder()\n X[:, 1] = label_encoder_X_1.fit_transform(X[:, 1])\n label_encoder_X_2 = LabelEncoder()\n X[:, 2] = label_encoder_X_2.fit_transform(X[:, 2])\n\n one_hot_encoder = OneHotEncoder(categorical_features=[1])\n X = one_hot_encoder.fit_transform(X).toarray()\n X = X[:, 1:]\n\n X_train, X_test, y_train, y_test = train_test_split(X, y,\n test_size=0.2,\n random_state=0)\n\n sc = StandardScaler()\n X_train = sc.fit_transform(X_train)\n X_test = sc.fit_transform(X_test)\n\n return X_train, X_test, y_train, y_test\n","sub_path":"artificial_neural_networks/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"328424461","text":"# -*- encoding: utf-8 -*-\n__author__ = 'pahaz'\n\nfrom bottle import route, run, template, response\nimport requests as r\n\n\n@route('/inst///')\ndef inst(lat, lng):\n url = 'https://api.instagram.com/v1/media/search?lat={lat:0.6f}&lng={lng:0.6f}&client_id=3d56e75ea0ae4b96aa459aa22530a519' \\\n .format(lng=float(lng), lat=float(lat))\n rez = r.get(url)\n\n response.content_type = 'application/json; charset=utf-8'\n return rez.content\n\n\n@route('/')\ndef index():\n a = open('index.html')\n return a.read()\n\n\nrun(host='localhost', port=80)\n","sub_path":"intagram_spyer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"511682650","text":"import pandas as pd\nfrom fbprophet import Prophet\n\ndef forecast(params):\n df = pd.io.json.json_normalize(params.get('history'))\n m = Prophet()\n m.fit(df)\n \n future = m.make_future_dataframe(periods=params.get('periods'), freq=params.get('freq'))\n return m.predict(future)\n","sub_path":"app/_prophet.py","file_name":"_prophet.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"311959280","text":"'''\nXML is acronym of eXtensible Markup Language\n\n Element : or \n Text : {{ String }} \n Contents : {{Content}} \n Property : {{Contents}} or \n Root Tag : Must be just one\n'''\n\nfrom bs4 import BeautifulSoup as bs\nimport urllib.request \n\nurl = 'http://www.weather.go.kr/weather/forecast/mid-term-rss3.jsp?stnId=109'\n\nresponse = urllib.request.urlopen(url)\n\nxml = response.read()\n\nsoup = bs(xml, 'html.parser')\n\nlocation = soup.find('city').text\ndatas = soup.find_all('data')\n\nfor data in datas:\n day = data.find('tmef').text\n weather = data.find('wf').text\n min_temperature = data.find('tmn').text\n max_temperature = data.find('tmx').text\n \n print(\n '{} {}의 날씨는 {}이며, 최저 온도는 {} 최고 온도는 {} 입니다.'.format(location, day, weather, min_temperature, max_temperature)\n )\n\nprint(location)","sub_path":"scraping/xml_practice.py","file_name":"xml_practice.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"648758686","text":"# coding=utf-8\nfrom random import randint\n\nprint(' 猜数字')\nprint('请输入数字:')\nnum = raw_input()\nvalue = randint(0, 9999)\nfloor = 0\nceil = 9999\n\nwhile True:\n if num.isdigit():\n if int(num) > value:\n ceil = min(ceil, int(num))\n elif int(num) < value:\n floor = max(floor, int(num))\n elif int(num) == value:\n msg = '猜对啦!该数为:{}'.format(value)\n print(msg)\n break\n else:\n print('请输入数字哦!')\n num = raw_input()\n continue\n\n msg = '所猜数字介于{}--{}之间,加油哦!'.format(floor, ceil)\n print(msg)\n num = raw_input()\n","sub_path":"MyFirstPython/src/GuessNum.py","file_name":"GuessNum.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"17388510","text":"def convertToBase7(num):\n \"\"\"\n :param num: int\n :return: str\n \"\"\"\n if num == 0:\n return '0'\n negative = False\n if num < 0:\n negative = True\n num *= -1\n ret = list()\n while num:\n ret.append(str(num % 7))\n num /= 7\n return ('-' if negative else '') + ''.join(ret[::-1])\n","sub_path":"normal/504_base_7.py","file_name":"504_base_7.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"216660268","text":"directions_list = open('in.txt').read().split('\\n')\n\nrow = 1\ncol = 1\nkeypad = [['1', '2', '3'], ['4', '5', '6'], ['7', '8','9']\n ]\ncode = \"\"\nfor directions in directions_list:\n for char in directions:\n if char == 'R':\n if col != 2:\n col += 1\n\n if char == 'L':\n if col != 0:\n col -= 1\n\n if char == 'D':\n if row != 2:\n row += 1\n\n if char == 'U':\n if row != 0:\n row -= 1\n\n code += keypad[row][col]\n\nprint(\"Code: \" + code)\n","sub_path":"day2/solve1.py","file_name":"solve1.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395770001","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nAPI 帐号注册\n@package:\n@file: register.py\n@author: yuiitsu\n@time: 2020-05-24 22:42\n\n\nrequest body:\n {\n \"account\": \"帐户名(*)\"\n \"password\": \"密码(*)\"\n \"confirm_password\": \"确认密码(*)\"\n }\n\nreturn:\n {\n \"code\": 0,\n 'msg\": \"创建成功\",\n \"data\": {\n \"admin_id\": \"帐号ID\"\n }\n }\n\"\"\"\nfrom base.base import Base\n\n\nclass Controller(Base):\n\n async def post(self):\n params = self.params()\n result = yield self.cs('user.admin.auth.service', 'register', params)\n self.out(result)\n","sub_path":"src/module/v1/user/admin/auth/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"400779486","text":"import random\nimport bisect\nimport sys\n\nclass GrammarRule:\n\n def __init__(self, key):\n self.key = key\n self.derivations = []\n self.sumOfDerivationWeights = 0\n\n def isTerminal(self):\n return len(self.derivations) == 0\n\n # Each derivation is an array of rules\n def addDerivation(self, derivation):\n self.derivations.append(derivation)\n self.sumOfDerivationWeights = self.sumOfDerivationWeights + derivation.weight\n\n def chooseRandomDerivation(self):\n cdfValues = []\n cumulativeSum = 0\n\n for derivation in self.derivations:\n cumulativeSum = cumulativeSum + derivation.weight\n cdfValues.append(cumulativeSum / self.sumOfDerivationWeights)\n\n randomInteger = random.random()\n choiceIndex = bisect.bisect(cdfValues, randomInteger)\n return self.derivations[choiceIndex]\n\n def generateSentence(self):\n if self.isTerminal() == True:\n return self.key\n\n sentence = \"\"\n derivation = self.chooseRandomDerivation()\n for rule in derivation.rules:\n sentence += rule.generateSentence() + \" \"\n\n return sentence\n\nclass Derivation:\n def __init__(self, ruleDict, ruleKeys, weight):\n \"\"\"\n ruleDict is a dictionary which stores rules already defined in the\n grammar to which the derivation being constructed belongs\n\n ruleKeys is an array of keys of the rules which make up the\n derivation being constructed\n\n weight is the weight assigned to the given rules which defines\n the relative probability of this derivation being randomly chosen\n from amongst all derivations for the rule from which the\n derivation is derivable\n \"\"\"\n self.weight = weight\n self.rules = []\n for key in ruleKeys:\n if key in ruleDict:\n rule = ruleDict[key]\n else:\n rule = GrammarRule(key)\n ruleDict[key] = rule\n self.rules.append(rule)\n\n\nSTART_SYMBOL_KEY = \"ROOT\"\nCOMMENT_SYMBOL = \"#\"\n\ndef validateTokens(tokens, lineno):\n if len(tokens) < 3:\n print(\"[{}] Syntax error: invalid number of tokens\".format(lineno))\n sys.exit(1)\n try:\n weight = float(tokens[0])\n if weight <= 0.:\n print(\"[{}] Syntax error: Derivation weight must greater than 0\".format(lineno))\n sys.exit(1)\n except ValueError:\n print(\"[{}] Syntax error: First token on line must be derivation weight\".format(lineno))\n sys.exit(1)\n\ndef parseTokens(line):\n \"\"\"\n Pre: the first token in the line is not the comment token\n \"\"\"\n line.strip()\n commentTokenIdx = line.find(COMMENT_SYMBOL)\n if commentTokenIdx != -1:\n line = line[:commentTokenIdx-1]\n return line.split()\n\ndef parseLine(ruleDict, line, lineno):\n if line == \"\" or line[0] == COMMENT_SYMBOL:\n return\n\n tokens = parseTokens(line)\n print(\"{}: {}\".format(lineno, tokens))\n validateTokens(tokens, lineno)\n weight = float(tokens[0])\n key = tokens[1]\n rules = tokens[2:]\n derivation = Derivation(ruleDict, rules, weight)\n ruleDict[key].addDerivation(derivation)\n\ndef generateGrammar(grammarFile):\n ruleDict = {}\n ruleDict[START_SYMBOL_KEY] = GrammarRule(START_SYMBOL_KEY)\n\n try:\n with open(grammarFile) as f:\n lineno = -1\n for line in f:\n lineno = lineno + 1\n line = line.strip()\n parseLine(ruleDict, line, lineno)\n\n f.close()\n return ruleDict\n except IOError:\n print(\"Could not open grammar file.\")\n usage()\n sys.exit(1)\n\ndef main(argv):\n if len(argv) != 2 or int(argv[1]) <= 0:\n usage()\n\n grammarFile = argv[0]\n try:\n sentenceCount = int(argv[1])\n except ValueError:\n usage()\n sys.exit(1)\n\n ruleDict = generateGrammar(grammarFile)\n\n for i in range(0, sentenceCount):\n print(ruleDict[START_SYMBOL_KEY].generateSentence())\n\ndef usage():\n print(\"Usage: ./randsent path/to/grammar/file number_of_sentences_to_generate\")\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n\n\n","sub_path":"nlp_jh_a1/randsent.py","file_name":"randsent.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"613866132","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport sys\nimport glob\nimport serial\nimport time\nimport socket\n\n# Задаем адрес сервера\nSERVER_ADDRESS = ('0.0.0.0', 6767)\n\n# Настраиваем сокет\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.bind(SERVER_ADDRESS)\nserver_socket.listen(1)\nprint('Door and light control server is working...')\n\n\ndef serial_ports():\n ports = glob.glob('/dev/ttyUSB*')\n\n result = ports\n return result\n\n\n# types: Sonar - sonar arduino, Box - box controlling arduino\n# returns serial connection\ndef connect_to():\n while 1:\n arduinos = serial_ports()\n if arduinos:\n nano = serial.Serial(arduinos[0], 115200)\n return nano\n else:\n print(\"Please, connect nano to robot\")\n time.sleep(10)\n\n\ndef action(i, nano):\n nano.write(str(i).encode())\n door = nano.readline().strip().decode(\"utf-8\")\n if door:\n return True\n else:\n return False\n\n\nif __name__ == \"__main__\":\n\n nano = None\n nano = connect_to()\n while True:\n connection, address = server_socket.accept()\n print(\"new connection from {address}\".format(address=address))\n\n data = connection.recv(1024).decode(\"utf-8\")\n\n print(str(data))\n if nano:\n if action(data, nano):\n connection.send(bytes(str(data), encoding='UTF-8'))\n else:\n connection.send(bytes(str(\"Nano is disconnected\"), encoding='UTF-8'))\n else:\n connection.send(bytes(str(data), encoding='UTF-8'))\n\n connection.close()\n","sub_path":"control/tcp-server.py","file_name":"tcp-server.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"431810868","text":"import warnings\r\nwarnings.filterwarnings('ignore')\r\nimport pandas as pd\r\nimport re\r\n\r\nrestaurants = pd.read_csv('restaurants_AZ.csv')\r\nc = restaurants['categories']\r\ncategories = []\r\n\r\n\r\nfor i in range(0, 2867):\r\n d = re.findall(r\"'(.*?)'\", c[i], re.DOTALL)\r\n for element in d:\r\n if element not in categories:\r\n categories.append(element)\r\ncategories_df = pd.DataFrame(categories)\r\ncategories_df.to_csv('categories_AZ.csv', encoding='utf-8', index=False)\r\n","sub_path":"categories_AZ.py","file_name":"categories_AZ.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"446745114","text":"'''\n对requests中的get、post的方法进行一层封装\n1.增加异常处理\n2.增加日志打印\n3.创建一个session,确保能自动管理cookie\n'''\nimport requests\nclass BaseRequests:\n def __init__(self):\n # 创建一个session,赋值给属性session\n self.session = requests.session()\n def get(self,url,**kwargs):\n try:\n # 使用session的方式调用requests中的get接口\n r = self.session.get(url,**kwargs)\n print(f\"发送get请求:{url},参数:{kwargs}成功\")\n return r\n except Exception as e:\n print(f\"发送get请求:{url},参数:{kwargs}异常,异常信息为:{e}\")\n def post(self,url,**kwargs):\n try:\n # 使用session的方式调用requests中的get接口\n r = self.session.post(url,**kwargs)\n print(f\"发送post请求:{url},参数:{kwargs}成功\")\n return r\n except Exception as e:\n print(f\"发送post请求:{url},参数:{kwargs}异常,异常信息为:{e}\")\nif __name__ == '__main__':\n r = BaseRequests().get(\"http://www.httpbin.org/get?username=root&pwd=123123\")\n print(r.text)\n canshu = {\"username\":\"root\",\"pwd\":123123}\n r1 = BaseRequests().post(\"http://www.httpbin.org\",data=canshu)\n print(r1.text)\n\n\n\n\n","sub_path":"ZongHe/caw/BaseRequests.py","file_name":"BaseRequests.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"109221768","text":"import numpy as np\nimport matplotlib.pylab as plt\nfrom collections import defaultdict\nref = defaultdict(list)\n# datos=np.genfromtxt(\"datosej11.txt\",\"r\")\ndatos=open(\"datosej11.txt\",\"r\")\nfor i in datos:\n a=i.split()\n a[0]=float(a[0])\n a[1]=int(a[1])\n ref[a[1]].append(a[0])\navg=np.zeros(len(ref.keys()))\nfor i in range(len(ref.keys())):\n avg[i]=sum(ref[i+1])/len(ref[i+1])\nX=np.arange(1,len(ref.keys())+1)\nmaximo=np.argmax(avg)\nprint(X[maximo])\nplt.plot(X,avg,color=\"firebrick\")\nplt.title(\"Verosimilitud vs Grado del ajuste\")\nplt.xlabel(r\"Grados\")\nplt.ylabel(r\"$P(D|X)$\")\nplt.savefig(\"pdfAjuste.pdf\")\nplt.savefig(\"average.pdf\")\nplt.show()\n","sub_path":"Otros Codigos/Average11.py","file_name":"Average11.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535614747","text":"#Q.1- Write a Python program to read last n lines of a file\n\ndef lastnlines(f, n):\n with open(f) as file:\n print(\"last lines from file : \",f)\n for line in (file.readlines()[-n:]):\n print(line, end=\"\")\n\nname = \"Home/Documents/python/acadview/workspace/hello-git/assignment14/assign14.txt\"\nn = int(input('Type the number of n last lines to read : '))\ntry:\n lastnlines(name,n)\nexcept():\n\tprint('File Error')\n\n\n\n\n\n#Q.2- Write a Python program to count the frequency of words in a file.\n\nfrom collections import Counter\ndef word_count(file):\n with open(file) as f:\n return Counter(f.read().split())\n\nprint(\"Words with their frequency are : \\n\",word_count(\"assign14.txt\"))\n\n\n\n\n\n#Q.3- Write a Python program to copy the contents of a file to another file \n\nimport os\nos.system('copy assign14.txt assignmen14.txt')\n\n\n\n\n\n\n# Q.4- Write a Python program to combine each line from first file with the corresponding line in second file.\n\nwith open('assign14.txt') as fh1, open('assignmen14.txt') as fh2:\n for line1, line2 in zip(fh1, fh2):\n print(line1+line2)\n \n\n\n\n#Q.5- Write a Python program to write 10 random numbers into a file. Read the file and then sort the numbers and then store it to another file.\n\nimport random\n\nb=[]\nwith open(\"assign14.txt\", \"w\") as f:\n for i in range(10):\n a =random.random()\n b.append(a)\n f.write(str(a) + \"\\n\")\n\na = b.sort()\n\nwith open(\"assignmen14.txt\", \"w\") as f:\n for i in range(len(b)):\n f.write(str(b[i]) + \"\\n\")\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"hello-git/acadview/assignment/assignment14/assign14.py","file_name":"assign14.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"175762035","text":"#\n# CAMP\n#\n# Copyright (C) 2017 -- 2019 SINTEF Digital\n# All rights reserved.\n#\n# This software may be modified and distributed under the terms\n# of the MIT license. See the LICENSE file for details.\n#\n\n\n\nfrom __future__ import unicode_literals\n\nfrom camp.entities.model import TestSettings\n\nfrom unittest import TestCase\n\n\n\nclass TheTestSettingsShould(TestCase):\n\n\n def setUp(self):\n self._command = \"this is a Shell command\"\n self._report_format = \"JUnit\"\n self._report_location = \"in/this/directory\"\n self._report_pattern = \"TEST*.xml\"\n self._settings = TestSettings(\n self._command,\n self._report_format,\n self._report_location,\n self._report_pattern\n )\n\n\n def test_expose_a_command_to_run_the_tests(self):\n self.assertEqual(self._command,\n self._settings.test_command)\n\n\n def test_expose_the_format_of_test_reports(self):\n self.assertEqual(self._report_format,\n self._settings.report_format)\n\n\n def test_expose_the_location_of_the_reports(self):\n self.assertEqual(self._report_location,\n self._settings.report_location)\n\n\n def test_expose_a_pattern_to_detect_test_report(self):\n self.assertEqual(self._report_pattern,\n self._settings.report_pattern)\n","sub_path":"tests/entities/test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"457666304","text":"import os\nimport pickle\nfrom loading import Loader\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass Inputing(object):\n def __init__(self):\n self.pickledir = './pickles'\n self.loader = Loader()\n\n def input_train(self):\n pickle_file_dir = os.path.join(self.pickledir, 'train.txt')\n if not os.path.exists(pickle_file_dir):\n df = self.loader.train_loader()\n with open(pickle_file_dir, 'wb') as f:\n pickle.dump(df, f)\n\n else:\n with open(pickle_file_dir, 'rb') as f:\n df = pickle.load(f)\n print(df)\n print(df.columns)\n input_examples = df.apply(lambda x: InputExample(guid=x['index'],\n text_a=x['claim'],\n text_b=x['evidence'],\n label=x['label']), axis=1)\n return input_examples\n\n\n def input_dev(self):\n pickle_file_dir = os.path.join(self.pickledir, 'dev.txt')\n if not os.path.exists(pickle_file_dir):\n df = self.loader.dev_loader()\n with open(pickle_file_dir, 'wb') as f:\n pickle.dump(df, f)\n\n else:\n with open(pickle_file_dir, 'rb') as f:\n df = pickle.load(f)\n input_examples = df.apply(lambda x: InputExample(guid=x['index'],\n text_a=x['claim'],\n text_b=x['evidence'],\n label=x['label']), axis=1)\n return input_examples\n\n def input_test(self):\n pickle_file_dir = os.path.join(self.pickledir, 'test.txt')\n if not os.path.exists(pickle_file_dir):\n df = self.loader.test_loader()\n with open(pickle_file_dir, 'wb') as f:\n pickle.dump(df, f)\n else:\n with open(pickle_file_dir, 'rb') as f:\n df = pickle.load(f)\n input_examples = df.apply(lambda x: InputExample(guid=x['index'],\n text_a=x['claim'],\n text_b=x['evidence'],\n label='NOT ENOUGH INFO'), axis=1)\n return input_examples\n\ninputformatting = Inputing()\n#inputformatting.input_train()\n#inputformatting.input_dev()\ninputformatting.input_test()\n","sub_path":"input_data.py","file_name":"input_data.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"477048458","text":"import rdflib\nfrom ontario.rdfmt import MTManager\nfrom ontario.rdfmt.utils import contactRDFSource\n\n__author__ = \"Kemele M. Endris\"\n\n\nprefixes = \"\"\"\n @prefix rr: .\n @prefix rml: .\n @prefix ql: .\n @prefix rdfs: .\n @prefix rdf: .\n @prefix rev: .\n @prefix schema: .\n @prefix xsd: .\n @prefix base: .\n @prefix iasis: .\n @prefix hydra : .\n\"\"\"\n\n\nclass ReferenceMap(object):\n def __init__(self, name, datatype=\"xsd:string\", lang=\"en\"):\n self.name = name\n self.datatype = datatype\n self.lang = lang\n\n\nclass RMLPredicate(object):\n def __init__(self, predicate, refmap, prefix=None, isconstant=False):\n self.predicate = predicate\n self.refmap = refmap\n self.prefix = prefix\n self.isconstant = isconstant\n\n def __repr__(self):\n return \"\\t\" + self.predicate + \" => \" + str(self.refmap)\n\n\nclass RMLSubject(object):\n def __init__(self, id, logicalsource, subjecttemplate, subjectclass=\"rdfs:Class\", predicates=[], iterator='$'):\n self.id = id\n self.logicalsource = logicalsource\n if iterator is None or iterator == 'None':\n iterator = '$'\n self.iterator = iterator\n self.subjecttemplate = subjecttemplate\n self.subjectclass = subjectclass\n self.predicates = predicates\n\n def __repr__(self):\n rep = \"<\" + self.id + \"> rml:source \" + self.logicalsource + \"; rr:class \" + self.subjectclass + \"; rr:iterator: \" + self.iterator + \"; \\n \"\n for p in self.predicates:\n rep += str(p) + \";\\n\"\n\n return rep[:-2] + \". \"\n\n def __eq__(self, other):\n return self.id == other.id\n\n\nclass RMLMapping(object):\n\n prefix = \"prefix rr: \" \\\n \"prefix rml: \" \\\n \"prefix ql: \" \\\n \"prefix bsbm: \"\n\n def __init__(self, mapfile, subjectmaps={}):\n self.mapingfile = mapfile\n self.subjectmaps = subjectmaps\n\n def __repr__(self):\n rep = \"Mapping file: \" + self.mapingfile + \" \\n\"\n for s in self.subjectmaps:\n rep += str(s) + \"\\n -------------------------------------------------\\n\"\n return rep\n\n def loadAllMappings(self):\n return self.queryMappings()\n\n def getMapping(self, subjectclass):\n\n if len(self.subjectmaps) > 0:\n subjj = self.subjectmaps[subjectclass]\n #subjj = [s for s in self.subjectmaps if s.subjectclass == subjectclass]\n return subjj\n else:\n return self.queryMappings(subjectclass)\n\n def queryMappings(self, subjectclass=None):\n g = rdflib.Graph()\n g.load(self.mapingfile, format='n3')\n\n subj = \"?subjectclass\"\n if subjectclass is not None:\n subj = \" <\" + subjectclass + \"> \"\n\n query = self.prefix + \" SELECT * \" \\\n \" WHERE {\" \\\n \"?s rml:logicalSource ?source. \" \\\n \"?source rml:source ?sourceuri. \" \\\n \"?s rr:subjectMap ?smap. \" \\\n \"?smap rr:template ?subjtemplate. \" \\\n \"?smap rr:class \" + subj + \". \" \\\n \"?s rr:predicateObjectMap ?pmap. \" \\\n \"?pmap rr:predicate ?predicate. \" \\\n \" ?pmap rr:objectMap ?pomap. \" \\\n \"?pomap rml:reference ?headername \" \\\n \" OPTIONAL{?source rml:iterator ?iterator } \" \\\n \" OPTIONAL{?pomap rr:datatype ?datatype } \" \\\n \" OPTIONAL{?pomap rr:language ?lang}\" \\\n \" }\"\n res = g.query(query)\n\n for row in res:\n datatype = row.datatype\n if not datatype or len(datatype) == 0:\n datatype = \"xsd:string\"\n\n lang = row.lang\n if not lang or len(lang) == 0:\n lang = 'en'\n\n header = ReferenceMap(str(row.headername), str(datatype), str(lang))\n pred = RMLPredicate(\"<\"+str(row.predicate)+\">\", header)\n\n if hasattr(row, 'subjectclass'):# and row.subjectclass:\n subjectclass = row.subjectclass\n if hasattr(row, 'iterator'):\n subject = RMLSubject(str(row.s), str(row.sourceuri), str(row.subjtemplate), \"<\"+str(subjectclass)+\">\", [pred], iterator=str(row.iterator))\n else:\n subject = RMLSubject(str(row.s), str(row.sourceuri), str(row.subjtemplate),\n \"<\" + str(subjectclass) + \">\", [pred])\n\n if str(subjectclass) not in self.subjectmaps:\n self.subjectmaps[str(subjectclass)] = [subject]\n else:\n for sub in self.subjectmaps[str(subjectclass)]:\n if sub.id == str(row.s):\n sub.predicates.append(pred)\n\n if subj != \"?subjectclass\":\n if str(subjectclass) in self.subjectmaps:\n return self.subjectmaps[str(subjectclass)]\n else:\n return {}\n else:\n return self.subjectmaps\n\n\nclass RMLManagerX(object):\n\n prefix = \"prefix rr: \" \\\n \"prefix rml: \" \\\n \"prefix ql: \" \\\n \"prefix bsbm: \"\n\n def __init__(self, mtendpoint, federation, dsid):\n self.mtmgr = MTManager(mtendpoint, \"dba\", \"dba\", federation)\n self.datasource = self.mtmgr.get_data_source(dsid)\n self.mtendpoint = mtendpoint\n self.federation = federation\n self.subjectmaps = {}\n\n def __repr__(self):\n rep = \"Data Source: \" + self.datasource.url + \" \\n\"\n for s in self.subjectmaps:\n rep += str(s) + \"\\n -------------------------------------------------\\n\"\n return rep\n\n def loadAllMappings(self):\n return self.queryMappings()\n\n def getMapping(self, subjectclass):\n\n if len(self.subjectmaps) > 0:\n subjj = self.subjectmaps[subjectclass]\n #subjj = [s for s in self.subjectmaps if s.subjectclass == subjectclass]\n return subjj\n else:\n return self.queryMappings(subjectclass)\n\n def queryMappings(self, subjectclass=None):\n\n subj = \"?subjectclass\"\n if subjectclass is not None:\n subj = \" <\" + subjectclass + \"> \"\n\n query = self.prefix + \" SELECT * \" \\\n \" WHERE {\" \\\n \"?s rml:logicalSource ?source. \" \\\n \"?source rml:source ?sourceuri. \" \\\n \"?s rr:subjectMap ?smap. \" \\\n \"?smap rr:template ?subjtemplate. \" \\\n \"?smap rr:class \" + subj + \". \" \\\n \"?s rr:predicateObjectMap ?pmap. \" \\\n \"?pmap rr:predicate ?predicate. \" \\\n \" ?pmap rr:objectMap ?pomap. \" \\\n \" ?pomap rml:reference ?headername \" \\\n \" OPTIONAL{?source rml:iterator ?iterator } \" \\\n \" OPTIONAL{?pomap rr:datatype ?datatype } \" \\\n \" OPTIONAL{?pomap rr:language ?lang}\" \\\n \" }\"\n res, card = contactRDFSource(query, self.mtendpoint)\n if res is None:\n return {}\n\n for row in res:\n datatype = \"xsd:string\"\n if 'datatype' in row:\n datatype = row['datatype']\n\n lang = 'en'\n if 'lang' in row:\n lang = row['lang']\n\n header = ReferenceMap(str(row['headername']), str(datatype), str(lang))\n pred = RMLPredicate(\"<\"+str(row['predicate'])+\">\", header)\n\n if 'subjectclass'in row:\n subjectclass = row['subjectclass']\n if 'iterator' in row:\n subject = RMLSubject(str(row['s']), str(row['sourceuri']), str(row['subjtemplate']), \"<\"+str(subjectclass)+\">\", [pred], iterator=str(row['iterator']))\n else:\n subject = RMLSubject(str(row['s']), str(row['sourceuri']), str(row['subjtemplate']),\n \"<\" + str(subjectclass) + \">\", [pred])\n\n if str(subjectclass) not in self.subjectmaps:\n self.subjectmaps[str(subjectclass)] = [subject]\n else:\n for sub in self.subjectmaps[str(subjectclass)]:\n if sub.id == str(row['s']):\n sub.predicates.append(pred)\n\n if subj != \"?subjectclass\":\n if str(subjectclass) in self.subjectmaps:\n return self.subjectmaps[str(subjectclass)]\n else:\n return {}\n else:\n return self.subjectmaps\n\n\nif __name__ == \"__main__\":\n mapping = RMLManager(\"http://node2.research.tib.eu:1300/sparql\", \"http://tib.eu/dsdl/ontario/g/ontariofed\", \"http://tib.eu/dsdl/ontario/resource/COSMIC\")\n mapping.loadAllMappings()\n import pprint\n pprint.pprint(mapping.subjectmaps)","sub_path":"ontario/mapping/RMLMapping.py","file_name":"RMLMapping.py","file_ext":"py","file_size_in_byte":9772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"190208333","text":"import network\nfrom machine import I2C, Pin\nimport time\nimport urequests\nimport json\nimport ubinascii\n\nprint(\"\\nRUNNING MAIN!\\n\")\n\n\ndef get_mac_address():\n mac = ubinascii.hexlify(network.WLAN().config('mac')).decode()\n return mac\n\n\ndef get_sensor_data():\n \"\"\"Return sensor temperature and humidity.\"\"\"\n # Send measurement command\n payload = bytes([0x06])\n i2c.writeto_mem(address, 0x2C, payload)\n\n time.sleep(0.5)\n\n # Read data back\n data = i2c.readfrom_mem(address, 0x00, 6)\n\n # Convert data\n temp = data[0] * 256 + data[1]\n cTemp = -45 + (175 * temp / 65535.0)\n humidity = 100 * (data[3] * 256 + data[4]) / 65535.0\n\n return {\n \"temperature\": cTemp,\n \"humidity\": humidity\n }\n\n\ndef post_data(data):\n data = json.dumps(data).encode('utf-8')\n urequests.post('http://192.168.1.23:5000/api', data=data)\n print(\"Posted new sensor data\")\n\n\nprint(\"Starting..\")\n\n# SHT3X Sensor\ni2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000)\n\naddress = 68\n\nif (address not in i2c.scan()):\n raise Exception(\"SENSOR NOT FOUND!\")\n\ntime.sleep(1)\n\nwhile True:\n\n data = get_sensor_data()\n\n device_id = get_mac_address()\n data[\"device_id\"] = device_id\n\n post_data(data=data)\n\n print(\"Uploaded data.\")\n time.sleep(10)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"448233218","text":"import torch\nfrom collections import deque\nimport matplotlib.pyplot as plt\nfrom unityagents import UnityEnvironment\nimport numpy as np\nimport time\nfrom ddpg_agent import Agent\nimport os\n\nenv = UnityEnvironment(file_name=\"Tennis.app\")\n\n# get the default brain\nbrain_name = env.brain_names[0]\nbrain = env.brains[brain_name]\n\n# reset the environment\nenv_info = env.reset(train_mode=True)[brain_name]\n\n# number of agents\nnum_agents = len(env_info.agents)\nprint('Number of agents:', num_agents)\n\n# size of each action\naction_size = brain.vector_action_space_size\nprint('Size of each action:', action_size)\n\n# examine the state space\nstates = env_info.vector_observations\nstate_size = states.shape[1]\nprint('There are {} agents. Each observes a state with length: {}'.format(states.shape[0], state_size))\nprint('The state for the first agent looks like:', states[0])\n\nagent1 = Agent(state_size=state_size, action_size=action_size, random_seed=42,\n actor_filepath = 'trained_weights/checkpoint_actor1.pth',\n critic_filepath = 'trained_weights/checkpoint_critic1.pth')\nagent2 = Agent(state_size=state_size, action_size=action_size, random_seed=42, memory = agent1.memory,\n actor_filepath = 'trained_weights/checkpoint_actor2.pth',\n critic_filepath = 'trained_weights/checkpoint_critic2.pth')\n\nenv_info = env.reset(train_mode=False)[brain_name] # reset the environment\nstates = env_info.vector_observations # get the current state (for each agent)\n\n\nfor i in range(10):\n scores = np.zeros(num_agents) # initialize the score (for each agent)\n while True:\n action1 = agent1.act(states[0], add_noise = False)\n action2 = agent2.act(states[1], add_noise = False)\n actions = [action1, action2]\n env_info = env.step(actions)[brain_name] # send all actions to tne environment\n next_states = env_info.vector_observations # get next state (for each agent)\n rewards = env_info.rewards # get reward (for each agent)\n dones = env_info.local_done # see if episode finished\n scores += env_info.rewards # update the score (for each agent)\n states = next_states # roll over states to next time step\n if np.any(dones): # exit loop if episode finished\n break\n\n print(\"Episode %d best score is %f\" % (i, np.mean(scores)))","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"122380986","text":"# Copyright 2015, 2016 OpenMarket Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport json\nimport logging\n\nfrom synapse.storage.database import LoggingTransaction\nfrom synapse.storage.engines import BaseDatabaseEngine\nfrom synapse.storage.prepare_database import get_statements\n\nlogger = logging.getLogger(__name__)\n\n\nALTER_TABLE = (\n \"ALTER TABLE events ADD COLUMN origin_server_ts BIGINT;\"\n \"CREATE INDEX events_ts ON events(origin_server_ts, stream_ordering);\"\n)\n\n\ndef run_create(cur: LoggingTransaction, database_engine: BaseDatabaseEngine) -> None:\n for statement in get_statements(ALTER_TABLE.splitlines()):\n cur.execute(statement)\n\n cur.execute(\"SELECT MIN(stream_ordering) FROM events\")\n rows = cur.fetchall()\n min_stream_id = rows[0][0]\n\n cur.execute(\"SELECT MAX(stream_ordering) FROM events\")\n rows = cur.fetchall()\n max_stream_id = rows[0][0]\n\n if min_stream_id is not None and max_stream_id is not None:\n progress = {\n \"target_min_stream_id_inclusive\": min_stream_id,\n \"max_stream_id_exclusive\": max_stream_id + 1,\n \"rows_inserted\": 0,\n }\n progress_json = json.dumps(progress)\n\n sql = (\n \"INSERT into background_updates (update_name, progress_json)\"\n \" VALUES (?, ?)\"\n )\n\n cur.execute(sql, (\"event_origin_server_ts\", progress_json))\n","sub_path":"synapse/storage/schema/main/delta/27/ts.py","file_name":"ts.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535395010","text":"from nba_api.stats.static import players\nfrom nba_api.stats.endpoints import shotchartdetail\nfrom nba_api.stats.endpoints import playerdashptshots\nimport pandas as pd\nfrom icecream import ic\nimport time\n\nplayer_dict = players.get_players()\nmaster_list = []\ncurrent_player = {'name': None, 'id': None, 'kahuna': None}\n\n\ndef get_scd_stats(id):\n ic(id)\n sc = shotchartdetail.ShotChartDetail(0, id, last_n_games=5)\n ic()\n df = sc.get_data_frames()[0]\n longshot_total = 0\n for index, row in df.iterrows():\n if(row['SHOT_DISTANCE'] > 24):\n longshot_total += row['SHOT_DISTANCE']\n\n return longshot_total\n\n\ndef get_pds_stats(id):\n return (0, 0, 0)\n\n\ndef kahunator(id):\n kahuna = 0\n pds_stats = get_pds_stats(id)\n scd_stats = get_scd_stats(id)\n kahuna = scd_stats\n return kahuna\n\n\ndef master_list_entry_creator(p):\n player_id = p['id']\n player_name = p['full_name']\n current_player['name'] = player_name\n current_player['id'] = player_id\n current_player['kahuna'] = kahunator(player_id)\n master_list.append(current_player.copy())\n\n\nfor p in player_dict:\n if(p['is_active']):\n master_list_entry_creator(p)\n\nkahuna_df = pd.DataFrame.from_dict(master_list)\nfinal_df = kahuna_df.sort_values(by=['kahuna'], ascending=False)\nprint(final_df)\n\n\n\"\"\" def get_kahuna_index(df):\n kahuna = 0\n for index, row in df.iterrows():\n if(row[\"SHOT_DISTANCE\"] > 24):\n kahuna += (row[\"SHOT_DISTANCE\"]-24)\n return kahuna\n\n\ntest_name = \"LeBron James\"\n\n\ndef kahunator(name):\n df = get_stats(name)\n kahuna = get_kahuna_index(df)\n print(name, \" Kahuna Index: \", kahuna)\n\n\ndf = get_shots(test_name)\nprint(df) \"\"\"\n","sub_path":"api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385849836","text":"\"\"\"\nlibanac - Python library for interacting with ANAC (Agencia Nacional de Aviacao\nCivil) online services\n\n\nCopyright (c) 2015 Andre Sencioles Vitorio Oliveira \n\nPermission to use, copy, modify, and distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\nOR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\"\"\"\n\n\n__title__ = 'libanac'\n__summary__ = 'Python library for interacting with ANAC (Agencia Nacional de' \\\n ' Aviacao Civil) online services'\n__url__ = 'https://github.com/asenci/libanac'\n\n__version__ = '0.1'\n\n__author__ = 'Andre Sencioles'\n__email__ = 'asenci@gmail.com'\n\n__license__ = 'ISC License'\n","sub_path":"libanac/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"162911115","text":"# client-server-based microservices\r\n\r\n# a socket server can be opened to listen to requests\r\nimport socket\r\nimport sys\r\n\r\ndef myClient():\r\n\r\n #open a socket\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # family INET and type STREAM\r\n param_tup = ('localhost', 9874)\r\n \r\n #connect to server\r\n sock.connect(param_tup)\r\n\r\n # send a message to the server\r\n if len(sys.argv) > 1:\r\n # join the sys arguments with a space between them\r\n msg = ' '.join(sys.argv[1:])\r\n else:\r\n msg = \"Default message\"\r\n \r\n sock.send(msg.encode())\r\n\r\n # handle response from server\r\n res = sock.recv(1024)\r\n print(res)\r\n\r\n #clean-up\r\n sock.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n myClient()\r\n\r\n\r\n","sub_path":"pyadvanced/some_requests/303my_client.py","file_name":"303my_client.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"485487220","text":"\n\nfrom xai.brain.wordbase.nouns._memento import _MEMENTO\n\n#calss header\nclass _MEMENTOES(_MEMENTO, ):\n\tdef __init__(self,): \n\t\t_MEMENTO.__init__(self)\n\t\tself.name = \"MEMENTOES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"memento\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_mementoes.py","file_name":"_mementoes.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"269806835","text":"\ndef define_morph_dictionary(surface, base, pos, pos1):\n morph = {}\n morph['surface'] = surface\n morph['base'] = base\n morph['pos'] = pos\n morph['pos1'] = pos1\n return morph\n\ndef read_file(file_path='./neko.txt.mecab'):\n \"\"\" read file tokenized\n \"\"\"\n doc = []\n with open(file_path) as fp:\n sentence = []\n for line in fp:\n line = line.split('\\t')\n if line[0] == 'EOS\\n':\n if len(sentence) > 0:\n doc.append(sentence)\n sentence = []\n else:\n morphes = line[1].split(',')\n surface = line[0]\n base = morphes[6]\n pos = morphes[0]\n pos1 = morphes[1]\n morph = define_morph_dictionary(surface, base, pos, pos1)\n sentence.append(morph)\n\n return doc\n\nif __name__ == '__main__':\n doc = read_file()\n","sub_path":"aida/chapter04/knock30.py","file_name":"knock30.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"425022199","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Aug 9 23:36:27 2017\r\n\r\n@author: Melvin Lee\r\n\"\"\"\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\n\r\n# should ask for input\r\ntmp = \"https://childes.talkbank.org/browser/index.php?url=Clinical-MOR/ENNI/SLI/413.cha\"\r\n\r\ndef getpage(html):\r\n url = requests.get(html)\r\n return url\r\n \r\npage = getpage(tmp) \r\nsoup = BeautifulSoup(page.content, 'html.parser')\r\n#print(soup.prettify())\r\na = soup.find(id='transcript')\r\nres = a.text # prints content \r\nb = res.strip()\r\n#print(b)\r\nprint(b.getline())\r\n\r\n","sub_path":"htmlscrape.py","file_name":"htmlscrape.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"509204777","text":"from google.appengine.ext import db\n\nimport os\n\nclass MolnsConfigWrapper(db.Model):\n \"\"\"\n A container for the per user MolnsConfig object\n \"\"\"\n user_id = db.StringProperty()\n folder = db.StringProperty()\n path = db.StringProperty()\n\n def delete(self):\n if self.path:\n if os.path.exists(self.path):\n os.remove(self.path)\n\n try:\n os.remove(self.folder)\n except:\n pass\n\n super(MolnsConfigWrapper, self).delete()\n\nclass MolnsConfigProcessWrapper(db.Model):\n \"\"\"\n A container for the per user MolnsConfig object\n \"\"\"\n user_id = db.StringProperty()\n outPath = db.StringProperty()\n stdout = db.StringProperty()\n stderr = db.StringProperty()\n stdout_seek = db.IntegerProperty()\n stderr_seek = db.IntegerProperty()\n return_code = db.StringProperty()\n pid = db.IntegerProperty()\n\n def delete(self):\n if self.stdout:\n if os.path.exists(self.stdout):\n os.remove(self.stdout)\n\n if self.stderr:\n if os.path.exists(self.stderr):\n os.remove(self.stderr)\n\n if self.return_code:\n if os.path.exists(self.return_code):\n os.remove(self.return_code)\n\n try:\n os.rmdir(self.outPath)\n except:\n pass\n\n super(MolnsConfigProcessWrapper, self).delete()\n\n def is_alive(self):\n if os.path.exists(self.return_code):\n return False\n else:\n # From http://stackoverflow.com/a/568285/3769360\n if type(self.pid) == long:\n try:\n os.kill(self.pid, 0)\n except OSError:\n return False\n else:\n return True\n else:\n return False\n\n def communicate(self, reset = False):\n if reset == True or type(self.stdout_seek) != long or type(self.stderr_seek) != long:\n self.stdout_seek = 0\n self.stderr_seek = 0\n\n stdout = \"\"\n stderr = \"\"\n\n if self.stdout:\n if os.path.exists(self.stdout):\n f = open(self.stdout)\n f.seek(self.stdout_seek)\n stdout = f.read()\n self.stdout_seek = f.tell()\n f.close()\n\n if self.stderr:\n if os.path.exists(self.stderr):\n f = open(self.stderr)\n f.seek(self.stderr_seek)\n stderr = f.read()\n self.stderr_seek = f.tell()\n f.close()\n\n self.put()\n \n return stdout, stderr\n","sub_path":"app/db_models/molnsconfig.py","file_name":"molnsconfig.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"185432243","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 15 11:01:58 2021\n\n@author: arndt\nPlots global maps of the input variables as well as timeseries\n\"\"\"\nfrom distributed import Client, progress\nimport numpy as np\nimport matplotlib\nmatplotlib.use(\"PS\")\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.dpi'] = 400\nfrom matplotlib.colors import ListedColormap, Normalize\nimport cartopy.crs as ccrs\nfrom cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter\nimport sys\nimport os\nimport traceback\nimport dask.dataframe as dd\nimport glob\nimport time\nfrom datetime import datetime,timedelta\nimport matplotlib.dates as mdates\n\n\n\ndef customize(ax):\n ax.set_extent([-180,180,-90,90], crs=ccrs.PlateCarree())\n ax.set_xticks(range(-160, 200, 40), crs=ccrs.PlateCarree())\n ax.set_yticks(range(-80, 120, 40), crs=ccrs.PlateCarree())\n ax.xaxis.set_major_formatter(LongitudeFormatter())\n ax.yaxis.set_major_formatter(LatitudeFormatter())\n ax.coastlines()\n\n\nif __name__ == \"__main__\":\n print(matplotlib.get_backend())\n print(sys.argv)\n if len(sys.argv)>=3:\n client = Client(sys.argv[2])\n client.restart()\n else:\n while True:\n try:\n SCHEDULER_FILE = glob.glob(os.path.join(os.environ[\"SCR\"],\"/scheduler*.json\"))[0]\n \n if SCHEDULER_FILE and os.path.isfile(SCHEDULER_FILE):\n client = Client(scheduler_file=SCHEDULER_FILE)\n break\n except IndexError:\n time.sleep(10)\n print(client.dashboard_link)\n plt.close(\"all\")\n work = os.environ[\"WORK\"]\n ctnames = [ \"Ci\", \"As\", \"Ac\", \"St\", \"Sc\", \"Cu\", \"Ns\", \"Dc\"]\n propnames = ['twp', 'lwp', 'iwp', 'cer_liq', 'cer_ice', 'cot', 'ctp', 'stemp_cloudy']\n \n \n axlabel_dict={\"clear\": \"Clear sky fraction\",\"Ci\":\"Cirrus/Cirrostratus fraction\",\n \"As\":\"Altostratus fraction\", \"Ac\":\"Altocumulus fraction\",\n \"St\":\"Stratus fraction\", \"Sc\": \"Stratocumulus fraction\",\n \"Cu\": \"Cumulus fraction\", \"Ns\": \"Nimbostratus fraction\",\n \"Dc\": \"Deep convection fraction\",\"clear_p\": \"Predicted clear sky fraction\",\n \"Ci_p\":\"Predicted Cirrus/Cirrostratus fraction\",\n \"As_p\":\"Predicted Altostratus fraction\", \n \"Ac_p\":\"Predicted Altocumulus fraction\",\n \"St_p\":\"Predicted Stratus fraction\", \"Sc_p\": \"Predicted Stratocumulus fraction\",\n \"Cu_p\": \"Predicted Cumulus fraction\", \"Ns_p\": \"Predicted Nimbostratus fraction\",\n \"Dc_p\": \"Predicted Deep convection fraction\",\n \"cwp\":\"total water path\", \"twp\":\"total water path\",\n \"lwp\": \"liquid water path\", \"iwp\":\"ice water path\",\n \"cod\": \"cloud optical depth\", \"tsurf\": \"surface temperature\",\n \"stemp_cloudy\": \"surface temperature\", \"cee\": \"emissivity\",\n \"ptop\": \"cloud top pressure\", \"htop\": \"cloud top height\",\n \"ttop\": \"cloud top temperature\", \"cerl\": \"liquid droplet radius\",\n \"ceri\": \"ice particle radius\",\"ctp\":\"cloud top pressure\"}\n \n \n ranges = [(0,800),(0,750),(0,500),(0,14),(0,28),(0,50),(0,950),(175,350)]\n ranges_dict={x:y for x,y in zip(propnames,ranges)}\n \n client.wait_for_workers(1)\n try:\n sptemp = [\"time\",\"lat\", \"lon\"] \n df=dd.read_parquet( os.path.join(work, \"frames/parquets\", sys.argv[1]), columns =sptemp+propnames,\n chunksize=1_000_000)\n times=0\n except Exception:\n traceback.print_exc()\n sptemp = [ \"lat\", \"lon\"] \n df=dd.read_parquet( os.path.join(work, \"frames/parquets\", sys.argv[1]), columns =sptemp+propnames,\n chunksize=1_000_000 )\n \n name=sys.argv[1]\n \n print(\"df loaded\", df.npartitions)\n \n dtypes = {x:\"float16\" for x in sptemp}\n for cname in ctnames :\n dtypes[cname]=\"float32\"\n \n df=df.sample(frac=0.001, replace=False, random_state=22345)\n rounddict={key:{\"lat\": 0, \"lon\": 0, \"time\":0,\n 'twp':0, 'lwp':0, 'iwp':0, 'cer_liq':1, 'cer_ice':1, 'cot':1, \n 'ctp':0, 'stemp_cloudy':0}[key] for key in sptemp+propnames}\n units ={'twp':\"g/m²\", 'lwp':\"g/m²\", 'iwp':\"g/m²\", 'cer_liq':\"µm\", 'cer_ice':\"µm\", 'cot':\"-\", \n 'ctp':\"hPa\", 'stemp_cloudy':\"K\"}\n longnames ={'twp':\"Total water path\", 'lwp':\"Liquid water path\", 'iwp':\"Ice water path\",\n 'cer_liq':\"Effective radius of liquid particles\", 'cer_ice':\"Effective radius of ice particles\",\n 'cot':\"Cloud Optical Thickness\", \n 'ctp':\"Cloud top Pressure\", 'stemp_cloudy':\"Surface Temperature\"}\n \n \n #exclude july 2010\n start = datetime.fromisoformat(\"1970-01-01\")\n start_july = datetime.fromisoformat(\"2010-07-01\")\n end_july = datetime.fromisoformat(\"2010-07-31\")\n ex_july = (df.time>(end_july-start).days)|( df.time<(start_july-start).days)\n df=df[ex_july]\n \n \n df_label=df.round(rounddict)\n df_label=client.persist(df_label)\n progress(df_label)\n \n regional = df_label.groupby([\"lat\",\"lon\"]).mean()\n \n for j in propnames[:]:\n i=regional.loc[:,j]\n \n prop=i.compute()\n prop=prop.reset_index(level=[\"lat\",\"lon\"])\n \n un_lat = np.unique(prop.lat)\n un_lon = np.unique(prop.lon)\n colors=prop.loc[:,j].values\n gg=np.ones((len(un_lat),len(un_lon)))*-1\n for x,y,z in zip(prop.lat,prop.lon,colors):\n I = np.argwhere(un_lat==x)\n J= np.argwhere(un_lon==y)\n gg[I,J] = z\n gg=np.where(gg<0,np.nan,gg)\n lonlon,latlat = np.meshgrid(un_lon,un_lat)\n \n #client.wait_for_workers(16)\n fig=plt.figure(j)\n ax=fig.add_subplot(1,1,1,projection=ccrs.PlateCarree())\n \n customize(ax)\n vmi,vma = ranges_dict[j]\n scatter=ax.pcolormesh(lonlon, latlat,gg,cmap=\"Greens\",shading=\"nearest\",\n transform=ccrs.PlateCarree())#,vmin=vmi,vmax=vma)\n\n ax.set_title(\"{} [{}]\".format(longnames[j],units[j]), fontsize=15)\n \n cbar = fig.colorbar(scatter, orientation =\"vertical\", fraction=0.12,pad=0.01,\n shrink=0.55)\n cbar.ax.tick_params(axis=\"y\", labelsize=15)\n fig.savefig(os.path.join(work,\"stats\", name.replace(\".parquet\",\"_\")+j+\".eps\"))\n print(j, \"done\")\n del colors\n \n iwp=regional.loc[:,\"iwp\"].compute()\n cwp=regional.loc[:,\"twp\"].compute()\n \n \n iwp=iwp.reset_index(level=[\"lat\",\"lon\"])\n cwp=cwp.reset_index(level=[\"lat\",\"lon\"])\n prop=iwp.copy()\n prop.iwp = iwp.iwp.values/cwp.twp.values\n print(prop.head())\n print(iwp.head())\n print(cwp.head())\n \n un_lat = np.unique(prop.lat)\n un_lon = np.unique(prop.lon)\n print(prop.columns)\n colors=prop.loc[:,\"iwp\"].values\n gg=np.ones((len(un_lat),len(un_lon)))*-1\n for x,y,z in zip(prop.lat,prop.lon,colors):\n I = np.argwhere(un_lat==x)\n J= np.argwhere(un_lon==y)\n gg[I,J] = z\n gg=np.where(gg<0,np.nan,gg)\n lonlon,latlat = np.meshgrid(un_lon,un_lat)\n \n \n fig = plt.figure()\n ax=fig.add_subplot(1,1,1,projection=ccrs.PlateCarree())\n \n customize(ax)\n vmi,vma = (0,1)\n \n assert np.all(gg.shape==lonlon.shape),lonlon.shape\n scatter=ax.pcolormesh(lonlon, latlat, gg,cmap=\"Greens\",shading=\"nearest\",\n transform=ccrs.PlateCarree(),vmin=vmi,vmax=vma)\n ax.set_title(\"Relative ice water path\", fontsize=16)\n \n cbar = fig.colorbar(scatter, orientation =\"vertical\", fraction=0.12,pad=0.01,\n shrink=0.55)\n cbar.ax.tick_params(axis=\"y\", labelsize=15)\n #fig.tight_layout()\n plt.draw()\n fig.savefig(os.path.join(work,\"stats\", name.replace(\".parquet\",\"_\")+\"relice.eps\"))\n print(\"relice\", \"done\")\n \n \n if \"times\" in globals():\n df_now = df_label[df_label.lat<0] \n fig, ax =plt.subplots(4,2, sharex=True, figsize=(10,10))\n ax=ax.flatten()\n for i,cname in enumerate(propnames):\n print(cname)\n sub = df_now.loc[:,[\"lat\",\"lon\",\"time\",cname]]\n gpby=sub.groupby(\"time\")\n \n temporal=gpby.agg([\"mean\", \"std\"]).iloc[:,4:]\n temporal=temporal.compute()\n temporal.sort_index(inplace=True)\n \n temporal.iloc[:,0].plot(ax=ax[i], label=\"mean\")\n ax[i].set_title(temporal.columns[0][0])\n bottom = temporal.iloc[:,0]-temporal.iloc[:,1]\n bottom = np.where(bottom<0, 0,bottom)\n top = temporal.iloc[:,0]+temporal.iloc[:,1]\n days = temporal.index.values\n start=datetime.fromisoformat(\"1970-01-01\")\n dates = [start+timedelta(days=x) for x in days]\n ax[i].fill_between(dates, (bottom), (top), color='b', alpha=.1, label=u\"$\\sigma$\")\n ax[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))\n ax[i].grid()\n ax[i].legend(fontsize=15)\n fig.autofmt_xdate()\n fig.tight_layout()\n fig.savefig(os.path.join(work,\"stats\", name.replace(\".parquet\",\"_\")+\"tempprops.eps\"))\n \n","sub_path":"ML/inputmaps.py","file_name":"inputmaps.py","file_ext":"py","file_size_in_byte":9347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"224243694","text":"'''\nBOJ 9507 Generations of Tribbles\nhttps://www.acmicpc.net/problem/9507\n---\n\n- 풀이과정:\n - **왜 DP로 풀어야 하는가?**\n 걍 딱 봐도 피보나치... \n'''\n\nfrom collections import defaultdict\nimport sys\n\nt = int(sys.stdin.readline().rstrip())\n\ndp = defaultdict(int)\ndp[0] = 1\ndp[1] = 1\ndp[2] = 2\ndp[3] = 4\n\ndef get_dp(n):\n if dp[n-1] == 0:\n get_dp(n-1)\n if dp[n-2] == 0:\n get_dp(n-2)\n if dp[n-3] == 0:\n get_dp(n-3)\n if dp[n-4] == 0:\n get_dp(n-4)\n dp[n] = dp[n-1] + dp[n-2] + dp[n-3] + dp[n-4]\n\nfor i in range(t):\n n = int(sys.stdin.readline().rstrip())\n if dp[n] == 0:\n get_dp(n)\n print(dp[n])\n else:\n print(dp[n])","sub_path":"DP/9507.py","file_name":"9507.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"232201342","text":"f = open(\"day2in.txt\")\nchecksumList = []\nfor item in f:\n temp = item.strip().split(\"\\t\")\n temp = [int(x) for x in temp]\n checksumList.append(temp)\n########## part 1 ###########\ncheckSUM = 0\nfor item in checksumList:\n checkSUM += max(item) - min(item)\n\nprint(checkSUM)\n\n############# part 2 ############\ncheckSUM = 0\nfor item in checksumList:\n for value in item:\n for compare in item:\n if value > compare:\n if value % compare == 0:\n checkSUM += value / compare\n if compare > value:\n if compare % value == 0:\n print()\n \nprint(checkSUM)\n\n","sub_path":"day2-2017.py","file_name":"day2-2017.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"337147027","text":"\"\"\"\nProblem: \nCompare if two strings are anagrams or not \n\nAlgorithm 1: \nAdd each character from one string to a dictionary and maintain \ncount for each character. \nNow for each character in the second string reduce count for character \nfound in dictionary. If character cannot be found return false. \n\nReturn true if count for each character from dictionary is equal to 0. \n\nAlgorithm 2: \nReturn results of a comparison between sorted versions of the two strings. \n\"\"\"\nprint(__doc__)\n\nclass SolutionAnagram(object):\n def isAnagram1(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\" \n if not s and not t:\n return True\n if bool(s) != bool(t):\n return False \n \n char_dictionary = {}\n for c in s: \n if c in char_dictionary: \n char_dictionary[c] += 1 \n else:\n char_dictionary[c] = 1 \n \n for c in t:\n if c in char_dictionary: \n char_dictionary[c] -= 1\n else:\n return False \n \n return not any(cv for cv in char_dictionary.values() if cv != 0)\n \n def isAnagram2(self,s, t):\n # Take care of corner cases \n if not s and not t:\n return True\n if bool(s) != bool(t):\n return False \n \n # return result of sorted comparison of the strings \n return sorted(s) == sorted(t)\n \nif __name__ == '__main__':\n s = SolutionAnagram()\n tests = [\n [\"anagram\",\"nagaram\"],\n [\"rat\",\"car\"]\n ]\n \n for t in tests:\n print(\"Input:\")\n print(t[0] + ',' + t[1])\n print(\"Answer: Algo 1\")\n print(s.isAnagram1(t[0], t[1])) \n print(\"Answer: Algo 2\")\n print(s.isAnagram2(t[0], t[1]))\n print()","sub_path":"strings/isanagram.py","file_name":"isanagram.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"195816500","text":"import numpy as np\n\nimport params\nimport utils\n\nimport random\nimport copy\n\nclass GeneticAlgo:\n\n def __init__(self, population_size, mutation_prob):\n self.population_size = population_size\n\n self.current_population = Population(self.population_size)\n\n self.mutation_prob = mutation_prob\n\n def next_population(self, selected_individuals):\n\n selected_individuals = [self.current_population.population[i] for i in selected_individuals]\n\n next_pop = []\n\n for i in range(len(selected_individuals)):\n for j in range(i+1, len(selected_individuals)):\n parent1 = selected_individuals[i]\n parent2 = selected_individuals[j]\n child1, child2 = self.crossover(parent1, parent2)\n next_pop.append(child1)\n \n if len(next_pop) < self.population_size:\n next_pop.append(child2)\n\n if len(next_pop) >= self.population_size:\n next_pop = self.mutation(next_pop)\n self.current_population.population = next_pop\n return \n \n raise Exception(\"Not enough images are selected\")\n\n def mutation(self, population):\n mutated_population = []\n for individual in population:\n for channel in range(3):\n if random.random() < self.mutation_prob:\n individual[channel].mutate()\n mutated_population.append(individual)\n return mutated_population\n \n def crossover(self, parent1, parent2):\n\n channel_crossover = random.randint(0, 2)\n\n temp = copy.copy(parent2[channel_crossover])\n parent2[channel_crossover] = copy.copy(parent1[channel_crossover])\n parent1[channel_crossover] = copy.copy(temp)\n\n return parent1, parent2\n\nclass Population:\n def __init__(self, size):\n self.size = size\n self.population = []\n\n for i in range(self.size):\n self.population.append(utils.build_rgb_tree(100))\n\n def get_pop_as_images(self):\n images = []\n\n for individual in self.population:\n images.append(utils.tree_to_rgb_image(individual))\n \n return images\n\n\nclass Individual:\n\n def __init__(self, value):\n self.value = value\n self.child1 = None\n self.child2 = None\n\n def set_child(self, child):\n if self.child1 is None:\n self.child1 = child\n return\n elif self.child2 is None:\n self.child2 = child\n return\n else:\n raise Exception(\"All children already set\")\n \n def is_child_missing(self):\n return self.child1 is None or self.child2 is None\n\n def get_tree(self, tree):\n if isinstance(self.child1, Individual):\n tree.append(self.child1)\n self.child1.get_tree(tree)\n if isinstance(self.child2, Individual):\n tree.append(self.child2)\n self.child2.get_tree(tree)\n return tree\n\n def print(self):\n print(self.value)\n if isinstance(self.child1, Individual):\n self.child1.print()\n else:\n pass\n if isinstance(self.child2, Individual):\n self.child2.print()\n else:\n pass\n \n def find_and_replace(self, to_find, to_replace):\n if self == to_find:\n self.value = to_replace\n return\n else:\n if isinstance(self.child1, Individual):\n self.child1.find_and_replace(to_find, to_replace)\n if isinstance(self.child2, Individual):\n self.child1.find_and_replace(to_find, to_replace)\n\n def construct_function(self, function_string):\n\n if self.value.num_child == 0:\n function_string += self.value.__name__ + \".function ( \"\n\n if self.value.num_child == 1:\n function_string += self.value.__name__ + \".function ( \" + self.child1.construct_function(function_string)\n \n if self.value.num_child == 2:\n function_string += self.value.__name__ + \".function ( \" + self.child1.construct_function(function_string) + \" , \" + self.child2.construct_function(function_string)\n\n return function_string + \" ) \"\n \n def mutate(self):\n sub_tree = self.get_tree([])\n node_to_mutate = np.random.choice(sub_tree)\n\n replacer = None\n\n if node_to_mutate.value.num_child == 0:\n replacer = np.random.choice(possible_zero_nodes)\n elif node_to_mutate.value.num_child == 1:\n replacer = np.random.choice(possible_one_nodes)\n elif node_to_mutate.value.num_child == 2:\n replacer = np.random.choice(possible_two_nodes)\n\n self.find_and_replace(node_to_mutate, replacer)\n\n","sub_path":"genetic.py","file_name":"genetic.py","file_ext":"py","file_size_in_byte":4815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"268346386","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom collections import defaultdict\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom cms.plugin_base import CMSPluginBase\nfrom cms.plugin_pool import plugin_pool\n\nfrom aldryn_people import models\n\n\nclass PeoplePlugin(CMSPluginBase):\n\n TEMPLATE_NAME = 'aldryn_people/plugins/%s/people_list.html'\n module = 'People'\n render_template = TEMPLATE_NAME % models.PeoplePlugin.STYLE_CHOICES[0][0]\n name = _('People list')\n model = models.PeoplePlugin\n\n def group_people(self, people, language):\n groups = defaultdict(list)\n\n for people in people:\n groups[people.group].append(people)\n\n # Python/Django bug ?\n groups.default_factory = None\n return groups\n\n def render(self, context, instance, placeholder):\n people = instance.get_selected_people()\n self.render_template = self.TEMPLATE_NAME % instance.style\n\n context['instance'] = instance\n context['people'] = people\n\n if (models.Group.objects.filter(person__in=people).exists() and\n instance.group_by_group):\n context['people_groups'] = self.group_people(\n people, instance.language)\n context['group_less_people'] = people.filter(group__isnull=True)\n else:\n context['people_groups'] = []\n context['group_less_people'] = []\n return context\n\nplugin_pool.register_plugin(PeoplePlugin)\n","sub_path":"aldryn_people/cms_plugins.py","file_name":"cms_plugins.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25373015","text":"from aitoolkit import create_app, db\n\nfrom flask_script import Manager, prompt_bool\nfrom flask_migrate import Migrate, MigrateCommand\n\napp = create_app()\nmigrate = Migrate(app, db)\n\nmanager = Manager(app)\nmanager.add_command('db', MigrateCommand)\n\n@manager.command\ndef dropdb():\n '''Drops all database tables.'''\n if prompt_bool('Are you sure to drop your databse?'):\n db.drop_all()\n\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"340949960","text":"\ncol, row = map(int, input().split())\n\nmatrix = []\nfor i in range(row):\n matrix.append(list(input()))\n\nfor r in range(row):\n for c in range(col):\n\n if matrix[r][c] != '*':\n matrix[r][c] = 0\n\n for i in range(r-1, r+2):\n for k in range(c-1, c+2):\n \n if i < 0 or k < 0 or i >= row or k >= row:\n continue\n elif matrix[r][c] == '*':\n continue\n elif matrix[i][k] == '*':\n matrix[r][c] += 1\n\nfor r in matrix:\n for v in r:\n print(v, end='')\n print()\n","sub_path":"coding dojang/unit_23.py","file_name":"unit_23.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"155600367","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nf = open(\"concentration.dat\", \"r\")\nconcentration = np.fromfile(f, dtype=np.float32)\nf.close()\nf = open(\"porosity.dat\", \"r\")\nporosity = np.fromfile(f, dtype=np.float32)\nf.close()\nconcentration1 = np.load(\"concentration1.npy\")\nporosity1 = np.load(\"porosity1.npy\")\n\n\nt1 = np.linspace(0, 20, 21)*1e-3\nt2 = np.linspace(0, 20, 21)*1e-3\n\nfig = plt.figure()\nax1 = fig.add_subplot(1,3,1)\nax2 = fig.add_subplot(1,3,2)\nax3 = fig.add_subplot(1,3,3)\nfor m in range(5):\n ax1.plot(t1, concentration[m::5])\n ax1.plot(t2, concentration1[m], '+')\n ax2.plot(t1, porosity[m::5]-porosity[m])\n ax2.plot(t2, porosity1[m]-porosity1[m][0], '+')\n ax3.plot(t1, porosity[m::5])\nax1.set_title(\"concentration\")\nax2.set_title(\"delta_phi\")\nax3.set_title(\"phi\")\nplt.show()\n\n","sub_path":"reactive_flow/src/tests/reaction_test/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"391394574","text":"# -*- encoding:utf-8 -*-\nfrom WoZaiXiaoYuanPuncher import WoZaiXiaoYuanPuncher\nfrom utils.configHandler import ConfigReader\nfrom utils.jsonHandler import Reader\n\n\ndef getData(type):\n if type == \"json\":\n return readDataFromJson()\n\n\ndef readDataFromJson():\n json = Reader(json_path)\n return json.getJson()\n\n\nif __name__ == '__main__':\n # 填入配置文件所在路径\n config_path = \"C:\\\\Users\\\\xxxx\\\\Desktop\\\\WoZaiXiaoYuanPuncher\\\\config.ini\"\n # 填入json文件所在路径\n json_path = \"C:\\\\Users\\\\xxxx\\\\Desktop\\\\WoZaiXiaoYuanPuncher\\\\source.json\"\n config = ConfigReader(config_path)\n data = getData(config.getDataSourceType())\n for item in data:\n wzxy = WoZaiXiaoYuanPuncher(item)\n loginStatus = wzxy.login()\n if loginStatus:\n wzxy.PunchIn()\n else:\n print(\"登陆失败\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"605674148","text":"import matplotlib.pyplot as plt\r\nfrom openpyxl import load_workbook\r\nimport math\r\nimport numpy as np\r\nimport dill\r\nimport unicodedata\r\nimport re\r\n\r\n\r\ndef print_a_event(kwd,lEvent):\r\n i=0\r\n for e in lEvent:\r\n if kwd in e.Key:\r\n print(i,e)\r\n i += 1\r\n\r\ndef slugify(value):\r\n \"\"\"\r\n Normalizes string, converts to lowercase, removes non-alpha characters,\r\n and converts spaces to hyphens.\r\n \"\"\"\r\n # import unicodedata\r\n # value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')\r\n # value = unicode(re.sub('[^\\w\\s-]', '', value).strip().lower())\r\n # value = unicode(re.sub('[-\\s]+', '-', value))\r\n value = re.sub('[^\\w\\s-]', '', value).strip().lower()\r\n value = re.sub('[-\\s]+', '-', value)\r\n return value\r\n\r\nNumDirections = 6 # 6 cones to cover the all release direction for a sphere\r\n\r\n\r\nTVDPLot = True\r\n\r\n\r\n#Topside\r\nArea = 'ProcessArea'\r\niExlFilename='Bv06_i'\r\ncExlFilename='Bv06_c'\r\n# cExlFilename='Bv05jalLM_Hull_c'\r\n# SysLen = 7 #Length of 'v08_9m' + 1\r\n# SysLen = 23 #Length of 'RUBY_FRA_Rev.B_v01_shk' + 1\r\n# SysLen = len('RUBY_FRA_Rev.B_v01_shk') + 1\r\nEqvsModule = {'020-01': 'S05', '020-02':'S05', \\\r\n '020-03':'S04', '020-04':'S04', \\\r\n '021-01':'S02','023-01':'P03','023-02':'P03', \\\r\n '023-03':'S03', '023-04':'S03', \\\r\n '024-01':'P04', '024-02':'P04','024-03':'P04', '025-01':'P04', '025-02':'P04', \\\r\n '025-03':'S03','027-01':'P05', '027-02':'P05', '027-03':'P05', \\\r\n '045-01':'P03','045-02':'P03','046-01':'P02','013-01':'S05'}\r\n\r\nSFXFiles = ['013-01-C1-G', '013-01-C2-G', '013-01-N1-G', '013-01-N2-G', \\\r\n '020-01-01-G', '020-01-02-L', '020-02-01-Li', '020-02-02-G', '020-02-03-Lo', '020-03-01-Li', '020-03-02-G', '020-03-03-Lo', '020-04-01-L', '020-04-02-G', '020-05-01-G', '020-05-02-L', \\\r\n '023-01-01-G-DA', '023-01-01-G-DB', '023-01-02-L', '023-02-01-G-DA', '023-02-01-G-DB', '023-02-02-L', '023-03-01-G-DA', '023-03-01-G-DB', '023-03-01-G-DC', '023-03-02-L','023-03-03-L', '023-04-G',\\\r\n '024-01-01-G','024-01-02-L', '024-02-G-DA', '024-02-G-DB', '024-02-G-DC', '024-03-01-G', '024-03-02-L', \\\r\n '025-01-01-G', '025-01-02-L', '025-02-01-G', '025-02-02-L', '027-01-G-DA', '027-01-G-DB', '027-01-G-DC', '027-02-G', '027-03-G', \\\r\n '043-03-G', '045-01-G', '045-02-01-G', '045-02-02-L', '045-03-G', '046-02-L', '046-03-L',\\\r\n '021-01-01-L','046-01-01-L','046-01-02-L','046-01-03-L','046-01-04-L','062-01-01-L','043-01-01-G','043-01-02-L','043-02-01-G','043-02-02-L']\r\nTVDprefix = ''\r\nelement_dump_filename = 'Bv06_dump'\r\n#Topside Parameters End\r\n\r\n#Offloaidng ara analysis\r\n# 'Flammable dispersion' is not relevant??? All vaporized??\r\ncExlFilename='Bv06_O_c'\r\nSFXFiles = ['021-02-L']\r\nelement_dump_filename = 'Bv06_offloading_dump'\r\n\r\n#Utlity analysis\r\ncExlFilename='Bv06_u_c'\r\nSFXFiles = ['045-04-G','062-01-02-L']\r\nelement_dump_filename = 'Bv06_utility_dump'\r\n\r\n#Hull deck analysis\r\ncExlFilename='Bv06_h_c'\r\nSFXFiles = ['131-01-L-fwdP','131-01-L-fwdS','131-01-L-aftP','131-01-L-aftS','131-02-L-fwdP','131-02-L-fwdS','131-02-L-aftP','131-02-L-aftS','057-01-02-L','057-01-01-G','046-04-L','021-01-02-L','013-06-L','013-05-L']\r\nelement_dump_filename = 'Bv06_hull_dump'\r\n\r\n\r\n\r\niExl=load_workbook(filename=iExlFilename+'.xlsx')\r\ncExl=load_workbook(filename=cExlFilename+'.xlsx')\r\nfExl=load_workbook(filename='Leak_Freq_Hole_Size.xlsx')\r\nshFreq = fExl['RESULTS - Hole size']\r\n\r\n\r\nshPV = iExl['Pressure vessel']\r\nshtTLV = iExl['Time varying leak']\r\nshDc = cExl['Discharge']\r\nshJet = cExl['Jet fire']\r\nshDispersion = cExl['Flammable Dispersion']\r\nshExplosion = cExl['Explosions']\r\n\r\n\r\ndef jffit(m):\r\n jl_lowe = 2.8893*np.power(55.5*m,0.3728)\r\n # if m>5:\r\n # jf = -13.2+54.3*math.log10(m)\r\n # elif m>0.1:\r\n # jf= 3.736*m + 6.\r\n # else:\r\n # jf = 0.\r\n # print(m, jl_lowe,jf)\r\n return jl_lowe\r\ndef mfit(jl):\r\n m = np.power(10,math.log10(jl/2.8893)/0.3728) / 55.5\r\n return m\r\n\r\nclass Event:\r\n def __init__(self,study_folder_pv,scenario,weather,dc=None,jf=None,epf=None,lpf=None,exp=None,freq=None,x=None,y=None,rh = None, \\\r\n hole = None,holemm = None, PP = None, TT = None,fireball = None, dispersion = None, esd = True, bdv = True,module = None,deck= None,pesd = 1, pbdv = 1): \r\n self.Study_Folder_Pv = study_folder_pv\r\n self.Path = study_folder_pv + \"\\\\\" + scenario\r\n self.Weather = weather\r\n study,pv, folder = study_folder_pv.split(\"\\\\\")\r\n self.Key = pv + \"\\\\\" + scenario + \"\\\\\" + weather\r\n self.Frequency = freq\r\n self.Discharge = dc\r\n self.JetFire = jf\r\n self.EarlyPoolFire = epf\r\n self.LatePoolFire = lpf\r\n self.Explosion = exp\r\n self.Fireball = fireball\r\n self.Dispersion = dispersion\r\n self.TVD = []\r\n self.TVDRead = False\r\n self.Module = module\r\n self.Deck = deck\r\n self.X = x\r\n self.Y = y\r\n self.ReleaseHeight = rh #should be 'Elevation.' Or Elevation + ReleaseHeight?\r\n self.Hole = hole\r\n self.Holemm = holemm\r\n self.Pressure = PP\r\n self.Temperature = TT \r\n self.PImdIgn = 1\r\n self.PDelIgn = 0\r\n self.PExp_Ign = 0.21 #WOAD as referred by by IP & UKOOA as the 'probability of explosion given ignition'\r\n self.ESDSuccess = esd\r\n self.BDVSuccess = bdv\r\n self.BDVDia = 0\r\n self.jfscale = 1 \r\n self.PESD = pesd\r\n self.PBDV = pbdv\r\n \"\"\" def __str__(self):\r\n ts, folder, pv, scenario = self.Path.split(\"\\\\\")\r\n if self.TVDRead == True:\r\n # RelDuration = self.TVD[-1,0]\r\n a,b,c,d,e = self.JetFire.JetLengths\r\n fmt = \"{:10s} | {:40s} | {:20s} | {:6.2f} |{:6.2f} |{:6.2f} | {:6s} | {:8s} | {:6s} | {:.2e} | {:6.0f} | {:8.2f} | {:8.2f} | {:8.2f} | {:8.2f}| {:8.2f}*\".\\\r\n format(ts, folder, pv, self.X, self.Y, self.ReleaseHeight, self.Module, scenario, self.Weather[9:], self.JetFire.Frequency, self.JetFire.SEP, a, b, c, d,e)\r\n else:\r\n fmt = \"{:10s} | {:40s} | {:20s} | {:20s} | {:20s} | {:20s} | {:.2e} | {:8.2f} | {:8.2f}\".\\\r\n format(ts, folder, pv, self.Module, scenario, self.Weather, self.Frequency, self.Discharge.ReleaseRate,self.Discharge.Duration)\r\n \r\n return fmt \"\"\"\r\n def __str__(self):\r\n ts, folder, pv, scenario = self.Path.split(\"\\\\\")\r\n if self.TVDRead == True:\r\n # print(self.Path,self.Dispersion,self.JetFire,self.EarlyPoolFire,self.LatePoolFire,self.Explosion,self.Fireball)\r\n # RelDuration = self.TVD[-1,0]\r\n # a,b,c,d,e = self.JetFire.JetLengths\r\n fmt = \"{:20s} | {:6.2f} |{:6.2f} |{:6.2f} | {:6s} | {:8s} | {:6s} \\\r\n | {:8.2f} [barg]| {:8.2f} [degC]| | ESD : {:}| BDV {:} | Freq: {:8.2e}\\n\".\\\r\n format(pv, self.X, self.Y, self.ReleaseHeight, self.Module, scenario, self.Weather[9:], \\\r\n self.Pressure, self.Temperature, self.ESDSuccess,self.BDVSuccess, self.Frequency)\r\n \r\n if self.Dispersion != None:\r\n fmt += \"\\tDispersion: Frequency {:8.2e}, Distance to LFL {:}\\n\".format(self.Dispersion.Frequency,self.Dispersion.DfMax)\r\n else:\r\n fmt += \"\\tDispersion: No dispersion\\n\"\r\n \r\n if self.JetFire != None:\r\n fmt += \"\\tJF: Frequency {:8.2e}, Length {:6.1f}\\n\".format(self.JetFire.Frequency,self.JetFire.Length)\r\n else:\r\n fmt += \"\\tJF: No Jet Fire\\n\"\r\n \r\n if self.Explosion != None:\r\n fmt += \"\\tExplosion: Frequency {:8.2e}, Overpressure {:6.1f} to {:6.1f} [m]\\n\".format(self.Explosion.Frequency,self.Explosion.Overpressures[-1],self.Explosion.Distance2OPs[-1])\r\n else:\r\n fmt += \"\\tExplosion: No Explosion\\n\"\r\n \r\n if self.EarlyPoolFire != None:\r\n fmt += \"\\tEPF: Frequency {:8.2e}, Diameter {:6.1f}\\n\".format(self.EarlyPoolFire.Frequency,self.EarlyPoolFire.Diameter)\r\n else:\r\n fmt += \"\\tEPF: No Early Pool Fire\\n\"\r\n if self.LatePoolFire != None:\r\n fmt += \"\\tLPF: Frequency {:8.2e}, Diameter {:6.1f}\\n\".format(self.LatePoolFire.Frequency,self.LatePoolFire.Diameter)\r\n else:\r\n fmt += \"\\tLPF: No Late Pool Fire\\n\"\r\n if self.Fireball != None:\r\n fmt += \"\\tFireball: Frequency {:8.2e}, Diameter {:6.1f}\\n\".format(self.Fireball.Frequency,self.Fireball.Diameter)\r\n else:\r\n fmt += \"\\tFireball: No Fireball\\n\"\r\n \r\n else:\r\n ts,pv,IS,hole = self.Path.split(\"\\\\\")\r\n f = \"{:15s} {:4s} ({:6.1f},{:6.1f},{:6.1f}) {:6.1f} {:6s} P({:8.2f}) T({:8.2f}) ESD({:}) BDV({:}) | Freq: {:8.2e}\".\\\r\n format(IS, self.Module, self.X, self.Y, self.ReleaseHeight, self.Holemm, self.Weather,self.Pressure, self.Temperature, self.ESDSuccess,self.BDVSuccess,self.Frequency)\r\n if self.Dispersion != None:\r\n f += \" O \"\r\n else:\r\n f += \" X \"\r\n if self.JetFire != None:\r\n f += \" O \"\r\n else:\r\n f += \" X \"\r\n if self.EarlyPoolFire != None:\r\n f += \" O \"\r\n else:\r\n f += \" X \"\r\n if self.LatePoolFire != None:\r\n f += \" O \"\r\n else:\r\n f += \" X \"\r\n if self.Explosion != None:\r\n f += \" O \"\r\n else:\r\n f += \" X \"\r\n if self.Fireball != None:\r\n f += \" O \"\r\n else:\r\n f += \" X \" \r\n fmt = f\r\n \r\n return fmt\r\n # return self.Key\r\n def EventTree(self):\r\n # Pwss = 1/8*1/2 #8 wind directions & 2 wind velocities\r\n Pwss = 1\r\n Pi = self.PImdIgn # Probability of immediate ignition #input into SAFETI hole \r\n Pdi = self.PDelIgn\r\n\r\n Ph = 4/6 #horizontal fraction for vertical and horizontal release cases\r\n Pj_h = 1/4*Ph # probability of horizontal jet fire Pjh x ph = 4/6 x 1/4 = 1/6 with no accompanying pool fire\r\n Pp_h = 1/2*Ph #probability of pool fire upon horizontal release with no accompanying jet fire\r\n Pjp_h =0.5/4*Ph #probability of jet & pool fire upon horizontal release\r\n\r\n Pj_v = 1/2*(1-Ph)#probabilty of vertical jet fire upon vertical release\r\n Pp_v = 1/2*(1-Ph)#\r\n Pjp_v = 0.5/4*(1-Ph)#\r\n\r\n #short release\r\n Ps = 1 #fraction for short release effects; release is shorter than cut-off time '20 s'\r\n Pbp = 1 #prob of bleve & pool fire\r\n Pb = 0 #prob of bleve without a pool fire\r\n Pfp = 0 #prob for short duration release immediate ignition resulting in flash fire and pool\r\n Pf = 0 #Flash fire along\r\n Pp = 0#prob for short duration release immediate ignition resulting in to have pool fire\r\n Pep = 0#prob for short duration release immediate ignition resulting in to have immediate explosion with pool fire\r\n Pe = 0#prob for short duration release immediate ignition resulting in to have immediate explosion without pool fire\r\n Pp = 0#prob for short duration release immediate ignition resulting in to have early pool fire without explosion\r\n\r\n\r\n Prp = 0.15 #prob of residual pool fire\r\n Po = (1-Pi)*Pwss*Pipr*Prp#prob of igniton of residual pool\r\n Pf_d = 0.6 #prob of delayed flash fire\r\n Pe_d = 0.4 #prob of explosion upon delayed ignition\r\n\r\n #Immediate, Not short\r\n P_i_ns_h_j = (1-Ps)*Ph*Pwss*Pj_h*Pi\r\n P_i_ns_h_p = (1-Ps)*Ph*Pwss*Pp_h*Pi\r\n P_i_ns_h_jp = (1-Ps)*Ph*Pwss*Pjp_h*Pi\r\n P_i_ns_v_j = (1-Ps)*(1-Ph)*Pwss*Pj_v*Pi\r\n P_i_ns_v_p = (1-Ps)*(1-Ph)*Pwss*Pp_v*Pi\r\n P_i_ns_v_jp = (1-Ps)*(1-Ph)*Pwss*Pjp_v*Pi\r\n #Immediate, Short\r\n P_i_s_BP = Ps*Pwss*Pbp*Pi #BLEVE & Pool\r\n P_i_s_B = Ps*Pwss*Pb*Pi #BLEVE only\r\n P_i_s_FP = Ps*Pwss*Pfp*Pi #Flash fire and pool\r\n P_i_s_F = Ps*Pwss*Pf*Pi #Flash fire only\r\n P_i_s_EP = Ps*Pwss*Pep*Pi #Explosion & pool fire\r\n P_i_s_E = Ps*Pwss*Pe*Pi #Explosion only\r\n P_i_s_P = Ps*Pwss*Pp*Pi #Pool fire only\r\n\r\n #Delayed\r\n P_d_FP = (1-Pi)*Pwss*Pfp*Pdi #Delayed flash and pool fire\r\n P_d_E = (1-Pi)*Pwss*Pdd*Pdi #Delayed explosion\r\n P_d_p = (1-Pi)*Pwss*Prp*Pirp #Redisual pool fire\r\n\r\n print(\"----Imd Ignition---Not short--|-Horizontal---Jet fire : {:8.2e}\".format(P_i_ns_h_j))\r\n print(\" | | |-Pool fire : {:8.2e}\".format(P_i_ns_h_p))\r\n print(\" | | -Jet & Pool fire: {:8.2e}\".format(P_i_ns_h_jp))\r\n print(\" | |-Vertical-----Jet fire : {:8.2e}\".format(P_i_ns_v_j))\r\n print(\" | |-Pool fire : {:8.2e}\".format(P_i_ns_v_p))\r\n print(\" | -Jet & Pool fire: {:8.2e}\".format(P_i_ns_v_jp))\r\n print(\" --Short----------------------BLEVE & Poolfire: {:8.2e}\".format(P_i_s_BP))\r\n print(\" |-BLEVE only : {:8.2e}\".format(P_i_s_B))\r\n print(\" |-Flash & Pool fire:{:8.2e}\".format(P_i_s_FP))\r\n print(\" |-Flash only: {:8.2e}\".format(P_i_s_F))\r\n print(\"----Delayed-------Ignited--------------------Flash and Pool fire:{:8.2e}\".format(P_d_FP))\r\n print(\" |- Explosion : {:8.2ef}\".format(P_d_E))\r\n print(\" |- Pool fire: {:8.2e}\".format(P_d_p))\r\n \r\n\r\nclass Discharge:\r\n def __init__(self,rr,duration,liqfrac = 0.):\r\n self.ReleaseRate = rr\r\n self.Duration = duration\r\n self.LiquidMassFraction = liqfrac\r\n self.Ts = [0.,0.,0.,0.,0.]\r\n self.Ms = [0.,0.,0.,0.,0.]\r\n self.RRs = [0.,0.,0.,0.,0.] \r\n\r\nclass Dispersion:\r\n def __init__(self,fdisp,dfmax,dfmin,wf,dmax,dmin,w,ffmax,ffw):\r\n self.Frequency = fdisp \r\n \r\n # self.Distance2LFLFraction = d2f\r\n # self.Distance2LFL = d\r\n \r\n #Column P: max d, Q: min d, R: max w for LFL fraction\r\n #Column S: max d, T: min d, U: max w for LFL fraction\r\n self.DfMax = dfmax\r\n self.DfMin = dfmin\r\n self.Wf = wf\r\n self.DMax = dmax\r\n self.DMin = dmin\r\n self.W = w\r\n\r\n self.FFMaxDistance = ffmax\r\n self.FFWidth = ffw\r\n\r\n def __str__(self):\r\n \r\n fmt = \"{:.2e} | {:8.2f}m to LFL Fraction | {:8.2f}m to LFL\".\\\r\n format(self.Frequency, self.DfMax, self.DMax) \r\n return fmt\r\n\r\nclass JetFire:\r\n def __init__(self,length,sep,jff):\r\n self.Length = length\r\n self.SEP = sep\r\n self.Frequency = jff\r\n self.Ts = [0.,0.,0.,0.,0.]\r\n self.JetLengths = [0.,0.,0.,0.,0.]\r\n def __str__(self):\r\n a,b,c,d,e = self.JetLengths\r\n fmt = \"{:.2e} | {:6.0f} | {:8.2f} | {:8.2f} | {:8.2f} | {:8.2f}| {:8.2f}\".\\\r\n format(self.Frequency, self.SEP, a, b, c, d, e) \r\n return fmt\r\n\r\nclass EarlyPoolFire:\r\n def __init__(self,diameter,sep,epff):\r\n self.Diameter = diameter\r\n self.SEP = sep\r\n self.Frequency = epff\r\n self.Ts = [0.,0.,0.,0.,0.]\r\n self.PoolDiameters = [0.,0.,0.,0.,0.]\r\n def __str__(self):\r\n a,b,c,d,e = self.PoolDiameters\r\n fmt = \"{:.2e} | {:6.0f} | {:8.2f} | {:8.2f} | {:8.2f} | {:8.2f}| {:8.2f}\".\\\r\n format(self.Frequency, self.SEP, a, b, c, d, e)\r\n\r\nclass LatePoolFire:\r\n def __init__(self,diameter,sep,epff):\r\n self.Diameter = diameter\r\n self.SEP = sep\r\n self.Frequency = epff\r\n self.Ts = [0.,0.,0.,0.,0.]\r\n self.PoolDiameters = [0.,0.,0.,0.,0.]\r\n def __str__(self):\r\n a,b,c,d,e = self.PoolDiameters\r\n fmt = \"{:.2e} | {:6.0f} | {:8.2f} | {:8.2f} | {:8.2f} | {:8.2f}| {:8.2f}\".\\\r\n format(self.Frequency, self.SEP, a, b, c, d, e)\r\n\r\nclass Explosion:\r\n def __init__(self,fexp,op,d2op):\r\n self.Overpressures = op\r\n self.Distance2OPs = d2op\r\n self.Frequency = fexp \r\n def __str__(self):\r\n a,b,c = self.Distance2OPs\r\n pa,pb,pc = self.Overpressures\r\n fmt = \"{:.2e} | {:8.2f}barg to {:8.2f} | {:8.2f}bar to {:8.2f} | {:8.2f} barg to {:8.2f}\".\\\r\n format(self.Frequency, pa, a, pb, b, pc,c) \r\n return fmt\r\n\r\nclass Fireball:\r\n def __init__(self,ffb,D,sep):\r\n self.Diameter = D\r\n self.SEP = sep\r\n self.Frequency = ffb \r\n def __str__(self):\r\n \r\n fmt = \"{:.2e} | Diameter: {:8.2f} | SEP {:8.2f}\".\\\r\n format(self.Frequency, self.Diameter, self.SEP) \r\n return fmt\r\n\r\n#Read Leaks\r\n#listLeak = []\r\nReleaseHeight= {} #from vessel bottom, Column 'V'? Shall be elevation Columnt 'T'?\r\nFrequency ={}\r\nPImdIgn ={}\r\nPDelIgn = {}\r\nPExp ={}\r\nReleaseRate = {}\r\nDuration = {}\r\nJ00 = {}\r\nJ05 = {}\r\nJ10 = {}\r\nJ30 = {}\r\nJ60 = {}\r\nJetSEP = {}\r\nJetFrequency = {}\r\nTiso = {}\r\nTbdv = {}\r\nHole = {}\r\nHolemm = {}\r\nPP = {} #Pressure of the PV\r\nTT = {} #Temp of the PV\r\nESDSuccess ={}\r\nBDVSuccess ={}\r\nBDVDia ={}\r\nX = {}\r\nY = {}\r\nZ = {}\r\nMaterial = {}\r\n\r\n\r\n\r\niIS=load_workbook(filename='IS_v12_shk.xlsx')\r\nshIS = iIS['Isolatable summary']\r\nIS_sub = {}\r\nnumESDVs = {}\r\nModules = {}\r\nDeck = {}\r\nr = 3\r\n# while r < 79:\r\n# nsub = shIS.cell(r,4).value\r\n# IS_sub[shIS.cell(r,3).value] = [r,nsub]\r\n# r += nsub\r\nwhile r < 82:\r\n pv = shIS.cell(r,5).value\r\n IS_sub[pv] = shIS.cell(r,11).value #Read for each leak at respective height\r\n Modules[pv] = shIS.cell(r,7).value\r\n Deck[pv] = shIS.cell(r,8).value\r\n if shIS.cell(r,24).value != None:\r\n nedvs = shIS.cell(r,24).value.count(\"\\\"\") \r\n numESDVs[pv] = nedvs\r\n else:\r\n numESDVs[pv] = pnedvs\r\n pnedvs = nedvs\r\n r += 1\r\n\r\nr=5\r\nwhile shFreq.cell(r,2).value == \"Full pressure leak\": \r\n pv = shFreq.cell(r,1).value \r\n Frequency[pv] = [0.,0.,0.,0.]\r\n if pv[-1] == \"G\":\r\n Frequency[pv][0] = shFreq.cell(r,4).value #Gas SM\r\n Frequency[pv][1] = shFreq.cell(r,5).value # ME\r\n Frequency[pv][2] = shFreq.cell(r,6).value # MA\r\n Frequency[pv][3] = shFreq.cell(r,7).value # LA\r\n else:\r\n Frequency[pv][0] = shFreq.cell(r,10).value #Liq SM\r\n Frequency[pv][1] = shFreq.cell(r,11).value # ME\r\n Frequency[pv][2] = shFreq.cell(r,12).value # MA\r\n Frequency[pv][3] = shFreq.cell(r,13).value # LA\r\n r += 3\r\nnumIS = (r-5)/3\r\n\r\n\r\n\r\n#Read 'Presure vessel' from Input\r\nr=63\r\nwhile shPV.cell(r,1).value == \"Yes\": \r\n study = shPV.cell(r,2).value\r\n pv = shPV.cell(r,8).value \r\n # key = study + \"\\\\\" + pv\r\n key = pv\r\n Material[key] = shPV.cell(r,9).value\r\n TT[key] = shPV.cell(r,16).value\r\n PP[key] = shPV.cell(r,16).value\r\n X[key] = shPV.cell(r,136).value\r\n Y[key] = shPV.cell(r,137).value \r\n Z[key] = shPV.cell(r,20).value #Elevation\r\n r += 1\r\nnumPV = r-63\r\n\r\n\r\n\r\n\r\n#Read 'Time varying leak' from Input\r\n#for r in range(6,numscn):\r\nr = 63\r\nwhile shtTLV.cell(r,1).value == \"Yes\":\r\n study = shtTLV.cell(r,2).value \r\n relheight = shtTLV.cell(r,32).value\r\n equip = shtTLV.cell(r,8).value\r\n folder = shtTLV.cell(r,9).value\r\n hole = shtTLV.cell(r,20).value \r\n holemm = shtTLV.cell(r,21).value\r\n relheight = shtTLV.cell(r,25).value\r\n # key = study + \"\\\\\" + equip + \"\\\\\" + folder + \"\\\\\" + hole\r\n key_hole = equip+\"-\"+hole\r\n ReleaseHeight[equip] = relheight\r\n\r\n #Construci disctionarys with keys as 'Path'\r\n Hole[key_hole] = hole\r\n Holemm[key_hole] = holemm\r\n #SAFETI\r\n # Frequency[key] = shtTLV.cell(r,38).value\r\n # PImdIgn[key] = shtTLV.cell(r,44).value\r\n # PDelIgn[key] = shtTLV.cell(r,46).value\r\n # PExp[key] = shtTLV.cell(r,48).value\r\n #PHAST doesn't provide this frequency & probability \r\n \r\n # PHAST\r\n ESDSuccess[key_hole] = shtTLV.cell(r,44).value\r\n Tiso[key_hole] = shtTLV.cell(r,45).value\r\n BDVSuccess[key_hole] = shtTLV.cell(r,47).value\r\n Tbdv[key_hole] = shtTLV.cell(r,48).value\r\n BDVDia[key_hole] = shtTLV.cell(r,49).value\r\n r=r+1\r\n print(\"Reading Time varying leaks: \",key_hole)\r\nnumLeak = r-63\r\n\r\n\r\n\r\nlEvent = [] #List of class Event\r\n#Construct Event list\r\n#Read Discharge, shDc\r\n# And evaluate ignition probability'\r\n# weathers = ['1.2/F', '6.6/D']\r\nweathers = ['2.9F','7.7D','14.5D']\r\nHoleSizes = [7.1, 36.1, 111.8, 150]\r\ndk=0\r\n#for r in range(2,numLeak*len(weathers)+2):\r\nfor r in range(2,shDc.max_row+1):\r\n study_folder_pv = shDc.cell(r,1).value\r\n hole = shDc.cell(r,2).value\r\n if hole != \"Catastrophic rupture\":\r\n study,pv,folder = study_folder_pv.split(\"\\\\\")\r\n scenario = shDc.cell(r,2).value\r\n weather = shDc.cell(r,3).value\r\n path = study_folder_pv + \"\\\\\" + scenario\r\n # key = study_folder_pv + \"\\\\\" + scenario + \"\\\\\" + weather\r\n key_hole = pv +\"-\"+ hole\r\n key_hole_weather = pv +\"-\"+hole+\"-\"+weather\r\n liqmassfrac = shDc.cell(r,14).value\r\n if weather in weathers:\r\n rr = shDc.cell(r,10).value\r\n ReleaseRate[key_hole] = rr\r\n duration = shDc.cell(r,11).value\r\n x = X[pv]\r\n y = Y[pv]\r\n z = Z[pv]\r\n Duration[key_hole] = duration\r\n basefreq = 0.\r\n #Frequency allocatin\r\n if hole[0:2] in ['SM','ME','MA','LA']:\r\n holesizeindex = ['SM','ME','MA','LA'].index(hole[0:2])\r\n if pv in Frequency.keys(): \r\n basefreq = Frequency[pv][holesizeindex]\r\n else:\r\n for k in Frequency.keys():\r\n if k in pv:\r\n fkey = k\r\n basefreq = Frequency[fkey][holesizeindex]\r\n elif hole[0:2] == \"LM\":\r\n for k in range(0,4):\r\n if Holemm[key_hole] > HoleSizes[k]:\r\n continue\r\n else:\r\n break\r\n holesizeindex = k \r\n if pv in Frequency.keys():\r\n for k in range(holesizeindex,4): #Add all frequency for larger hole size categories for LM\r\n basefreq += Frequency[pv][k]\r\n Frequency[pv][k] = 0.\r\n Frequency[pv][holesizeindex] = basefreq \r\n else:\r\n for k in Frequency.keys():\r\n if k in pv:\r\n fkey = k\r\n for k in range(holesizeindex,4):\r\n basefreq += Frequency[fkey][k]\r\n Frequency[fkey][k] = 0.\r\n Frequency[fkey][holesizeindex] = basefreq\r\n \r\n leak_freq = IS_sub[pv]*basefreq#actually Frequency[pv] = 1 \r\n\r\n \r\n # aEvent = Event(study_folder_pv,scenario,weather,freq=Frequency[path],dc=Discharge(rr,duration),hole=Hole[path])\r\n p_ESDfail = 0.01*numESDVs[pv]\r\n if hole[4]==\"O\":\r\n esd = True\r\n p_esd_branch = 1-p_ESDfail\r\n leak_freq *= 1-p_ESDfail\r\n elif hole[4] == \"X\":\r\n esd = False\r\n p_esd_branch = p_ESDfail\r\n leak_freq *= p_ESDfail\r\n else:\r\n print(pv,hole,'ESDV value wrong')\r\n break\r\n #BDV failure into Event Frequency\r\n if hole[-1]==\"O\":\r\n bdv = True\r\n p_bdv_branch = (1 - 0.005)\r\n leak_freq *= (1 - 0.005)\r\n elif hole[-1]==\"N\":\r\n bdv = \"None\"\r\n p_bdv_branch = 1\r\n elif hole[-1]==\"X\":\r\n bdv = False\r\n p_bdv_branch = 0.005\r\n leak_freq *= 0.005\r\n else:\r\n print(pv,hole,'BDV value wrong')\r\n break\r\n\r\n if weather == '2.9F':\r\n leak_freq *= 0.486\r\n elif weather == '7.7D':\r\n leak_freq *= 0.471\r\n elif weather == '14.5D':\r\n leak_freq *= 0.044\r\n else:\r\n print('Wrong wetaher', key_hole_weather)\r\n break\r\n\r\n\r\n\r\n aEvent = Event(study_folder_pv,hole,weather,freq=leak_freq,dc=Discharge(rr,duration,liqfrac=liqmassfrac),hole=Hole[key_hole],holemm = Holemm[key_hole],\\\r\n esd=esd,bdv=bdv,x=x,y=y,rh=z,PP=PP[pv],TT=TT[pv],module=Modules[pv],deck=Deck[pv],pesd=p_esd_branch, pbdv=p_bdv_branch)\r\n lEvent.append(aEvent)\r\n\r\n else:\r\n print(\"{} Discharge events read\".format(dk))\r\n break\r\n dk=dk+1\r\n\r\n#End of constructing list of Events\r\n#Up to now, read IS, '_i', '_c[Discharge]'\r\n\r\nIgnProb = {}\r\nIgnProb['023-01']=[0.00050007132890309,0.00120241794400881,0.0121099047419176,0.0133941985161508]\r\nIgnProb['023-02']=[0.000500009730687852,0.00112728346839808,0.0114299096696923,0.0124894860472479]\r\nIgnProb['045-01']=[0.000500092602037187,0.00214457708972392,0.0159824850536888,0.015707932976315]\r\nIgnProb['024-01']=[0.000500049238017383,0.00135755735655058,0.0127160815903571,0.0137890702655233]\r\nIgnProb['024-02']=[0.000500092602037187,0.00177918758871906,0.014582259955286,0.0152682624925632]\r\nIgnProb['024-03']=[0.000500092602037187,0.00187273284139629,0.0148864999002958,0.0153843297225681]\r\nIgnProb['025-01']=[0.000500066037325877,0.00155843931004843,0.0138293983168883,0.0148186113336855]\r\nIgnProb['025-02']=[0.000500076839107057,0.001583080559352,0.0138624647673917,0.0148213944403002]\r\nIgnProb['027-01']=[0.000500092602037187,0.00141234355179696,0.0130284920753651,0.014098525976969]\r\nIgnProb['027-02']=[0.000500092602037187,0.00167828753177232,0.0139540201469402,0.0148124734230255]\r\nIgnProb['023-03']=[0.000500074056674887,0.00134865578738282,0.0127446106070196,0.013756233693594]\r\nIgnProb['023-04']=[0.000500014189107731,0.00114561328550342,0.0121656333278765,0.0136982452845986]\r\nIgnProb['024-01']=[0.000500056109924782,0.00140883072048731,0.013214286058242,0.0148872691410471]\r\nIgnProb['045-02']=[0.000500077778731805,0.00141477302560298,0.012839767974552,0.0139304583821647]\r\nIgnProb['020-01']=[0.000500081597970954,0.00198507390262245,0.0159033776172752,0.0159730079240214]\r\nIgnProb['020-02']=[0.000500044233038885,0.00127252532590165,0.0126086841965461,0.0139360824741458]\r\nIgnProb['013-01']=[0.000500081597970954,0.00125827417928573,0.0124609025752969,0.0136146062289823]\r\nIgnProb['020-03']=[0.000500037598733664,0.00117389329582008,0.0122180292562774,0.0135140045120202]\r\nIgnProb['020-04']=[0.000500009985715746,0.00113070577630583,0.0120388416453966,0.0131069382140561]\r\nIgnProb['027-03']=[0.000500087509063428,0.00137082995866607,0.0129208012390835,0.0142136300044506]\r\nIgnProb['General']=[0.000502,0.001677,0.017112,0.017916]\r\n\r\n\r\nIgnitionModel = \"OLF\"\r\np = []\r\n#Set Ignition probability after reading the Discharge result\r\nfor e in lEvent: \r\n # study,pv,pv_hole,hole,weather = e.Key.split(\"\\\\\")\r\n pv,hole,weather = e.Key.split(\"\\\\\") \r\n key_hole = pv +\"-\"+ hole\r\n rr = ReleaseRate[key_hole]\r\n for k in IgnProb.keys():\r\n if k in pv:\r\n p = IgnProb[k] \r\n \r\n if IgnitionModel == \"OLF\":\r\n # Adjustment for liquid mass fraction\r\n rr *= (1-min(e.Discharge.LiquidMassFraction,0.95)) \r\n if p == []:\r\n p = IgnProb['General']\r\n if rr < 1:\r\n e.PImdIgn = 0.0005\r\n e.PDelIgn = p[0] - e.PImdIgn\r\n # e.PDelIgn = p[0]\r\n elif rr < 10:\r\n e.PImdIgn = 0.001\r\n e.PDelIgn = p[1] - e.PImdIgn \r\n # e.PDelIgn = p[1]\r\n elif r < 30.:\r\n e.PImdIgn = 0.01 \r\n e.PDelIgn = p[2] - e.PImdIgn \r\n # e.PDelIgn = p[2]\r\n elif r >= 30.: \r\n e.PImdIgn = 0.01\r\n e.PDelIgn = p[3] - e.PImdIgn \r\n # e.PDelIgn = p[3]\r\n # Adjustment for liquid mass fraction\r\n # e.PImdIgn *= (1-min(e.Discharge.LiquidMassFraction,0.95))\r\n # e.PDelIgn *= (1-min(e.Discharge.LiquidMassFraction,0.95))\r\n # print(key_hole, rr, e.PImdIgn)\r\n elif IgnitionModel == \"UKOOA\": #No.22 Offshore FPSO Gas or Liquid\r\n if \"-L\" in pv:\r\n #26 FPSO Liquid\r\n max_p =0.028\r\n min_p = 0.001\r\n pointa = 0.1\r\n grad_a = 0.468558\r\n offset_a = -2.49002\r\n pointb = 100\r\n if rr < pointa:\r\n pign = np.power(10,grad_a*np.log1o(rr)+offset_a)\r\n if pign < min_p:\r\n pign = min_p\r\n if rr >= pointb:\r\n pign = max_p\r\n else:\r\n #22 Offshor Process Gas Congested or Mechanical Vented Module\r\n \r\n #24 Offshore FPSO Gas\r\n max_p =0.15\r\n min_p = 0.001\r\n pointa = 0.1\r\n grad_a = 0.072551\r\n offset_a = -2.88606\r\n pointb = 1\r\n grad_b = 1.213764\r\n offset_b = -2.88606\r\n pointc = 50\r\n\r\n if rr < pointa:\r\n pign = np.power(10,grad_a*np.log1o(rr)+offset_a)\r\n if pign < min_p:\r\n pign = min_p\r\n elif rr < pointb:\r\n pign = np.power(10,grad_b*np.log1o(rr)+offset_b)\r\n if pign > max_p:\r\n pign = max_p\r\n elif rr >= pointc:\r\n pign = max_p\r\n else:\r\n # rr *= (1-min(e.Discharge.LiquidMassFraction,0.95)) \r\n if p == None:\r\n p = IgnProb['General']\r\n if rr < 1:\r\n e.PImdIgn = p[0]\r\n elif rr < 10:\r\n e.PImdIgn = p[1]\r\n elif r < 30.:\r\n e.PImdIgn = p[2]\r\n elif r >= 30.: \r\n e.PImdIgn = p[3]\r\n\r\n \r\n # e.PImdIgn = PImdIgn[path]\r\n # e.PDelIgn = PDelIgn[path]\r\n # e.PExp_Ign = PExp[path]\r\n \r\n\r\n\r\n\r\n#Read TV Discharge data and append the info on each Event ... equip - hole - weather\r\n\r\nfor sfx in SFXFiles:\r\n# for sfx in ['013-01-C2-G']:\r\n# for sfx in ['021-01-01-L']:\r\n #sfx = '020-01'\r\n tvExl = load_workbook(filename=TVDprefix + sfx+'.xlsx')\r\n print(\"Reading ...\", sfx)\r\n sh = tvExl['Sheet1']\r\n new_scn = False\r\n #iterte for all row\r\n #read total row\r\n\r\n r = 1\r\n while r < sh.max_row:\r\n rv = sh.cell(r,1).value \r\n #read the path at the row next toe 'Sceanrio ...'\r\n if rv != None:\r\n if \"Scenario\" in rv:\r\n #print (r, \"in the loop\")\r\n #print(rv) \r\n r = r + 1\r\n path = sh.cell(r,1).value\r\n filename,study,pv,folder,hole = path.split(\"\\\\\") \r\n # path = path[SysLen:]\r\n path = study +\"\\\\\"+pv +\"\\\\\"+folder +\"\\\\\"+hole\r\n\r\n r = r + 2\r\n weather = sh.cell(r,1).value\r\n weather = weather[9:]\r\n #scn = path[20:]+\"-\"+weather[9:]\r\n scn = path +\"\\\\\"+weather\r\n r = r + 3\r\n t = sh.cell(r,1).value # read t=0 data\r\n mm = sh.cell(r,2).value\r\n rr = sh.cell(r,3).value\r\n m0 = mm\r\n r0 = rr\r\n TVD = [t, mm, rr ] \r\n \r\n while t != None:\r\n mm = sh.cell(r,2).value\r\n rr = sh.cell(r,3).value\r\n TVD = np.vstack([TVD, [t, mm, rr]]) \r\n # if ((\"Flow line\" in path) and (\"NE_TLV\" in path) and (t==3600)):\r\n # print([t, mm, rr])\r\n # print(TVD[-1,:])\r\n tp = t\r\n r = r + 1\r\n t = sh.cell(r,1).value \r\n \r\n # if tp==3600:\r\n # print(path, weather, TVD[-1,:])\r\n #print(\"Scenario {} ends at time {:8.2f} \\n with the remaining mass {:10.2f}( \\% of the inventory) and Release rate: {:8.2f})\".\\\r\n # format(scn, tp, mm/m0*100, rr))\r\n #print(\"End of scenario {}\".format(path+weather)) \r\n #print(r, rv) \r\n\r\n\r\n #print out release rate at t=0, t=5min, t=10min, t=30min, t = 60min\r\n T_gate = [0, 300, 600, 1800, 3600]\r\n M_gate = [TVD[0,1], 0., 0., 0., 0.]\r\n RR_gate = [TVD[0,2], 0., 0., 0., 0.]\r\n #Tgi = 1\r\n for Tgi in range(1,5):\r\n tp = 0\r\n ti = 1\r\n #if T_gate[Tgi] < Duration[scn]:\r\n for t in TVD[1:,0]: \r\n if tp < T_gate[Tgi] and T_gate[Tgi] <= t:\r\n #t = TVD[ti,0]\r\n M_gate[Tgi] = TVD[ti,1]\r\n RR_gate[Tgi] = TVD[ti,2]\r\n #print(\"ti={:5d} Mass {:12.2f} ({:12.2f}) \\& Release Rate {:12.2f} ({:12.2f})at {:12.2f} read\".format(ti,M_gate[Tgi],TVD[ti,1],RR_gate[Tgi],TVD[ti,2],t))\r\n tp = t\r\n ti = ti+1\r\n #print(\"{:12d}{:12d}{:12d}{:12d}{:12d}\".format(T_gate[0],T_gate[1],T_gate[2],T_gate[3],T_gate[4]))\r\n #print(\"{:12.2f}{:12.2f}{:12.2f}{:12.2f}{:12.2f}\".format(M_gate[0],M_gate[1],M_gate[2],M_gate[3],M_gate[4]))\r\n #print(\"{:12.2f}{:12.2f}{:12.2f}{:12.2f}{:12.2f}\".format(RR_gate[0],RR_gate[1],RR_gate[2],RR_gate[3],RR_gate[4]))\r\n\r\n #Find an Event that fits the 'path' + 'weather'\r\n # i=0\r\n # while (not (lEvent[i].Path == path and lEvent[i].Weather == weather)):\r\n # i = i + 1\r\n # if i == len(lEvent):\r\n # break\r\n # if i < len(lEvent):\r\n # key = path + \"\\\\\" + weather\r\n # #Save the results of T, M & RR\r\n # lEvent[i].Discharge.Ts = T_gate\r\n # lEvent[i].Discharge.Ms = M_gate\r\n # lEvent[i].Discharge.RRs = RR_gate\r\n # lEvent[i].TVDRead = True\r\n # lEvent[i].TVD = TVD\r\n # print(\"TVD Read & Saved : {} {}\".format(path, weather))\r\n # else:\r\n # print(\"Event corresponding to {} {} not found\".format(path, weather))\r\n\r\n for e in lEvent:\r\n if e.Path == path:\r\n e.Discharge.Ts = T_gate\r\n e.Discharge.Ms = M_gate\r\n e.Discharge.RRs = RR_gate\r\n e.TVDRead = True\r\n e.TVD = TVD\r\n print(e.Path,e.Weather, \"TVD Read\")\r\n \r\n\r\n\r\n\r\n if TVDPLot == True:\r\n fig,ax1 = plt.subplots() \r\n Time = TVD[:,0]\r\n Mass = TVD[:,1]\r\n RelRate = TVD[:,2]\r\n\r\n masscolor = 'tab:blue'\r\n ax1.set_xlabel('Time [s]')\r\n ax1.set_ylabel('Mass [kg]',color=masscolor)\r\n ax1.plot(Time,Mass,color=masscolor)\r\n ax1.set_ylim(bottom=0)\r\n ax1.tick_params(axis='y',labelcolor=masscolor)\r\n # ax1.xaxis.set_major_locator(plt.FixedLocator([300, 600, 1800, 3600]))\r\n # ax1.set_xlim(left=0, right=3600)\r\n \r\n ax2 = ax1.twinx()\r\n rrcolor = 'tab:red'\r\n ax2.set_ylabel('Release Rate [kg/s]',color=rrcolor)\r\n ax2.plot(Time,RelRate,color=rrcolor)\r\n ax2.set_ylim(bottom=0)\r\n ax2.tick_params(axis='y',labelcolor=rrcolor)\r\n pngfilename = \"TVD-\"+pv+\"_\"+hole\r\n plt.title(pngfilename) \r\n plt.show()\r\n fn = slugify(pngfilename)\r\n fig.savefig(\".\\\\tvd_rev.B\\\\{}.png\".format(fn))\r\n plt.close()\r\n \r\n\r\n #Copy the discharge pattern from 6.6/D to 1.2/F\r\n # i=0\r\n # while (not (lEvent[i].Path == path and lEvent[i].Weather == '1.2/F')):\r\n # i = i + 1\r\n # if i == len(lEvent):\r\n # break\r\n # if i < len(lEvent):\r\n # key = path + \"\\\\\" + '1.2/F'\r\n # lEvent[i].Discharge.Ts = T_gate\r\n # lEvent[i].Discharge.Ms = M_gate\r\n # lEvent[i].Discharge.RRs = RR_gate\r\n # lEvent[i].TVDRead = True\r\n # lEvent[i].TVD = TVD\r\n # #print(lEvent[i].Discharge.Ms)\r\n # else:\r\n # print(\"Event corresponding to {} {} not found\".format(path, '1.2/F')) \r\n else:\r\n print(\"skip line {}\".format(r))\r\n # continue\r\n r = r + 1\r\n\r\n#End of reading Discharge files\r\n\r\n#For an Event, find the relevant Leak and return its frequency\r\n#r = 10\r\n#key = lEvent[r].Path\r\n#print(\"Path: {} Frequency: {} Release Height: {}\".format(key,Frequency[key],ReleaseHeight[key]))\r\n\r\n#Reading Jet fire\r\n#1. Find an Event that has the same study_folder_pv, scenario, & weather\r\n# lEvent[##].JetFire = JetFiire\r\n#for r in range(2,numLeak*len(weathers)+2):\r\nfor r in range(2,shJet.max_row+1):\r\n study_folder_pv = shJet.cell(r,1).value\r\n scenario = shJet.cell(r,2).value\r\n weather = shJet.cell(r,3).value\r\n path = study_folder_pv + \"\\\\\" + scenario\r\n \r\n study,pv,folder = study_folder_pv.split(\"\\\\\")\r\n # holesizeindex = ['SM','ME','MA','LA'].index(scenario[0:2])\r\n\r\n key = pv + \"\\\\\" + scenario + \"\\\\\" + weather\r\n #Find the relevant event\r\n # for e in lEvent:\r\n # if e.Key == key: \r\n # break\r\n \r\n i=0\r\n while not (lEvent[i].Path == path and lEvent[i].Weather == weather):\r\n i = i + 1\r\n if i == len(lEvent):\r\n break\r\n if i < len(lEvent):\r\n # key = path + \"\\\\\" + weather\r\n if weather in weathers:\r\n jfl = shJet.cell(r,10).value\r\n #J00[key] = jfl\r\n sep = shJet.cell(r,11).value\r\n JetSEP[key] = sep\r\n\r\n e = lEvent[i]\r\n jff = e.Frequency*e.PImdIgn/NumDirections\r\n # if weather == '1.2/F':\r\n # jff = jff*0.18\r\n # elif weather == '6.6/D':\r\n # jff = jff*0.82\r\n JetFrequency[key] = jff\r\n lEvent[i].JetFire = JetFire(jfl,sep,jff)\r\n\r\n if e.Discharge.Ts[2] != 0:\r\n jf0 = e.JetFire.Length\r\n m0 = e.Discharge.RRs[0]\r\n jf0fit = jffit(m0)\r\n jfscale = e.JetFire.Length/jf0fit\r\n e.jfscale = jfscale\r\n lEvent[i].JetFire.JetLengths[0] = jf0\r\n for ti in range(1,5):\r\n #t = a_event.Ts[i]\r\n m = e.Discharge.RRs[ti]\r\n jf = jffit(m)\r\n lEvent[i].JetFire.JetLengths[ti] = jf*jfscale\r\n #lEvent[i].JetFire.JetLengths[ti] = jf\r\n J00[key] = jf0\r\n J05[key] = lEvent[i].JetFire.JetLengths[1]\r\n J10[key] = lEvent[i].JetFire.JetLengths[2]\r\n J30[key] = lEvent[i].JetFire.JetLengths[3]\r\n J60[key] = lEvent[i].JetFire.JetLengths[4]\r\n\r\n else:\r\n print(\"{} Jet fire events read\".format(k))\r\n break\r\n # k=k+1\r\n#Read Jet, shJet\r\n\r\n\r\n#shExplosion\r\nExpD1 = {}\r\nExpD2 = {}\r\nExpD3 = {}\r\nExpFreq = {}\r\n#Read Early Pool Fire\r\nfor r in range(2,shExplosion.max_row+1):\r\n study_folder_pv = shExplosion.cell(r,1).value\r\n scenario = shExplosion.cell(r,2).value\r\n weather = shExplosion.cell(r,3).value\r\n # path = study_folder_pv + \"\\\\\" + scenario \r\n # key = path + \"\\\\\" + weather \r\n p1 = shExplosion.cell(r,9).value \r\n p2 = shExplosion.cell(r,10).value \r\n p3 = shExplosion.cell(r,11).value \r\n d1 = shExplosion.cell(r,12).value \r\n d2 = shExplosion.cell(r,13).value \r\n d3 = shExplosion.cell(r,14).value \r\n\r\n study,pv,folder = study_folder_pv.split(\"\\\\\")\r\n key = pv + \"\\\\\" + scenario + \"\\\\\" + weather\r\n\r\n ExpD1[key] = d1\r\n ExpD2[key] = d2\r\n ExpD3[key] = d3\r\n \r\n for e in lEvent:\r\n if e.Key == key:\r\n # fexp = e.Frequency*(1-e.PImdIgn)*e.PDelIgn*e.PExp_Ign\r\n fexp = e.Frequency*e.PDelIgn*e.PExp_Ign\r\n ExpFreq[key] = fexp\r\n e.Explosion = Explosion(fexp,[p1,p2,p3],[d1,d2,d3])\r\n\r\n\r\n#shDispersion\r\nDistLFLFrac = {}\r\nDistLFL = {}\r\nDispFreq = {}\r\n#Read Flammable Dispersion\r\nfor r in range(2,shDispersion.max_row+1):\r\n study_folder_pv = shDispersion.cell(r,1).value\r\n scenario = shDispersion.cell(r,2).value\r\n weather = shDispersion.cell(r,3).value\r\n path = study_folder_pv + \"\\\\\" + scenario \r\n # key = path + \"\\\\\" + weather \r\n # key = pv+ \"\\\\\" + hole + \"\\\\\" + weather \r\n\r\n study,pv,folder = study_folder_pv.split(\"\\\\\")\r\n key = pv + \"\\\\\" + scenario + \"\\\\\" + weather\r\n # 15,16,17\r\n dfmax = shDispersion.cell(r,15).value \r\n dfmin = shDispersion.cell(r,16).value \r\n wf = shDispersion.cell(r,17).value \r\n # 19,20,21\r\n dmax = shDispersion.cell(r,19).value \r\n dmin = shDispersion.cell(r,20).value \r\n w = shDispersion.cell(r,21).value \r\n\r\n ffmax = shDispersion.cell(r,27).value \r\n ffw = shDispersion.cell(r,29).value \r\n \r\n \r\n DistLFLFrac[key] = dfmax\r\n DistLFL[key] = dmax\r\n \r\n for e in lEvent:\r\n if e.Key == key:\r\n # fdisp = e.Frequency*(1-e.PImdIgn)*e.PDelIgn*(1-e.PExp_Ign)\r\n fdisp = e.Frequency*(1-e.PImdIgn - e.PDelIgn)\r\n DispFreq[key] = fdisp\r\n e.Dispersion = Dispersion(fdisp,dfmax,dfmin,wf,dmax,dmin,w,ffmax,ffw)\r\n\r\nif 'Early Pool Fire' in cExl.sheetnames:\r\n shPool = cExl['Early Pool Fire']\r\n EPSEP = {}\r\n EPFreq = {}\r\n #Read Early Pool Fire\r\n for r in range(2,shPool.max_row+1):\r\n study_folder_pv = shPool.cell(r,1).value\r\n scenario = shPool.cell(r,2).value\r\n weather = shPool.cell(r,3).value\r\n path = study_folder_pv + \"\\\\\" + scenario \r\n # key = path + \"\\\\\" + weather \r\n study,pv,folder = study_folder_pv.split(\"\\\\\")\r\n key = pv + \"\\\\\" + scenario + \"\\\\\" + weather\r\n\r\n sep = shPool.cell(r,11).value \r\n EPSEP[key] = sep\r\n dia = shPool.cell(r,10).value \r\n for e in lEvent:\r\n if e.Key == key:\r\n epff = e.Frequency*e.PImdIgn\r\n EPFreq[key] = epff\r\n e.EarlyPoolFire = EarlyPoolFire(dia,sep,epff)\r\n break\r\n\r\n\r\n\r\nif 'Late Pool Fire' in cExl.sheetnames:\r\n shPool = cExl['Late Pool Fire']\r\n LPSEP = {}\r\n LPFreq = {}\r\n #Read Late Pool Fire\r\n for r in range(2,shPool.max_row+1):\r\n study_folder_pv = shPool.cell(r,1).value\r\n scenario = shPool.cell(r,2).value\r\n weather = shPool.cell(r,3).value\r\n # path = study_folder_pv + \"\\\\\" + scenario \r\n # key = path + \"\\\\\" + weather \r\n study,pv,folder = study_folder_pv.split(\"\\\\\")\r\n key = pv + \"\\\\\" + scenario + \"\\\\\" + weather\r\n sep = shPool.cell(r,11).value \r\n LPSEP[key] = sep\r\n dia = shPool.cell(r,10).value \r\n for e in lEvent:\r\n if e.Key == key:\r\n # epff = e.Frequency*(1-e.PImdIgn)*e.PDelIgn\r\n epff = e.Frequency*e.PDelIgn\r\n LPFreq[key] = epff\r\n e.LatePoolFire = LatePoolFire(dia,sep,epff)\r\n\r\n\r\n#shFireball\r\nif 'Fireball' in cExl.sheetnames:\r\n shFireball = cExl['Fireball']\r\n DiaFireball = {}\r\n SEPFireball = {}\r\n FireballFreq = {}\r\n #Read Flammable Dispersion\r\n for r in range(2,shFireball.max_row+1):\r\n study_folder_pv = shFireball.cell(r,1).value\r\n scenario = shFireball.cell(r,2).value\r\n weather = shFireball.cell(r,3).value\r\n # path = study_folder_pv + \"\\\\\" + scenario \r\n # key = path + \"\\\\\" + weather \r\n study,pv,folder = study_folder_pv.split(\"\\\\\")\r\n key = pv + \"\\\\\" + scenario + \"\\\\\" + weather\r\n \r\n dia = shFireball.cell(r,9).value \r\n sep = shFireball.cell(r,10).value \r\n \r\n DiaFireball[key] = dia\r\n SEPFireball[key] = sep\r\n \r\n for e in lEvent:\r\n if e.Key == key:\r\n ffireball = e.JetFire.Frequency\r\n FireballFreq[key] = ffireball\r\n e.Fireball = Fireball(ffireball,dia,sep)\r\n\r\n\r\nwith open(element_dump_filename,'wb') as element_dump:\r\n dill.dump(lEvent,element_dump)\r\n\r\n\r\n\r\nF = Fe = Fl = 0.\r\nfor e in lEvent:\r\n if \"-L\" in e.Key:\r\n F += e.Frequency\r\n if e.EarlyPoolFire is not None: \r\n Fe += e.EarlyPoolFire.Frequency\r\n if e.LatePoolFire is not None: \r\n Fl += e.LatePoolFire.Frequency\r\n\r\nprint(\"{:15s} Liquid Leak Frequency: {:.2e}\".format(Area, F))\r\nprint(\"{:15s} Pool fire Toal Frequency: Early {:.2e} Late {:.2e}\".format(Area, Fe,Fl))\r\n# print(\"{:15s} Pool fire Toal Frequency: {:.2e}\".format(Area, sum(EPFreq.values()) + sum(LPFreq.values())))\r\n","sub_path":"PyExdCrv4.py","file_name":"PyExdCrv4.py","file_ext":"py","file_size_in_byte":46032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536089659","text":"class Animal():\n def __init__(self, name, *gametes):\n self.name = name\n self.gametes = gametes\n\n\nclass plant():\n def __init__(self, name, phenotype, numberOfTraits):\n self.name = name\n self.gametes = [\"\"] * 2 ** numberOfTraits\n print(self.gametes)\n aList = [0] * numberOfTraits\n count = 0\n base = 0\n for i in range(len(aList)):\n aList[i] = base\n base += 2\n for trait in range(2 ** numberOfTraits):\n binary = str(bin(count)[2:])\n print(binary)\n # print(type(binary), len(binary))\n if len(binary) == 2: binary = \"0\" + binary\n if len(binary) == 1: binary = \"00\" + binary\n if numberOfTraits == 2: binary = binary[1:]\n print(binary)\n for index in range(len(binary)):\n if binary[index] == \"0\":\n self.gametes[count] += phenotype[aList[index]]\n else:\n self.gametes[count] += phenotype[aList[index + 1]]\n count += 1\n\n\ndef crossGamete(genes, gamete1, gamet2):\n gene = gamete1[0] + gamet2 + gamete1[1]\n for i in range(0, len(gene), len(gamete1)):\n if gene[i].islower() and gene[i + 1].isupper():\n gene = list(gene)\n gene[i] = gene[i].upper()\n gene[i + 1] = gene[i + 1].lower()\n gene = \"\".join(gene)\n print(gene)\n for geneInList in genes:\n if gene == geneInList[0]:\n geneInList[1] += 1\n return genes\n genes.append([gene, 1])\n return genes\n\n\ndef crossAnimal(animal1, animal2):\n list = []\n for gametes1 in animal1.gametes:\n for gametes2 in animal2.gametes:\n list = crossGamete(list, gametes1, gametes2)\n return list\n\n\ndef phenotypicRatio(traits, legend):\n count = 0\n for trait in traits:\n for phenotype in legend:\n if trait[0] in phenotype:\n phenotype[-1] += trait[1]\n count += trait[1]\n print(legend)\n for phenotype in legend: phenotype[-1] = phenotype[-1] / float(count)\n return legend\n\n\np1 = plant(\"pea1\", \"YR\", 6)\np2 = plant(\"pea1\", \"yr\", 2)\nprint(crossGamete([\"YR\", \"Yr\", \"yR\", \"yr\"], p1, p2))\n\n# HypothesisOfDependentAssortmentEgg = plant(\"pea1\", \"YYRR\", 2)\n# HypothesisOfDependentAssortmentSperm = plant(\"pea2\", \"yyrr\", 2)\n# v = crossAnimal(HypothesisOfDependentAssortmentEgg, HypothesisOfDependentAssortmentSperm)\n# legend = [[\"Yellow and Plump\", \"YYRR\", \"YYRr\", \"YyRR\", \"YyRr\", 0],\n# [\"Green and shriveled\", \"yyrr\", 0]]\n# results = phenotypicRatio(v, legend)\n# for dataPoint in results:\n# print(dataPoint[0] + \" : \" + str(dataPoint[1:-1])[1:-1] + \" : \" + str(dataPoint[-1] * 100) + \"%\")\n#\n# print(\"------************-------------\")\n# HypothesisOfIndependentAssortmentEgg_YYRR = plant(\"pea1\", \"YYRR\", 2)\n# HypothesisOfIndependentAssortmentSperm_yyrr = plant(\"pea2\", \"yyrr\", 2)\n# v = crossAnimal(HypothesisOfIndependentAssortmentEgg_YYRR, HypothesisOfIndependentAssortmentSperm_yyrr)\n# legend = [[\"Yellow and Plump\", \"YYRR\", \"YYRr\", \"YyRR\", \"YyRr\", 0],\n# [\"Green and Plump\", \"yyRR\", \"yyRr\", 0],\n# [\"Yellow and shriveled\", \"YYrr\", \"Yyrr\", 0],\n# [\"Green and shriveled\", \"yyrr\", 0]]\n# results = phenotypicRatio(v, legend)\n# for dataPoint in results:\n# print(dataPoint[0] + \":\" + str(dataPoint[-1] * 100) + \"%\")\n#\n# print(\"\\nGeneration 2\")\n# HypothesisOfIndependentAssortmentEggGen2_YYRr = plant(\"pea1\", \"Yyrr\", 2)\n# HypothesisOfIndependentAssortmentSpermGen2_Yyrr = plant(\"pea2\", \"Yyrr\", 2)\n# v = crossAnimal(HypothesisOfIndependentAssortmentEggGen2_YYRr, HypothesisOfIndependentAssortmentSpermGen2_Yyrr)\n# legend = [[\"Yellow and Plump\", \"YYRR\", \"YYRr\", \"YyRR\", \"YyRr\", 0],\n# [\"Green and Plump\", \"yyRR\", \"yyRr\", 0],\n# [\"Yellow and shriveled\", \"YYrr\", \"Yyrr\", 0],\n# [\"Green and shriveled\", \"yyrr\", 0]]\n# results = phenotypicRatio(v, legend)\n# for dataPoint in results:\n# print(dataPoint[0] + \":\" + str(dataPoint[-1] * 100) + \"%\")\n#\n# print(\"------************----maybe do incomplete dominance pg 272---------\")\n# HypothesisOfDependent_assortment_egg = Animal(\"pea1\", \"R\", \"W\")\n# HypothesisOfDependent_assortment_sperm = Animal(\"pea2\", \"R\", \"W\")\n# v = crossAnimal(HypothesisOfDependent_assortment_egg, HypothesisOfDependent_assortment_sperm)\n# legend = [[\"Yellow and Plump\", \"YYRR\", \"YYRr\", \"YyRR\", \"YyRr\", 0],\n# [\"Green and shriveled\", \"yyrr\", 0]]\n# results = phenotypicRatio(v, legend)\n# for dataPoint in results:\n# print(dataPoint[0] + \":\" + str(dataPoint[-1]*100) + \"%\")\n","sub_path":"DNA/genetics lab.py","file_name":"genetics lab.py","file_ext":"py","file_size_in_byte":4612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"246564927","text":"# import modules\nimport functions.f_movement as f_move\nimport functions.f_load_data as f_load\nimport os\nimport pickle\n\n# obtain the names, csv_files, path, start_dt, end_dt\nnames = f_load.names\ncsv_files = f_load.csv_files\npath = f_load.path\nstart_dt = f_load.start_dt\nend_dt = f_load.end_dt\n\n# calculate movement\nmove = f_move.predict_movement(csv_files, names, path, start_dt, end_dt)\nmove.get_movements()\n\n# get the movement dataframe\nmove.periods_of_volatility()\nmovement = move.dataframe\nprint(movement)\n\n# save the volatility_dataframe into pickle\nfile_path = os.path.dirname(os.path.realpath(__file__))\nsave_path = file_path + '/docs/' + 'movement.pickle'\nwith open(save_path, 'wb') as f:\n pickle.dump(movement, f)\n","sub_path":"movement.py","file_name":"movement.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"287094734","text":"import unittest\nfrom random import randint\n\n\ndef insertion_sort(array):\n for i in range(1, len(array)):\n j = i-1\n current = array[i]\n while array[j] > current and j >= 0:\n array[j+1] = array[j]\n j -= 1\n array[j+1] = current\n\n\nclass InsertionSortTest(unittest.TestCase):\n\n def setUp(self):\n self.array = [randint(0, 100) for i in range(26)]\n\n def test_insertion_sort(self):\n print(self.array)\n insertion_sort(self.array)\n self.assertEqual(self.array, sorted(self.array))\n print(self.array)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"331235281","text":"class Solution(object):\n def fullJustify(self, words, maxWidth):\n \"\"\"\n :type words: List[str]\n :type maxWidth: int\n :rtype: List[str]\n \"\"\"\n lines = []\n while words:\n length, idx = 0, 0\n while idx < len(words) and length + idx - 1 <= maxWidth:\n length += len(words[idx])\n idx += 1\n\n if length + idx - 1 > maxWidth:\n lines.append(words[:idx-1])\n words = words[idx-1:]\n elif idx == len(words):\n lines.append(words[:idx])\n words = words[idx:]\n\n res = []\n for s in lines[:-1]:\n res.append(self.fullyHandle(s, maxWidth))\n res.append(self.leftHandle(lines[-1], maxWidth))\n\n return res\n\n\n def fullyHandle(self, words, maxWidth):\n if len(words) == 1:\n return words[0] + ' ' * (maxWidth - len(words[0]))\n sum_len = sum(len(i) for i in words)\n d, m = divmod(maxWidth - sum_len, len(words) - 1)\n res = ''\n for i, word in enumerate(words):\n if i < m:\n res += word + ' ' * (d + 1)\n else:\n res += word + ' ' * d\n res = res[:maxWidth] + ' ' * (maxWidth - len(res))\n\n return res\n\n\n def leftHandle(self, words, maxWidth):\n res = ' '.join(words)\n res = res + ' ' * (maxWidth - len(res))\n\n return res\n\n","sub_path":"0068_text_justification/text_justification.py","file_name":"text_justification.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"402316593","text":"from core.colored_grid import ColoredGrid\nfrom generators.binary_tree import BinaryTree\n\ngrid = ColoredGrid(50,50)\nBinaryTree.on(grid)\n\nstart = grid[0][0]\n\ngrid.distances(start.distances())\n\nimage = grid.to_png()\nimage.save(\"results/colorize.png\")\n","sub_path":"coloring_demo.py","file_name":"coloring_demo.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"334244320","text":"#!/usr/bin/env python3\n\nfrom argparse import ArgumentParser\nfrom os import environ\nfrom pathlib import Path\nfrom shutil import rmtree\nfrom subprocess import run\nfrom sys import exit\n\nPACKAGE = 'bidso'\n\nparser = ArgumentParser(prog='make',\n description=f'Run tests and documentation for {PACKAGE}')\nparser.add_argument('-r', '--release', action='store_true',\n help='create a point release')\nparser.add_argument('-m', '--major_release', action='store_true',\n help='create a major release')\nparser.add_argument('-t', '--tests', action='store_true',\n help='run tests')\nparser.add_argument('-d', '--docs', action='store_true',\n help='create documentations (run tests first)')\nparser.add_argument('-c', '--clean', action='store_true',\n help='clean up docs (including intermediate files)')\n\nargs = parser.parse_args()\n\n\nBASE_PATH = Path(__file__).resolve().parent\nPKG_PATH = BASE_PATH / PACKAGE\nDOCS_PATH = BASE_PATH / 'docs'\nBUILD_PATH = DOCS_PATH / 'build'\nSOURCE_PATH = DOCS_PATH / 'source'\n# this is where the documentation has been built (needs to match travis deploy)\nHTML_PATH = BUILD_PATH / 'html'\nAPI_PATH = SOURCE_PATH / 'api'\nTEST_PATH = BASE_PATH / 'tests'\nCOV_PATH = BASE_PATH / 'htmlcov'\nDATA_PATH = TEST_PATH / 'data'\n\nVER_PATH = PKG_PATH / 'VERSION'\nCHANGES_PATH = BASE_PATH / 'CHANGES.rst'\n\n\ndef _new_version(level):\n\n # read current version (and changelog)\n with VER_PATH.open() as f:\n major, minor = f.read().rstrip('\\n').split('.')\n major, minor = int(major), int(minor)\n\n with CHANGES_PATH.open() as f:\n changes = f.read().split('\\n')\n\n # update version (if major, reset minor)\n if level == 'major':\n major += 1\n minor = 1\n elif level == 'minor':\n minor += 1\n version = '{:d}.{:02d}'.format(major, minor)\n\n # ask user for comment\n comment = input('Comment for {} release v{}: '.format(level, version))\n if comment == '':\n print('empty comment, aborted')\n return\n\n # update change log\n ver_comment = '- **' + version + '**: ' + comment\n\n if level == 'major':\n marker = '=========='\n TO_ADD = ['Version ' + str(major),\n '----------',\n ver_comment,\n '',\n ]\n\n elif level == 'minor':\n marker = '----------'\n TO_ADD = [ver_comment,\n ]\n\n index = changes.index(marker) + 1\n changes = changes[:index] + TO_ADD + changes[index:]\n with CHANGES_PATH.open('w') as f:\n f.write('\\n'.join(changes))\n\n with VER_PATH.open('w') as f:\n f.write(version + '\\n')\n\n return version, comment\n\n\ndef _release(level):\n \"\"\"TODO: we should make sure that we are on master release\"\"\"\n version, comment = _new_version(level)\n\n if version is not None:\n\n run(['git',\n 'commit',\n str(VER_PATH.relative_to(BASE_PATH)),\n str(CHANGES_PATH.relative_to(BASE_PATH)),\n '--amend',\n '--no-edit',\n ])\n run(['git',\n 'tag',\n '-a',\n 'v' + version,\n '-m',\n '\"' + comment + '\"',\n ])\n run(['git',\n 'push',\n 'origin',\n '--tags',\n ])\n run(['git',\n 'push',\n 'origin',\n 'master',\n '-f',\n ])\n\n\ndef _tests():\n CMD = ['pytest',\n f'--cov={PACKAGE}',\n '--cov-report=term',\n 'tests',\n ]\n\n # html report if local\n if not environ.get('CI', False):\n CMD.insert(1, '--cov-report=html')\n\n output = run(CMD)\n return output.returncode\n\n\ndef _docs():\n run([\n 'sphinx-apidoc',\n '-f',\n '-e',\n '--module-first',\n '-o',\n str(API_PATH),\n str(PKG_PATH),\n ])\n output = run(['sphinx-build',\n '-T',\n '-b',\n 'html',\n '-d',\n str(BUILD_PATH / 'doctrees'),\n str(SOURCE_PATH),\n str(HTML_PATH),\n ])\n return output.returncode\n\n\ndef _clean_all():\n rmtree(BUILD_PATH, ignore_errors=True)\n rmtree(API_PATH, ignore_errors=True)\n rmtree(DATA_PATH, ignore_errors=True)\n\n # also remove coverage folder\n rmtree(COV_PATH, ignore_errors=True)\n\n\nif __name__ == '__main__':\n returncode = 0\n\n if args.clean:\n _clean_all()\n\n if args.tests:\n _clean_all()\n returncode = _tests()\n\n if args.docs:\n returncode = _docs()\n\n if args.release:\n _release('minor')\n\n if args.major_release:\n _release('major')\n\n exit(returncode)\n","sub_path":"make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252618155","text":"from i8自动化测试框架.comment.pageDriver import Action\nimport pyautogui as pyautogui\nfrom i8自动化测试框架.comment import getValueFromExcel\nfrom selenium.webdriver.common.by import By\nimport time\nimport json\n'''\nstep one:新增\nstep two:表头录入\nstep three:表体录入\n'''\ntimestamp = str(int(round(time.time() * 1000)))\n\nclass allot_in(Action):\n def __init__(self, driver=None):\n Action.__init__(self, driver)\n self.fileName = \"mi8-调拨入库.xlsx\"\n\n def test_调拨入库(self):\n self.getUrl(\"PMM\", \"调拨入库\")\n self.driver.implicitly_wait(5)\n self.maxWindows()\n self.driver.implicitly_wait(2)\n self.switchFrame(By.XPATH, \"/html[1]/body[1]/div[4]/div[2]/div[2]/div[1]/span[1]/div[1]/iframe[1]\")\n self.driver.implicitly_wait(1)\n time.sleep(5)\n self.clickElements(\"xpath\", \"//span[contains(text(),'新增')]\", 1)\n time.sleep(2)\n self.switchToParentFrame()\n self.switchFrame(By.XPATH, \"/html[1]/body[1]/div[4]/div[2]/div[3]/div[1]/span[1]/div[1]/iframe[1]\")\n time.sleep(2)\n print(\"step one\")\n # 项目名称\n PhidTrProj = getValueFromExcel.getExcelValue(self.fileName, 5, 2)\n # 仓库编码\n PhidWarehouse = getValueFromExcel.getExcelValue(self.fileName, 5, 3)\n # 调出项目\n PhidInOutProj = getValueFromExcel.getExcelValue(self.fileName, 5, 4)\n # 调入仓库\n PhidInOutWarehouse = getValueFromExcel.getExcelValue(self.fileName, 5, 5)\n self.projectHelpChoose(PhidTrProj, By.NAME, \"PhidTrProj\")\n time.sleep(2)\n self.projectHelpChoose(PhidWarehouse, By.NAME, \"PhidWarehouse\")\n time.sleep(2)\n self.projectHelpChoose(PhidInOutProj, By.NAME, \"PhidInOutProj\")\n time.sleep(2)\n self.projectHelpChoose(PhidInOutWarehouse, By.NAME, \"PhidInOutWarehouse\")\n time.sleep(2)\n print(\"step two\")\n #物料\n self.clickElement(\"xpath\", \"//span[contains(text(),'增行')]\")\n #物料名称\n Sou_name = getValueFromExcel.getExcelValue(self.fileName, 5, 1, \"allot_in_body\")\n #物料编码\n Source = getValueFromExcel.getExcelValue(self.fileName, 5, 2, \"allot_in_body\")\n #数量\n qty = getValueFromExcel.getExcelValue(self.fileName, 5, 3, \"allot_in_body\")\n #单价\n Prc = getValueFromExcel.getExcelValue(self.fileName, 5, 4, \"allot_in_body\")\n\n #添加物料\n time.sleep(3)\n self.sendKeys(Source, By.NAME, \"Code*str*like\")\n time.sleep(3)\n self.sendKeys(Sou_name, By.NAME, \"Name*str*like\")\n time.sleep(3)\n self.clickElement(\"xpath\", \"//span[contains(text(),'查 询')]/..//span[2]\")\n time.sleep(5)\n self.clickElement(\"xpath\", \"//span[contains(text(),'>>')]/..//span[2]\")\n time.sleep(3)\n self.clickElement(\"xpath\", \"//span[contains(text(),'确定')]/..//span[2]\")\n print(\"step three\")\n\n self.clickElement(\"xpath\",\n \"/html[1]/body[1]/div[2]/div[1]/div[2]/div[1]/div[4]/div[2]/div[1]/table[1]/tbody[1]/tr[1]/td[10]/div[1]\")\n time.sleep(0.5)\n self.sendKeys(qty, By.NAME, \"Qty\")\n time.sleep(2)\n self.clickElement(\"xpath\",\n \"/html[1]/body[1]/div[2]/div[1]/div[2]/div[1]/div[4]/div[2]/div[1]/table[1]/tbody[1]/tr[1]/td[11]/div[1]\")\n time.sleep(0.5)\n self.sendKeys(Prc, By.NAME, \"Prc\")\n time.sleep(0.5)\n self.clickElement(\"name\", \"Billno\")\n\n time.sleep(2)\n self.clickElement(\"xpath\", \"//span[contains(text(),'保存')]/../span[2]\")\n time.sleep(2)\n self.clickElement(\"xpath\", \"//span[contains(text(),'确定')]/../span[2]\")\n time.sleep(3)\n","sub_path":"i8自动化测试框架/case/MI8/test_调拨入库.py","file_name":"test_调拨入库.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"230245972","text":"from django.test import TestCase\n\nfrom projects.models import Project\nfrom staff.models import Staff\nfrom ticket.forms import TicketForm\nfrom ticket.models import Prioritaet\n\n\nclass FormTestCase(TestCase):\n\n def setUp(self):\n Prioritaet.objects.create(name='Normal')\n Project.objects.create(name='test')\n Staff.objects.create(name='test',\n initialies='tt',\n email='test@test.com',\n loginname='test',\n accessinvoice=False,\n accessstatistics=False\n )\n\n def test_ticket_form_valid(self):\n staff = Staff.objects.get(name='test')\n form = TicketForm(data={\n 'subject': 'test',\n 'project': 1, # value=1 from select field\n 'from_email': staff,\n 'comment': 'help',\n 'file': '',\n })\n self.assertTrue(form.is_valid())\n\n def test_ticket_form_invalid(self):\n form = TicketForm(data={\n 'subject': '',\n 'from_email': '',\n 'comment': 'help',\n 'file': '',\n })\n self.assertFalse(form.is_valid())","sub_path":"ticket/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"88235467","text":"import allure\nfrom selenium import webdriver\nimport pytest\nfrom pages.homePage import HomePage\nfrom pages.loginPage import LoginPage\nfrom utils import data\nimport moment\n\n@pytest.mark.usefixtures(\"test_setup\")\nclass TestLogin:\n\n def test_login(self):\n driver = self.driver\n lp = LoginPage(driver)\n lp.enter_username(data.UserName)\n lp.enter_passowrd(data.PassWord)\n lp.click_on_login()\n\n def tes_logout(self):\n driver = self.drive\n hp = HomePage(driver)\n hp.click_on_Welcome_btn()\n hp.click_on_LogOut_link()\n\n def test_login1(self):\n try:\n driver = self.driver\n lp = LoginPage(driver)\n lp.enter_username(data.UserName)\n lp.enter_passowrd(data.PassWord)\n lp.click_on_login()\n x=driver.title\n assert x==\"abc\"\n except AssertionError as e:\n print(\"Assertion Error occurred\")\n print(e)\n #Screen capture\n currentTime=moment.now().strftime(\"%d-%m-%y:%H-%M-%S\")\n testName=data.whoami()\n screenshotName=testName+\"_\"+currentTime\n allure.attach(self.driver.get_screenshot_as_png(),name=screenshotName,\n attachment_type=allure.attachment_type.PNG)\n raise\n except:\n print(\"There was an exception\")\n raise\n else:\n print(\"No exception occured\")\n finally:\n print(\"I am inside finally blok\")\n def tes_logout1(self):\n driver = self.drive\n hp = HomePage(driver)\n hp.click_on_Welcome_btn()\n hp.click_on_LogOut_link()\n","sub_path":"tests/test_loginfunctionality.py","file_name":"test_loginfunctionality.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"446866613","text":"import sys\n\nsys.path.append('../..')\nimport torch\nimport numpy as np\nimport scipy.io\nfrom gpinn.burgers import train, Generator, Encoder, Reconstructor, Discriminator\nfrom pathlib import Path\nfrom datetime import datetime\n\n\nif __name__ == '__main__':\n torch.manual_seed(1234)\n np.random.seed(5678)\n\n save_path = Path(f'./{datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")}')\n save_path.mkdir(parents=True, exist_ok=True)\n save_freq = 10000\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n torch.backends.cudnn.benchmark = True\n\n data = scipy.io.loadmat('../.data/cheb.nu0.03_ni1.mat')\n nu = data['nu'][0, 0]\n x0 = data['x0']\n t0 = data['t']\n idx_train = data['idx_train'].flatten()\n n_i = idx_train.shape[-1]\n u0 = torch.tensor(data['u0'][idx_train, :], dtype=torch.float)\n\n t_dom = (data['t'][0, 0], data['t'][-1, 0])\n n_t = 200\n t = torch.linspace(t_dom[0], t_dom[-1], n_t)\n\n x_dom = (data['x0'][0, 0], data['x0'][-1, 0])\n x = torch.tensor(data['x0'].flatten(), dtype=torch.float)\n n_x = x.numel()\n\n n_col = (200, 500)\n\n epochs = 40000\n init_bs = 100\n col_bs = 1000\n bc_bs = 50\n r_bs = init_bs\n\n # good: 10, 100, 10, 10, 0.2, 0.8\n alpha = 30\n beta = 100\n gamma = 30\n delta = 30\n label_noise = 0.2\n label_true = 0.8\n\n t = t.to(device)\n x = x.to(device)\n u0 = u0.to(device)\n\n # Network\n z_dim = 32\n v_dim = 32\n layers_gen = [2 + v_dim, 256, 256, 256, 256, 256, 1]\n layers_rec = [3, 256, 256, 256, v_dim]\n layers_enc = [n_x + z_dim, 256, 256, 256, v_dim]\n layers_dis = [3, 256, 256, 256, 1]\n lr_gen = 0.0001\n lr_dis = 0.0002\n\n gen = Generator(layers_gen).to(device)\n rec = Reconstructor(layers_rec).to(device)\n enc = Encoder(layers_enc).to(device)\n dis = Discriminator(layers_dis).to(device)\n\n optimizer_gen = torch.optim.Adam([{'params': gen.parameters(), 'lr': lr_gen},\n {'params': rec.parameters(), 'lr': lr_gen},\n {'params': enc.parameters(), 'lr': lr_gen}])\n optimizer_dis = torch.optim.Adam([{'params': dis.parameters(), 'lr': lr_dis}])\n\n params_to_save = {'layers_dec': layers_gen, 'layers_enc': layers_enc,\n 'layers_rec': layers_rec, 'layers_dis': layers_dis,\n 'z_dim': z_dim, 'v_dim': v_dim,\n 'alpha': alpha, 'beta': beta, 'gamma': gamma, 'delta': delta,\n 'label_noise': label_noise, 'label_true': label_true,\n 'lr_dec': lr_gen, 'lr_dis': lr_dis, 'epochs_num': epochs,\n 't_dom': t_dom, 'x_dom': x_dom, 'n_x': n_x, 'n_i': n_i,\n 'n_col': n_col, 'col_bs': col_bs, 'init_bs': init_bs, 'bc_bs': bc_bs, 'n_t': n_t,\n 'nu': nu}\n scipy.io.savemat(save_path / f'.params.mat', params_to_save)\n\n params = {'col_bs': col_bs, 'n_col': n_col, 'init_bs': init_bs, 'r_bs': r_bs, 'n_i': n_i, 'z_dim': z_dim,\n 'alpha': alpha, 'beta': beta, 'gamma': gamma, 'delta': delta,\n 'label_noise': label_noise, 'label_true': label_true, 'bc_bs': bc_bs, 'n_t': n_t,\n 'save_path': save_path, 'save_freq': save_freq,\n 'nu': nu}\n\n train(epochs, gen, enc, rec, dis, optimizer_gen, optimizer_dis, t, x, u0, params, device)\n","sub_path":"report/experiment_01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87470027","text":"# pylint: skip-file\n\nimport time\n\nclass RouterConfig(object):\n ''' RouterConfig is a DTO for the router. '''\n def __init__(self, rname, kubeconfig, router_options):\n self.name = rname\n self.kubeconfig = kubeconfig\n self._router_options = router_options\n\n @property\n def router_options(self):\n ''' return router options '''\n return self._router_options\n\n def to_option_list(self):\n ''' return all options as a string'''\n return RouterConfig.stringify(self.router_options)\n\n @staticmethod\n def stringify(options):\n ''' return hash as list of key value pairs '''\n rval = []\n for key, data in options.items():\n if data['include'] and data['value']:\n rval.append('--%s=%s' % (key.replace('_', '-'), data['value']))\n\n return rval\n\nclass Router(OpenShiftCLI):\n ''' Class to wrap the oc command line tools '''\n def __init__(self,\n router_config,\n verbose=False):\n ''' Constructor for OpenshiftOC\n\n a router consists of 3 or more parts\n - dc/router\n - svc/router\n - endpoint/router\n '''\n super(Router, self).__init__('default', router_config.kubeconfig, verbose)\n self.rconfig = router_config\n self.verbose = verbose\n self.router_parts = [{'kind': 'dc', 'name': self.rconfig.name},\n {'kind': 'svc', 'name': self.rconfig.name},\n #{'kind': 'endpoints', 'name': self.rconfig.name},\n ]\n def get(self, filter_kind=None):\n ''' return the self.router_parts '''\n rparts = self.router_parts\n parts = []\n if filter_kind:\n rparts = [part for part in self.router_parts if filter_kind == part['kind']]\n\n for part in rparts:\n parts.append(self._get(part['kind'], rname=part['name']))\n\n return parts\n\n def exists(self):\n '''return a deploymentconfig by name '''\n parts = self.get()\n for part in parts:\n if part['returncode'] != 0:\n return False\n\n return True\n\n def delete(self):\n '''return all pods '''\n parts = []\n for part in self.router_parts:\n parts.append(self._delete(part['kind'], part['name']))\n\n return parts\n\n def create(self, dryrun=False, output=False, output_type='json'):\n '''Create a deploymentconfig '''\n # We need to create the pem file\n router_pem = '/tmp/router.pem'\n with open(router_pem, 'w') as rfd:\n rfd.write(open(self.rconfig.router_options['cert_file']['value']).read())\n rfd.write(open(self.rconfig.router_options['key_file']['value']).read())\n\n atexit.register(Utils.cleanup, [router_pem])\n self.rconfig.router_options['default_cert']['value'] = router_pem\n\n options = self.rconfig.to_option_list()\n\n cmd = ['router']\n cmd.extend(options)\n if dryrun:\n cmd.extend(['--dry-run=True', '-o', 'json'])\n\n results = self.openshift_cmd(cmd, oadm=True, output=output, output_type=output_type)\n\n return results\n\n def update(self):\n '''run update for the router. This performs a delete and then create '''\n parts = self.delete()\n if any([part['returncode'] != 0 for part in parts]):\n return parts\n\n # Ugly built in sleep here.\n time.sleep(15)\n\n return self.create()\n\n def needs_update(self, verbose=False):\n ''' check to see if we need to update '''\n dc_inmem = self.get(filter_kind='dc')[0]\n if dc_inmem['returncode'] != 0:\n return dc_inmem\n\n user_dc = self.create(dryrun=True, output=True, output_type='raw')\n if user_dc['returncode'] != 0:\n return user_dc\n\n # Since the output from oadm_router is returned as raw\n # we need to parse it. The first line is the stats_password\n user_dc_results = user_dc['results'].split('\\n')\n # stats_password = user_dc_results[0]\n\n # Load the string back into json and get the newly created dc\n user_dc = json.loads('\\n'.join(user_dc_results[1:]))['items'][0]\n\n # Router needs some exceptions.\n # We do not want to check the autogenerated password for stats admin\n if not self.rconfig.router_options['stats_password']['value']:\n for idx, env_var in enumerate(user_dc['spec']['template']['spec']['containers'][0]['env']):\n if env_var['name'] == 'STATS_PASSWORD':\n env_var['value'] = \\\n dc_inmem['results'][0]['spec']['template']['spec']['containers'][0]['env'][idx]['value']\n\n # dry-run doesn't add the protocol to the ports section. We will manually do that.\n for idx, port in enumerate(user_dc['spec']['template']['spec']['containers'][0]['ports']):\n if not port.has_key('protocol'):\n port['protocol'] = 'TCP'\n\n # These are different when generating\n skip = ['dnsPolicy',\n 'terminationGracePeriodSeconds',\n 'restartPolicy', 'timeoutSeconds',\n 'livenessProbe', 'readinessProbe',\n 'terminationMessagePath',\n 'rollingParams',\n ]\n\n return not Utils.check_def_equal(user_dc, dc_inmem['results'][0], skip_keys=skip, debug=verbose)\n","sub_path":"openshift/installer/vendored/openshift-ansible-git-2016-04-18/roles/lib_openshift_api/build/src/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":5467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"559281142","text":"gender = \"f\"\r\nif gender == \"f\":\r\n print (\"Welcome to Hear me Code!\")\r\nelse:\r\n print (\"No boys allowed!!\")\r\n\r\n\r\nstudents = 10\r\ncapacity = 50\r\n\r\nif students < capacity:\r\n print (\"Keep recruiting students\")\r\nelse:\r\n print (\"Close ticket sign-ups.\")\r\n\r\ntas = 5\r\nif tas == 0:\r\n print (\"uh-oh...\")\r\nelif tas < students / 5:\r\n print (\"Keep recruiting Teaching Assistants.\")\r\nelse:\r\n print (\"Aren't the TA's great though?\")\r\n\r\n#Simple conditionals\r\n#elif means else and if together\r\n","sub_path":"Simple Conditionals.py","file_name":"Simple Conditionals.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"61472801","text":"\r\nbaza = []\r\n\r\nwith open(\"osoby.txt\") as plik:\r\n # lista kolumn\r\n opis_kolumn = plik.readline()\r\n\r\n for line in plik:\r\n # usuwamy białe znaki whitespace\r\n line = line.strip()\r\n\r\n osoba = line.split(\",\")\r\n\r\n baza.append(osoba)\r\nprint(baza)\r\n\r\nfor wpis in baza:\r\n print(wpis[0])","sub_path":"day7/csv_read.py","file_name":"csv_read.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"221192888","text":"# coding:utf-8\n\nimport os\nimport time\nimport logging\n\nimport numpy as np\nimport tensorflow as tf\nimport cloudpickle\nimport random\n\nlogging.basicConfig(format=logging.BASIC_FORMAT, level=logging.INFO)\n\n# File paths\nPATH_TRAIN_PICKLE = './dataset/dataset_train_encoded.pyk'\nPATH_TEST_PICKLE = './dataset/dataset_test_encoded.pyk'\n\n# Model hyperparams. See Riedel et al. for details\nINPUT_LAYER_SIZE = 5000\nHIDDEN_LAYER_SIZE = 100\nAMOUNT_CLASSES = 4\n\nDROPOUT_KEEP_P = 0.6\nL2_LAMBDA = 1e-5 # < paper says 1e-4, code uses 1e-5 (typo?)\nLEARNING_RATE = 1e-2\nGRAD_CLIP_RATIO = 5\n\nTRAIN_BATCH_SIZE = 500\nEPOCHS = 30 # < similar results are achieved w/ lesser epochs\n\nlogging.info('Loading train set')\nwith open(PATH_TRAIN_PICKLE, 'rb') as file:\n stash = cloudpickle.load(file)\n X_train = np.asarray(stash['X'])\n y_train = np.asarray(stash['y'])\n\nlogging.info('Loading test set')\nwith open(PATH_TEST_PICKLE, 'rb') as file:\n X_test = cloudpickle.load(file)['X']\n X_test = np.asarray(X_test)\n\n# Discovering the amount of samples (n) features (m)\nn = len(X_train)\nm = len(X_train[0])\n\ndef build_graph():\n # input paths\n x_pl = tf.placeholder(tf.float32, [None, m], 'x_layer')\n y_pl = tf.placeholder(tf.int64, [None], 'y_placeholder')\n training_pl = tf.placeholder(tf.bool, name='train_mode')\n\n # Magic trick to get the size of the batch without hard coding\n batch_size = tf.shape(x_pl)[0]\n\n # NN architecture\n hidden_layer = tf.layers.dropout(tf.nn.relu(tf.contrib.layers.linear(x_pl, HIDDEN_LAYER_SIZE)), rate=DROPOUT_KEEP_P, training=training_pl)\n linear_layer = tf.layers.dropout(tf.contrib.layers.linear(hidden_layer, AMOUNT_CLASSES), rate=DROPOUT_KEEP_P, training=training_pl)\n\n logits = tf.reshape(linear_layer, [batch_size, AMOUNT_CLASSES])\n\n # adding regularization\n ws = tf.trainable_variables()\n l2_reg = tf.add_n([tf.nn.l2_loss(w) for w in ws if 'bias' not in w.name]) * L2_LAMBDA \n\n # computing cross-entropy loss\n J = tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y_pl) + l2_reg)\n\n # adding prediction paths. Shortcut for prediction\n predict = tf.argmax(logits, axis=1, name='predict')\n\n return (x_pl, y_pl, training_pl, ws, J, predict)\n\n\n# getting paths to the compute graph\nx_pl, y_pl, training_pl, W, loss_function, predict = build_graph()\n\noptimizer = tf.train.AdamOptimizer(LEARNING_RATE)\n\n# clipping the gradients, as described in the paper\ngrads = tf.gradients(loss_function, W)\nclipped_grads, _ = tf.clip_by_global_norm(grads, clip_norm=GRAD_CLIP_RATIO)\n\n# optimizing with clipped grads\noptimization_step = optimizer.apply_gradients(zip(clipped_grads, W))\n\nstart_time = time.time()\nwith tf.Session() as session:\n session.run(tf.global_variables_initializer())\n\n total_loss = 0\n for epoch in range(EPOCHS):\n logging.info('Training epoch {}/{}'.format(epoch+1, EPOCHS))\n\n # shuffling training samples for each epoch\n samples_indices = list(range(n))\n random.shuffle(samples_indices)\n epoch_loss = 0\n\n for i in range(n // TRAIN_BATCH_SIZE):\n start = i * TRAIN_BATCH_SIZE\n indices = samples_indices[start:start+TRAIN_BATCH_SIZE]\n\n X_batch = X_train[indices]\n y_batch = y_train[indices]\n\n _, Jt = session.run([optimization_step, loss_function], feed_dict={\n x_pl: X_batch,\n y_pl: y_batch,\n training_pl: True\n })\n\n epoch_loss += Jt\n\n logging.info('Done. Cost function: {:4.4}'.format(epoch_loss))\n\n print('Training finished. It took {} s.'.format(time.time() - start_time))\n\n # persisting the model\n tf.train.Saver().save(session, os.path.join(os.getcwd(), 'model/model'))\n\n","sub_path":"trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"617762168","text":"#touchscreenkeyboard\nfrom collections import *\nfrom typing import *\nimport io, os, sys\n_fast_readline = io.BytesIO(os.read(0, 2147483647)).readline\n_readline = lambda: _fast_readline().decode()\nread_line = lambda: _readline().strip()\nread_list = lambda: _readline().strip().split(' ')\nread_lines_list = lambda n_lines: [_readline().strip() for _ in range(0, n_lines)]\nread_int = lambda: int(_readline())\nread_int_list = lambda: [int(x) for x in read_list]\nwrite = lambda *msg: sys.stdout.write(' '.join(list(map(str, msg))))\nwriteln = lambda *msg: sys.stdout.write(' '.join(list(map(str, msg))) + '\\n')\n\nclass Graph:\n def __init__(self):\n self.graph = [list(word) for word in [\"qwertyuiop\", \"asdfghjkl\", \"zxcvbnm\"]]\n\n self.loc = {}\n for row in range(len(self.graph)):\n for col in range(len(self.graph[row])):\n self.loc[self.graph[row][col]] = (col, row)\n\n def dist(self, c1, c2):\n return abs(self.loc[c1][0] - self.loc[c2][0]) + abs(self.loc[c1][1] - self.loc[c2][1])\n\ndef solve_case(graph: Graph):\n word, n_words = read_list()\n words_dist = sorted([(sum([graph.dist(w[i], word[i]) for i in range(len(w))]), w) for w in read_lines_list(int(n_words))])\n for l, w in words_dist:\n writeln(w, l)\n\ndef main() -> None:\n cases = read_int()\n graph = Graph()\n for _ in range(cases):\n solve_case(graph)\n\nif __name__ == '__main__':\n main()","sub_path":"kattis/touchscreenkeyboard/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"53295668","text":"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport os.path\nimport tempfile\n\nfrom oslo_config import cfg\nfrom oslo_config import fixture\n\nfrom subunit2sql.targets import localdir\nfrom subunit2sql.tests import base\n\n\nclass TestLocaldir(base.TestCase):\n def setUp(self):\n super(TestLocaldir, self).setUp()\n self.useFixture(fixture.Config(cfg.CONF))\n self.tdir = tempfile.mkdtemp()\n cfg.CONF.set_override(name='attachments_storage_dir',\n override=self.tdir)\n self.ad = localdir.AttachmentsDir()\n\n def test_localdir_enabled_when_configured(self):\n self.assertTrue(self.ad.enabled())\n\n def test_localdir_disabled_when_no_conf(self):\n cfg.CONF.clear_override(name='attachments_storage_dir')\n self.assertFalse(self.ad.enabled())\n\n def test_localdir_status_ignores_non_attachments(self):\n self.ad.status(test_id='foo.test',\n test_status='melancholy')\n self.ad.stopTestRun()\n self.assertEqual(0, len(os.listdir(self.tdir)))\n\n def test_localdir_saves_testless_attachments(self):\n self.ad.status(file_name='super.txt',\n file_bytes=b'the quick brown fox',\n route_code='routecode1')\n self.ad.status(file_name='super.txt',\n file_bytes=b'jumped over the lazy brown dog',\n route_code='routecode2')\n self.ad.stopTestRun()\n expected_path = os.path.join(self.tdir, 'routecode1', 'super.txt')\n self.assertTrue(os.path.exists(expected_path))\n with open(expected_path, 'rb') as f:\n self.assertEqual(b'the quick brown fox', f.read())\n expected_path = os.path.join(self.tdir, 'routecode2', 'super.txt')\n self.assertTrue(os.path.exists(expected_path))\n with open(expected_path, 'rb') as f:\n self.assertEqual(b'jumped over the lazy brown dog', f.read())\n","sub_path":"subunit2sql/tests/test_targets_localdir.py","file_name":"test_targets_localdir.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359980363","text":"from icalendar import Calendar, Event as IEvent\nfrom django.urls import reverse\nfrom django.template import loader\nfrom django.http import HttpResponse\nfrom .models import Letter\nfrom django.http import HttpResponseForbidden\nfrom ..authkey.parser import get_token\nfrom ..authkey.models import Key\nfrom datetime import timedelta\n\n\ncalendar_description_template = \"cases/letter/calendar_description.txt\"\nrefresh_props = [\n \"REFRESH-INTERVAL;VALUE=DURATION\",\n \"X-REFRESH-INTERVAL;VALUE=DURATION\",\n \"X-PUBLISHED-TTL\",\n]\n\n\ndef get_uuid(obj, description=\"\"):\n import hashlib\n\n m = hashlib.sha512()\n m.update(str(obj.name).encode())\n m.update(str(obj.event.timestamp()).encode())\n m.update(str(description).encode())\n return m.hexdigest()\n\n\ndef ical(request):\n t = loader.get_template(calendar_description_template)\n\n token = get_token(request)\n if not token:\n return HttpResponseForbidden(\"Missing authentication token\")\n try:\n key = Key.objects.select_related(\"user\").get(token=token)\n except Key.DoesNotExist:\n return HttpResponseForbidden(\"Invalid authentication token\")\n if not key.has_scopes([\"export_ical\"]):\n return HttpResponseForbidden(\"Unauthorized operation for the token\")\n key.update_used_on()\n\n cal = Calendar()\n cal.add(\"prodid\", f\"-//small-eod//letters//{key.user}//\")\n cal.add(\"version\", \"2.0\")\n for name in refresh_props:\n cal.add(name, \"PT1H\")\n for obj in Letter.objects.exclude(event__isnull=True).select_related(\n \"case\", \"case__audited_institution\"\n ):\n letter = IEvent()\n url = request.build_absolute_uri(\n reverse(\"admin:cases_letter_change\", kwargs={\"object_id\": str(obj.pk)})\n )\n description = t.render({\"obj\": obj}, request).strip()\n categories = [obj.case]\n if obj.case and obj.case.audited_institution:\n categories.append(obj.case.audited_institution)\n letter.add(\"uid\", get_uuid(obj, description))\n letter.add(\"dtstart\", obj.event)\n letter.add(\"dtstamp\", obj.event)\n letter.add(\"summary\", obj.name)\n letter.add(\"url\", url)\n if description:\n letter.add(\"description\", description)\n letter.add(\"categories\", categories)\n cal.add_component(letter)\n return HttpResponse(content=cal.to_ical(), content_type=\"text/calendar\")\n","sub_path":"small_eod/cases/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"482681415","text":"\n## Simple Hypergraph Example\n\n# In[1]:\n\nimport pydecode.hyper as ph\nimport pydecode.display as display\n\n\n# In[2]:\n\nhyp = ph.Hypergraph()\nwith hyp.builder() as b:\n n1 = b.add_node(label = \"a\")\n n2 = b.add_node(label = \"b\")\n n3 = b.add_node(label = \"c\")\n n4 = b.add_node(label = \"d\")\n n5 = b.add_node((([n1, n2], \"edge1\"),), label = \"e\")\n b.add_node([([n5], \"edge3\"), ([n3, n4], \"edge2\")], label = \"root\")\n\ndef build_potentials(label):\n return {\"edge1\" : 3, \"edge2\" : 1, \"edge3\" : 1}[label]\npotentials = ph.Potentials(hyp).build(build_potentials)\n\n\n# Draw the graph\n\n# In[3]:\n\ndisplay.HypergraphPotentialFormatter(hyp, potentials).to_ipython()\n\n\n# Out[3]:\n\n# \n\n# In[4]:\n\npath = ph.best_path(hyp, potentials)\ndisplay.HypergraphPathFormatter(hyp, [path]).to_ipython()\n\n\n# Out[4]:\n\n# \n","sub_path":"notebooks/hypergraphs.py","file_name":"hypergraphs.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"548424562","text":"# coding=utf-8\n# Copyright 2018 The DisentanglementLib 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\"\"\"Various utilities used in the data set code.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport numpy as np\nimport math\nfrom six.moves import range\nfrom sklearn.utils import shuffle\nimport copy\n\n\nclass GenericSampling(object):\n \"\"\" @author: jboilard\n State space with factors split between latent variable and observations and sampling.\"\"\"\n\n def __init__(self, factor_sizes, latent_factor_indices, factors, observation_ids):\n self.factor_sizes = factor_sizes\n self.num_factors = len(self.factor_sizes)\n self.latent_factor_indices = latent_factor_indices\n self.observation_factor_indices = [i for i in range(self.num_factors)\n if i not in self.latent_factor_indices]\n \n self.num_total_atoms = np.prod(self.factor_sizes)\n self.factor_bases = self.num_total_atoms / np.cumprod(self.factor_sizes)\n \n #atom_grouped_observations is referenced by sampling_list\n self.atom_grouped_observations, self.sampling_list, self.factor_splices_count = self.get_sampling_elements(factors, observation_ids)\n self.initial_sampling_list = copy.deepcopy(self.sampling_list)\n self.initial_factor_splices_count = copy.deepcopy(self.factor_splices_count)\n self.sampled_list = []\n self.paired_sampled_list = []\n self.first_sample = True\n \n @property\n def num_latent_factors(self):\n return len(self.latent_factor_indices)\n \n def get_sampling_elements(self, factors, observation_ids):\n \"\"\" @author: jboilard\n Called at class object initialization, initializes sampling_list, \n atom_grouped_observations and factor_splices count class objects\n returns : \n atom_grouped_observations : orders spectrogram dataset ids according to a state-space index (atom) \n and lists together ids where sapectrograms have the same factors\n sampling_list : a list to shuffle, where one sample is a pair [state-space-index, occurence], \n these pairs reference the object atom_grouped_observations\n factor_splices_count : from a matrix which counts every possible factor combinations, sum the f0 dimension, f1 dimension, \n etc until a sum array is obtained for every dimension. \n This objhect is important to determine which factor values can or cannot be locked for the B-VAE algorithm and is updated at every sampling step\n splice_factor_count[n_factors, n_possible_factor_values]\"\"\"\n #Create sampling list atom_count_listand factor list\n factor_count_list = np.zeros(shape=self.factor_sizes)\n factor_splices_count = []\n \n feature_state_space_index = self._features_to_state_space_index(factors) #get state-space index of each factor\n atom_grouped_observations = []\n sampling_list = []\n for i in range(self.num_total_atoms):\n atom_grouped_observations.append([]) # initialize list\n \n #Create the atom_grouped_observation arrays and sampling_list\n for i, index in enumerate(feature_state_space_index):\n atom_grouped_observations[index].append(observation_ids[i])\n sampling_list.append([index, len(atom_grouped_observations[index]) - 1])\n \n #counts every factor combination\n for factor in factors:\n idx = tuple(factor)\n factor_count_list[idx] = factor_count_list[idx] + 1\n \n # reduce the factor combination count matrix ton 1-d by summing every other axis, for each dimension\n for i in range(self.num_factors):\n axis_squish_list = list(range(self.num_factors))\n axis_squish_list.remove(i)\n factor_splices_count.append(np.sum(factor_count_list, axis=tuple(axis_squish_list)))\n \n factor_splices_count = self.get_splices(factors, observation_ids)\n \n return atom_grouped_observations, sampling_list, factor_splices_count\n \n\n def get_splices(self, factors, observation_ids):\n \"\"\" @author: jboilard\n Method overrided depending on class\"\"\" \n return []\n \n def reset_sampling_objects(self):\n \"\"\" @author: jboilard\n Called when the sampling list is empty and more samples are required, or \n whenever a new experiment is started. Resets sampling_list and factor_splices_count to initial values\"\"\"\n self.sampling_list = copy.deepcopy(self.initial_sampling_list)\n self.factor_splices_count = copy.deepcopy(self.initial_factor_splices_count)\n \n def remove_sample_from_lists(self, factor_id):\n \"\"\" @author: jboilard\n Called whenever an observation is sampled, remove factor/sample from sampling_list \n also builds a \"sampled list\" to keep track of selected samples during evaluation\"\"\"\n #remove sample from list\n self.sampling_list.remove(factor_id)\n self.sampled_list.append(self._state_space_index_to_features(factor_id[0]))\n \n # def sample_possible_latent_factors(self, num, random_state, lock_id, possible_lock_vals):\n # \"\"\" @author: jboilard\n # Using a lock_id, corresponding to the locked factor, \n # sample another factor_set where the locked factor is the same than those specified in possible lock_vals\n # num : num samples to sample\n # random_state : enables repeatability of experiments by making sampling deterministic\n # lock_id : index of locked factor (e.g. pitch is locked, corresponding to lock_id 0)\n # possible_lock_vals : Presampled values. values in column lock_id must be the same than the \"num\" factors sampled \"\"\"\n # factors = []\n # obs_id = []\n \n # for i in range(num):\n # factor_id = None\n # self.sampling_list = shuffle(self.sampling_list, random_state=random_state)\n \n # for sample in self.sampling_list:\n # for val in possible_lock_vals:\n # if self._state_space_index_to_features(sample[0])[lock_id] == val:\n # factor_id = sample\n # break ## break from for possible_factor_loop\n # if not factor_id == None:\n # break ## break from sample loop\n \n # factors.append(self._state_space_index_to_features(factor_id[0]))\n # obs_id.append(self.atom_grouped_observations[factor_id[0]][factor_id[1]])\n # self.remove_sample_from_lists(factor_id)\n \n # return np.asarray(factors), obs_id\n \n def sample_latent_factors(self, num, random_state, lock_list = []):\n \"\"\" @author: jboilard\n randomly sample a batch of factors.\n num : number of factors to sample\n random_state : enables repeatability of experiments by making sampling deterministic\n lock_list : passed to function _sample_factor\n returns : factors, observation_id which indexes the Dataset Object\"\"\"\n factors = []\n obs_id = []\n for i in range(num):\n lock = [] if len(lock_list) == 0 else lock_list[i]\n factor_id = self._sample_factor(random_state, lock)\n \n # if a sample has been effectively sampled. Only goes in else if code does not work properly.\n if not factor_id == None:\n factors.append(self._state_space_index_to_features(factor_id[0]))\n obs_id.append(self.atom_grouped_observations[factor_id[0]][factor_id[1]])\n self.remove_sample_from_lists(factor_id)\n\n else:\n print(\"Warning, lock-filtered factor sample not found. Reduce num sampling, increase datasize, or ignore because of outlier data\")\n factors.append([np.NaN]*len(self.factor_sizes))\n obs_id.append(None)\n \n return np.asarray(factors), obs_id\n \n \n def _sample_factor(self, random_state, lock_list = []):\n \"\"\" @author: jboilard\n function called by all other sampling methods. samples a factor corresponding to the possibilities listed in lock_list\"\"\"\n factor_id = None \n #if no lock list, do simple random sampling\n if lock_list == []:\n sample_id = random_state.randint(len(self.sampling_list))\n factor_id = self.sampling_list[sample_id] \n else:\n #if there is a lock list, list all possibilities, and sample a factor which corresponds to that possibility\n no_sample_available = False\n while factor_id == None and no_sample_available == False:\n possible_factors = self.get_possible_indexes(lock_list, random_state)\n self.sampling_list = shuffle(self.sampling_list, random_state=random_state)\n # possible factor list. checks sampling list in order, bu it has been pre-shuffled, making it random.\n for sample in self.sampling_list:\n for possible_factor in possible_factors:\n if sample[0] == possible_factor:\n factor_id = sample\n\n break ## break from for possible_factor_loop\n if not factor_id == None:\n break ## break from sample loop\n \n #if sample not found, continue while loop, else break out of it.\n if factor_id == None:\n no_sample_available = True\n return factor_id\n\n \n def get_possible_indexes(self, factors_lock, random_state):\n \"\"\" from defined unlocked (-1) and locked factors, get all possible values for sampling\"\"\"\n factor_list = [[]]\n for i, lock_val in enumerate(factors_lock):\n ## if unlocked, number of possible factor-samples are multiplied by the number of possible unlocked factor values\n if lock_val == -1 : \n base = factor_list\n factor_list = []\n for b in base:\n bc = b.copy()\n for f in range(self.factor_sizes[i]):\n bc.append(f)\n factor_list.append(bc)\n bc = b.copy()\n \n else: ## if factor is locked, just append the locked factor value\n for i in range(len(factor_list)):\n factor_list[i].append(lock_val)\n #transform to index\n possible_indexes = self._features_to_state_space_index(np.asarray(factor_list)) \n return possible_indexes\n \n \n def sample_possible_locking(self, batchsize, random_state, mode):\n raise NotImplementedError()\n pass \n\n\n def features_to_index(self, features):\n \"\"\"Returns the indices in the input space for given factor configurations.\n \n Args:\n features: Numpy matrix where each row contains a different factor\n configuration for which the indices in the input space should be\n returned.\"\"\"\n state_space_index = self._features_to_state_space_index(features)\n return self.state_space_to_save_space_index[state_space_index]\n\n \n def _features_to_state_space_index(self, features):\n \"\"\"Returns the indices in the atom space for given factor configurations.\n \n Args:\n features: Numpy matrix where each row contains a different factor\n configuration for which the indices in the atom space should be\n returned.\n \"\"\"\n if (np.any(features > np.expand_dims(self.factor_sizes, 0)) or\n np.any(features < 0)):\n raise ValueError(\"Feature indices have to be within [0, factor_size-1]!\")\n return np.array(np.dot(features, self.factor_bases), dtype=np.int64)\n \n def _state_space_index_to_features(self, index):\n \"\"\"Returns the corresponding features corresponding to an id.\n \n Args:\n index: single index value representing a factor atom.\n \"\"\"\n factor = []\n for base in self.factor_bases:\n f = math.floor(index/base)\n factor.append(f)\n index = index - f*base\n \n return factor\n","sub_path":"disentanglement_lib/evaluation/benchmark/sampling/generic_sampling.py","file_name":"generic_sampling.py","file_ext":"py","file_size_in_byte":13123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"227290000","text":"import json, argparse\n# import spacy\n\ndef get_tokenizer(lang):\n #Custom Tokenizers (e.g. SpaCy can be loaded here)\n return None\n\n\ndef tokenize_sentence(sentence_str, spacy_lang=None):\n if not spacy_lang:\n return sentence_str.split()\n\n\ndef file_pair2JSON(src_filename, tgt_filename, output, src_key=\"\", tgt_key=\"\"):\n json_output = open(output, \"w\")\n src_tokenizer = get_tokenizer(src_key)\n tgt_tokenizer = get_tokenizer(tgt_key)\n with open(src_filename) as src_file, open(tgt_filename) as tgt_file:\n for s, t in zip(src_file, tgt_file):\n src = s.strip(\"\\n\")\n tgt = t.strip(\"\\n\")\n if len(src) == 0 or len(tgt) == 0: continue\n source_tokens = tokenize_sentence(src, src_tokenizer)\n target_tokens = tokenize_sentence(tgt, tgt_tokenizer)\n obj = {\"source_tokens\": source_tokens,\n \"target_tokens\": target_tokens,\n \"src_lang\": src_key,\n \"tgt_lang\": tgt_key\n }\n json_output.write(json.dumps(obj)+\"\\n\")\n\n\ndef bilingual_file2JSON(filename, output, src_key=\"\", tgt_key=\"\", swap_parallel=False):\n json_output = open(output, \"w\")\n src_tokenizer = get_tokenizer(src_key)\n tgt_tokenizer = get_tokenizer(tgt_key)\n with open(filename) as f:\n for line in f:\n src, tgt = line.strip(\"\\n\").split(\"\\t\")\n source_tokens = tokenize_sentence(src, src_tokenizer)\n target_tokens = tokenize_sentence(tgt, tgt_tokenizer)\n if swap_parallel == 1: #True: languages should swap\n obj = {\"source_tokens\": target_tokens,\n \"target_tokens\": source_tokens,\n \"src_lang\": tgt_key,\n \"tgt_lang\": src_key\n }\n else:\n obj = {\"source_tokens\": source_tokens,\n \"target_tokens\": target_tokens,\n \"src_lang\": src_key,\n \"tgt_lang\": tgt_key\n }\n json_output.write(json.dumps(obj)+\"\\n\")\n\n\nif __name__ == \"__main__\":\n \"\"\"\n RUN EXAMPLE:\n python pre_processing/text_to_JSON.py --path toy_data/ -s en.txt -t de.txt -o en2de.json -ks \"\" -kt \"\"\n \"\"\"\n # Read arguments from command line\n parser = argparse.ArgumentParser()\n parser.add_argument('-p', '--path', help='Filepath where the input is and the where output file will be saved', default=\"\")\n parser.add_argument('-s', '--source_file', help='JSON File with the model outputs', required=True)\n parser.add_argument('-t', '--target_file', help='If files are separated per language', default=None)\n parser.add_argument('-ks', '--src_key', help='key for the JSON, compatible with allennlp DatasetReader!', required=True)\n parser.add_argument('-kt', '--tgt_key', help='key for the JSON, compatible with allennlp DatasetReader!', required=True)\n parser.add_argument('-sw', '--swap_langs', help='If 1 languages will swap. They stay the same otherwise', type=int, default=0)\n parser.add_argument('-o', '--output', help='JSON file where the output will be saved', required=True)\n args = parser.parse_args()\n\n if not args.target_file:\n bilingual_file2JSON(filename=args.path + \"/\" + args.source_file,\n output=args.path + \"/\" + args.output,\n src_key=args.src_key,\n tgt_key=args.tgt_key,\n swap_parallel=args.swap_langs)\n else:\n file_pair2JSON(src_filename=args.path + \"/\" + args.source_file,\n tgt_filename=args.path + \"/\" + args.target_file,\n output=args.path + \"/\" + args.output,\n src_key=args.src_key,\n tgt_key=args.tgt_key)\n","sub_path":"pre_processing/text_to_JSON.py","file_name":"text_to_JSON.py","file_ext":"py","file_size_in_byte":3880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"630268398","text":"#!/usr/bin/python3\n# -*-coding:utf-8-*-\n# Author: chengnian_20@163.com in 2018\nimport time\n\nfrom qcloudsms_py import SmsSingleSender, SmsVoicePromptSender, SmsStatusPuller, SmsMobileStatusPuller, TtsVoiceSender\nfrom qcloudsms_py.httpclient import HTTPError\n\nappkey = ''\n# 应用ID\nsdkappid = 1400140736\n# 正文模板id 短信\nsms_tp_id = 196241\n# 正文模板id 语音\nvoice_tp_id =197061 # ;签名\nsms_sign = '中科城安'\n\nphone_numbers = [\"13520691471\", ]\n\nssender = SmsSingleSender(sdkappid, appkey)\n# 安全提醒:{1}{2},编号{3}在{4}分{5},请现场确认消防安全!\nsms_params = ['嘉禾国信大厦',\n 'CD座5层展示大厅',\n '52FF6',\n '14:19',\n '故障电弧火警'\n ]\n\n\ndef send_sms():\n '''\n 指定模板ID单发短信\n :return:\n '''\n try:\n result = ssender.send_with_param(86, phone_number=phone_numbers[0],\n template_id=int(sms_tp_id),\n params=sms_params,\n sign=sms_sign,\n extend='',\n ext=''\n )\n except HTTPError as e:\n print(e)\n except Exception as e:\n print(e)\n print(result)\n\n\ndef datetime_timestamp(dt):\n # dt为字符串\n # 中间过程,一般都需要将字符串转化为时间数组\n time.strptime(dt, '%Y-%m-%d %H:%M:%S')\n ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=-1)\n s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))\n return int(s)\n\n\ndef sms_status():\n '''\n 拉取单个手机短信状态\n :return:\n '''\n begin_time = datetime_timestamp('2018-09-18 20:00:00') # 开始时间(unix timestamp)\n # begin_time = 1511125600 # 开始时间(unix timestamp)\n end_time = datetime_timestamp('2018-09-18 21:48:00') # 结束时间(unix timestamp)\n max_num = 10 # 单次拉取最大量\n mspuller = SmsMobileStatusPuller(sdkappid, appkey)\n try:\n # 拉取短信回执\n callback_result = mspuller.pull_callback(\"86\", phone_numbers[0],\n begin_time, end_time, max_num)\n # # 拉取回复\n # reply_result = mspuller.pull_reply(\"86\", phone_numbers[0],\n # begin_time, end_time, max_num)\n except HTTPError as e:\n print(e)\n except Exception as e:\n print(e)\n #\n print(callback_result)\n # print(reply_result)\n\n\ndef send_voice():\n '''\n 发送语音通知\n :return:\n '''\n # 中科城安提醒您,{1}{2}在{3}分发生{4},编号{5},请现场确认消防安全\n voice_params = ['嘉禾国信大厦',\n 'CD座5层展示大厅',\n '14:19',\n '故障电弧火警'\n '6587'\n ]\n tvsender = TtsVoiceSender(int(sdkappid), appkey)\n try:\n result = tvsender.send(int(voice_tp_id), voice_params , phone_number=phone_numbers[0],\n nationcode='86', playtimes=2, ext='')\n except HTTPError as e:\n print(e)\n except Exception as e:\n print(e)\n print(result)\n\n\ndef main():\n # send_sms()\n # sms_status()\n send_voice()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"extera_apps/tencent_sms.py","file_name":"tencent_sms.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"113196303","text":"from twisted.python import log\nfrom twisted.web.client import getPage\nfrom twisted.application import service\n\nfrom twisted.application.internet import TimerService\n\nclass TracMonitor(service.MultiService):\n def __init__(self, restartCallback, checkInterval, tracURL, timeout):\n service.MultiService.__init__(self)\n self._restartCallback = restartCallback\n self._tracURL = tracURL\n self._timeout = timeout\n TimerService(checkInterval, self.check).setServiceParent(self)\n\n def restart(self, f):\n log.err(f, 'accessing trac.')\n log.msg('restarting trac.')\n self._restartCallback()\n\n def check(self):\n return (getPage(self._tracURL, timeout=self._timeout)\n .addErrback(self.restart))\n","sub_path":"images/trac/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"509914384","text":"#!/usr/bin/env python3.6\n# -*- coding: utf-8 -*-\n\n\nimport os\nimport json\nfrom orbis.libs import scorer_lib\nfrom orbis.config import paths\n\ntest_cases = {\n \"0\": {\n \"gold_path\": os.path.abspath(os.path.join(paths.tests_dir, \"libs\", \"scorer_lib\", \"corpus\", \"gold_0.json\")),\n \"calculated_path\": os.path.abspath(os.path.join(paths.tests_dir, \"libs\", \"scorer_lib\", \"corpus\", \"calculated_0.json\")),\n \"conditions\": [\"overlap\", \"same_url\", \"same_type\"],\n \"result\": {\n 'tp': [1, 0, 0, 1, 0, 0],\n 'fp': [0, 0, 0, 0, 0, 1],\n 'fn': [0, 1, 1, 0, 1, 0],\n 'tp_ids': ['0,25', '401,413'],\n 'fp_ids': ['54,88'],\n 'fn_ids': ['54,88', '309,331', '420,442'],\n 'tp_sum': 2,\n 'fp_sum': 1,\n 'fn_sum': 3\n }\n },\n}\n\"\"\"\n \"1\": { Document 46 false positive\n \"\"\n }\n\"\"\"\n\n\ndef test_get_confusion_matrix():\n\n for key, case in test_cases.items():\n with open(case[\"gold_path\"]) as open_file:\n gold = json.load(open_file)\n with open(case[\"calculated_path\"]) as open_file:\n calculated = json.load(open_file)\n\n result = scorer_lib.get_confusion_matrix(calculated, gold, case[\"conditions\"])\n assert result == case[\"result\"]\n\n\nif __name__ == '__main__':\n test_get_confusion_matrix()\n\n\n\"\"\"\n gold_path = os.path.abspath(os.path.join(tests_dir, \"libs\", \"scorer_lib\", \"corpus\", \"gold_0.json\"))\n computed_path = os.path.abspath(os.path.join(tests_dir, \"libs\", \"scorer_lib\", \"corpus\", \"computed_0.json\"))\n conditions = [\"overlap\", \"same_url\", \"same_type\"]\n\n with open(gold_path) as open_file:\n gold = json.load(open_file)\n\n with open(computed_path) as open_file:\n computed = json.load(open_file)\n result_0 = get_confusion_matrix(computed, gold, conditions)\n\n with open(gold_path) as open_file:\n gold = json.load(open_file)\n\n with open(computed_path) as open_file:\n computed = json.load(open_file)\n result_1 = get_confusion_matrix(computed, gold, conditions)\n\n print(result_0)\n print(result_1)\n print(\"{}\\t{}\".format(result_0[\"tp\"], result_0[\"fp\"]))\n print(\"{}\\t{}\\t{}\".format(result_1[\"tp\"], result_1[\"fp\"], result_1[\"fn\"]))\n\n\n\"\"\"\n\"\"\"\n0,25 0,25 1\n54,88 False 0\n309,331 False 0\n401,418 401,413 1\n420,442 False 0\nFalse 54,88 0\n\"\"\"\n","sub_path":"tests/libs/scorer_lib/test_scorer_lib.py","file_name":"test_scorer_lib.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"75996894","text":"import cx_Oracle, sys, datetime, time, subprocess, os, atexit, string, multiprocessing, copy\nfrom signal import SIGTERM\nimport threading\n\n\n# 守护进程包裹类\nclass Daemon(object):\n def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):\n # 需要获取调试信息,改为stdin='/dev/stdin', stdout='/dev/stdout', stderr='/dev/stderr',以root身份运行。\n self.stdin = stdin\n self.stdout = stdout\n self.stderr = stderr\n self.pidfile = pidfile\n\n def _daemonize(self):\n try:\n pid = os.fork() # 第一次fork,生成子进程,脱离父进程\n if pid > 0:\n sys.exit(0) # 退出主进程\n except OSError as e:\n sys.stderr.write('fork #1 failed: %d (%s)\\n' % (e.errno, e.strerror))\n sys.exit(1)\n\n os.chdir(\"/\") # 修改工作目录\n os.setsid() # 设置新的会话连接\n os.umask(0) # 重新设置文件创建权限\n\n try:\n pid = os.fork() # 第二次fork,禁止进程打开终端\n if pid > 0:\n sys.exit(0)\n except OSError as e:\n sys.stderr.write('fork #2 failed: %d (%s)\\n' % (e.errno, e.strerror))\n sys.exit(1)\n\n # 重定向文件描述符\n sys.stdout.flush()\n sys.stderr.flush()\n\n # dup2函数原子化地关闭和复制文件描述符,重定向到/dev/nul,即丢弃所有输入输出\n si = open(self.stdin, 'r')\n so = open(self.stdout, 'a+')\n se = open(self.stderr, 'a+')\n os.dup2(si.fileno(), sys.stdin.fileno())\n os.dup2(so.fileno(), sys.stdout.fileno())\n os.dup2(se.fileno(), sys.stderr.fileno())\n\n # 注册退出函数,根据文件pid判断是否存在���程\n atexit.register(self.delpid)\n pid = str(os.getpid())\n open(self.pidfile, 'w+').write('%s\\n' % pid)\n\n def delpid(self):\n os.remove(self.pidfile)\n\n def start(self):\n # 检查pid文件是否存在以探测是否存在进程\n try:\n pf = open(self.pidfile, 'r')\n pid = int(pf.read().strip())\n pf.close()\n except IOError:\n pid = None\n\n if pid:\n message = 'pidfile %s already exist. Daemon already running!\\n'\n sys.stderr.write(message % self.pidfile)\n sys.exit(1)\n\n # 启动监控\n self._daemonize()\n self._run()\n\n def stop(self):\n # 从pid文件中获取pid\n try:\n pf = open(self.pidfile, 'r')\n pid = int(pf.read().strip())\n pf.close()\n except IOError:\n pid = None\n\n if not pid: # 重启不报错\n message = 'pidfile %s does not exist. Daemon not running!\\n'\n sys.stderr.write(message % self.pidfile)\n return\n\n # 杀进程\n try:\n while 1:\n os.kill(pid, SIGTERM)\n time.sleep(0.1)\n except OSError as err:\n err = str(err)\n if err.find('No such process') > 0:\n if os.path.exists(self.pidfile):\n os.remove(self.pidfile)\n else:\n print(str(err))\n sys.exit(1)\n\n def restart(self):\n self.stop()\n self.start()\n\n def _run(self):\n \"\"\" run your fun\"\"\"\n while True:\n main_func()\n time.sleep(1)\n\n# oracle操作类\nclass oracle_run_sql_class(object):\n db223_connect_info = \"etc/etc@10.138.22.223:1521/edw\"\n db226_connect_info = \"etc/etc_Control@10.138.22.226:1521/edw\"\n\n def __init__(self, which_db):\n self.which_db = which_db\n if which_db == 223:\n self.which_db = oracle_run_sql_class.db223_connect_info\n elif which_db == 226:\n self.which_db = oracle_run_sql_class.db226_connect_info\n\n @staticmethod\n def get_user_passwd(which_db):\n if which_db == 223:\n self.which_db = oracle_run_sql_class.db223_connect_info\n elif which_db == 226:\n self.which_db = oracle_run_sql_class.db226_connect_info\n return self.which_db\n\n # 查询标识表方法\n def search_sql_func(self, search_sql):\n try:\n conn = cx_Oracle.connect(self.which_db)\n cur = conn.cursor()\n cur.execute(search_sql)\n result = cur.fetchall()\n cur.close()\n conn.close()\n return result\n except BaseException as e:\n print(e)\n print(\"Oracle connect is broken!!!\")\n\n #通用版本\n def insert_into_sql_common_func(self, insert_sql):\n try:\n conn = cx_Oracle.connect(self.which_db)\n cur = conn.cursor()\n cur.execute(insert_sql)\n conn.commit()\n conn.close()\n except BaseException as e:\n print(e)\n print(\"Oracle connect is broken!!!\")\n\n#抽取配置文件转换类\nclass Get_Config_Json_Class(object):\n def __init__(self, which_db):\n self.which_db = which_db\n if which_db == 223:\n self.which_db = oracle_run_sql_class.db223_connect_info\n elif which_db == 226:\n self.which_db = oracle_run_sql_class.db226_connect_info\n\n ##作业调度时刻表 抽出 json格式 t_Jobs_Frequency\n def get_task_time_config_func(self):\n task_time_config_dict = {}\n task_time_config_dict['task_group_id'] = {}\n\n #把结果暂时保存 减少查询sql\n search_sql = \"select group_id, duration, run_time from t_Jobs_frequency\"\n search_sql_obj = oracle_run_sql_class(self.which_db)\n result = search_sql_obj.search_sql_func(search_sql)\n run_time_config_list = copy.deepcopy(result)\n # print(run_time_config_list)\n\n # 所有作业组\n for line in run_time_config_list:\n task_time_config_dict['task_group_id'][str(line[0])] = {}\n\n # 所有的调度类型\n for task_group_id in task_time_config_dict['task_group_id'].keys():\n task_time_config_dict['task_group_id'][task_group_id]['call_type'] = {}\n for line in run_time_config_list:\n if str(line[0]) == task_group_id:\n task_time_config_dict['task_group_id'][task_group_id]['call_type'][str(line[1])] = {}\n\n # 所有的调度类型后的时间\n for task_group_id in task_time_config_dict['task_group_id'].keys():\n for call_type in task_time_config_dict['task_group_id'][task_group_id]['call_type'].keys():\n task_time_config_dict['task_group_id'][task_group_id]['call_type'][call_type]['run_time'] = []\n for line in run_time_config_list:\n if str(line[0]) == task_group_id and str(line[1]) == call_type:\n task_time_config_dict['task_group_id'][task_group_id]['call_type'][call_type]['run_time'].append(str(line[2]))\n #返回最后的json配置\n # print('last dict:', task_time_config_dict)\n return task_time_config_dict\n\n # 作业调度顺序表 抽出 json格式 t_Jobs_Order 详细的作业信息\n def get_task_group_info_dict(self):\n task_group_info_dict = {}\n task_group_info_dict['task_group_id'] = {}\n\n #把结果暂时保存 减少查询sql\n search_sql = \"select group_id, JOB_ID, PREJOB_ID, OTHER_SELECT_SQL, PRO_NAME, PARA_IN, PARA_OUT from t_Jobs_Order\"\n # search_sql = \"select * from t_Jobs_Order\"\n search_sql_obj = oracle_run_sql_class(self.which_db)\n result = search_sql_obj.search_sql_func(search_sql)\n task_group_info_list = copy.deepcopy(result)\n\n # 所有作业组\n for line in task_group_info_list:\n task_group_info_dict['task_group_id'][str(line[0])] = {}\n\n # 所有作业 及作业组的外部依赖\n for task_group_id in task_group_info_dict['task_group_id'].keys():\n task_group_info_dict['task_group_id'][task_group_id]['job_id'] = {}\n task_group_info_dict['task_group_id'][task_group_id]['other_prejob'] = ''\n for line in task_group_info_list:\n if str(line[0]) == task_group_id:\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][str(line[1])] = {}\n task_group_info_dict['task_group_id'][task_group_id]['other_prejob'] = str(line[3])\n\n # 所有作业的 pre_job_id, PRO_NAME, PARA_IN, PARA_OUT\n for task_group_id in task_group_info_dict['task_group_id'].keys():\n for job_id in task_group_info_dict['task_group_id'][task_group_id]['job_id'].keys():\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][job_id]['prejob_id'] = []\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][job_id]['storeprodure_name'] = ''\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][job_id]['para_info'] = ''\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][job_id]['return_info'] = ''\n\n for line in task_group_info_list:\n if str(line[0]) == task_group_id and job_id == str(line[1]):\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][job_id]['prejob_id'].append(str(line[2]))\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][job_id]['storeprodure_name'] = str(line[4])\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][job_id]['para_info'] = str(line[5])\n task_group_info_dict['task_group_id'][task_group_id]['job_id'][job_id]['return_info'] = str(line[6])\n\n # print(task_group_info_dict)\n return task_group_info_dict\n\n###查询时间多线程并发\ndef check_TaskGroup_RunTime_func(task_time_config_dict):\n #线程池\n thread_list = []\n for task_group_id in task_time_config_dict['task_group_id'].keys():\n t = threading.Thread(target=_check_TaskGroup_RunTime_func, args=(task_group_id, task_time_config_dict['task_group_id'][task_group_id],))\n t.start()\n thread_list.append(t)\n for t in thread_list:\n t.join()\n\n#并发函数\ndef _check_TaskGroup_RunTime_func(task_group_id, call_type_info):\n status_file_name = 'status.txt'\n\n # 没有文件就创建文件\n if not os.path.isfile(status_file_name):\n with open(status_file_name, 'a') as f:\n pass\n\n #时间定义参数\n now_date = ((datetime.datetime.now()) + datetime.timedelta(days=-1)).strftime(\"%Y%m%d\")\n now_date_time = (datetime.datetime.now()).strftime(\"%H:%M\")\n now_date_time = '07:00'\n\n #查看当前时间 是否 对的上\n for call_type_id in call_type_info['call_type']:\n for run_time in call_type_info['call_type'][call_type_id]['run_time']:\n\n #如果时间对上了,看看是不是在调用了\n if now_date_time == run_time:\n # print(task_group_id, call_type_id, run_time)\n #done?\n now_done_statu = check_TaskGroup_RunStatusDone_func(task_group_id, run_time, now_date)\n\n #running?\n if not now_done_statu:\n now_run_statu = check_TaskGroup_RunStatusRunning_func(task_group_id, run_time, now_date)\n\n ## will run..\n if not now_done_statu and not now_run_statu:\n will_call_task_group_dict = {}\n will_call_task_group_dict['task_group_id'] = str(task_group_id)\n will_call_task_group_dict['call_type_id'] = str(call_type_id)\n will_call_task_group_dict['now_date'] = str(now_date)\n will_call_task_group_dict['run_time'] = str(run_time)\n\n\n # wirte_running_flag\n time.sleep(1)\n with open(status_file_name, 'r+') as f:\n wirte_running_flag = True\n for line in f:\n line = line.strip()\n line_list = line.split(' ')\n if line_list[0] == str(task_group_id) and line_list[1] == now_date and line_list[\n 2] == run_time and line_list[3] == 'R':\n wirte_running_flag = False\n if wirte_running_flag:\n print(task_group_id, now_date, run_time, 'R', '写入标识')\n print(task_group_id, now_date, run_time, 'R', file=f)\n\n ##调用另一个跑批脚本\n # print('call SP running .....', will_call_task_group_dict)\n Run_file = \"%s/Auto_Call_SP_Run.py\" % (os.path.dirname(__file__))\n cmd = \"python %s %s %s %s %s\" % (Run_file, task_group_id, call_type_id, now_date, run_time)\n subprocess.run(cmd, check=True)\n\n\n##检测调度运行完毕\ndef check_TaskGroup_RunStatusDone_func(task_group_id, run_time, now_date):\n status_file_name = 'status.txt'\n now_done_statu = False\n ##done?\n with open(status_file_name, 'r') as f:\n for line in f:\n line = line.strip()\n line_list = line.split(' ')\n if line_list[0] == str(task_group_id) and line_list[1] == now_date and line_list[2] == run_time and \\\n line_list[3] == 'D':\n print('今天任务已经完成!', task_group_id,now_date, run_time, 'D')\n now_done_statu = True\n return now_done_statu\n return now_done_statu\n\n##检测调度运行zhengzai运行\ndef check_TaskGroup_RunStatusRunning_func(task_group_id, run_time, now_date):\n status_file_name = 'status.txt'\n\n now_run_statu = False\n ##done?\n with open(status_file_name, 'r') as f:\n for line in f:\n line = line.strip()\n line_list = line.split(' ')\n if line_list[0] == str(task_group_id) and line_list[1] == now_date and line_list[\n 2] == run_time and \\\n line_list[3] == 'R':\n print('今天任务正在运行...', task_group_id, now_date, run_time, 'R')\n now_run_statu = True\n return now_run_statu\n\n return now_run_statu\n\n\n#主程序\ndef main_func():\n #取配置文件\n db226_config = Get_Config_Json_Class(226)\n task_time_config_dict = db226_config.get_task_time_config_func()\n\n check_TaskGroup_RunTime_func(task_time_config_dict)\n\nif __name__ == '__main__':\n main_func()\n\n# if __name__ == '__main__':\n# status_file_name = 'status.txt'\n# daemon = Daemon('/var/run/call_SP1.pid', stdout='/var/log/call_SP_stdout1.log', stderr=\"/var/log/call_SP_stderr1.log\")\n# if len(sys.argv) == 2:\n# if 'start' == sys.argv[1]:\n# daemon.start()\n# elif 'stop' == sys.argv[1]:\n# daemon.stop()\n# elif 'restart' == sys.argv[1]:\n# daemon.restart()\n# else:\n# print('unknown command')\n# sys.exit(2)\n# sys.exit(0)\n# else:\n# print('usage: %s start|stop|restart' % sys.argv[0])\n# sys.exit(2)","sub_path":"online/Call_StoredProdures/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":15267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"17730866","text":"from unidecode import unidecode\n\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom tkinter import *\nimport webbrowser\nimport csv\n\ndef open_graven_channel():\n webbrowser.open_new(\"https://www.tripadvisor.fr/\")\n \n\ndef parcours(url,compteur=[0],liste=[]):\n reponse=requests.get(url)\n if reponse.ok:\n soup=BeautifulSoup(reponse.text)\n reviews=soup.find_all('div',{'class':'Dq9MAugU T870kzTX LnVzGwUB'})\n #for rv in reviews:\n #b=rv.find_all('div',{'class':'oETBfkHU'})\n \n\n for rv in reviews:\n profil=rv.find('div',{'class':\"_310S4sqz\"}).find('div',{'class':\"_2uYWQXeO\"}).find('div',{'class':\"_2fxQ4TOx\"})\n date=profil.find().text\n profil=profil.find('a',{'class':\"ui_header_link _1r_My98y\"}).text\n commentaire=rv.find('q',{'class':'IRsGHoPm'}).find('span').text\n lieuderesidence=rv.find('div',{'class':'_1EpRX7o3'}).text\n NombreDavis=rv.find('div',{'class':'_1EpRX7o3'}).find('span',{'class':'_1fk70GUn'}).text\n #print(NombreDavis)\n NombreVoteutile=rv.find('div',{'class':'_1EpRX7o3'}).find_next('span',{'class':'_3fPsSAYi'}).find_next().find('span',{'class':'_1fk70GUn'}).text\n #print(NombreVoteutile)\n linkprofil=profil+str([lieuderesidence])+str([NombreDavis])+str([NombreVoteutile])+str([date])+str([commentaire])\n compteur[0]=compteur[0]+1\n liste.append('' + linkprofil)\n \n liensuivant=soup.find('div',{'class':'ui_pagination is-centered'})\n liensuivant=liensuivant.find('a',{'class':'ui_button nav next primary'})\n try:\n liensuivant=liensuivant['href']\n except TypeError or ConnectionError or gaierror:\n print(\"FinParcours\")\n print(compteur)\n return liste\n linkfollowing=str('https://www.tripadvisor.fr')+str(liensuivant)\n print(linkfollowing)\n return parcours(linkfollowing)\n \n\n\n\n\ndef concatenation(liste1): \n Liste=[]\n l=[]\n for review in liste1:\n l=review.split('[')\n Liste.append(l[:])\n print(Liste)\n return Liste\n\ndef generate_lien():\n lien=lien_entry.get()\n a=parcours(lien,compteur=[0],liste=[])\n test2=concatenation(a)\n with open('innovators.csv', 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow([\"Nom\",\"Lieu de residence\",\"Nombre Davis\",\"Nombre Vote de Utile\",\"Date\", \"commentaire\"])\n for k in range(len(test2)) : \n writer.writerow([(test2[k][0].capitalize()),\n (test2[k][1].split(\"'\"))[1].split(\",\")[0],\n (test2[k][2].split(\"'\")[1]),\n (test2[k][1].split('contributions')[1]).split(\" \")[0],\n (test2[k][4].split('('))[1].split(')')[0],\n (test2[k][5]).split(']')[0]])\n#(test2[k][1].split(\"'\"))[1].split(\",\")[1].split('contributions')[1].split(\" \")[0]\n#(test2[k][4].split('('))[1].split(')')[0],(test2[k][2]).split(\"'\")[1]\n#.split('contributions')[0]\nWindow =Tk()\nWindow.iconbitmap('logo.ico')\nWindow['bg'] = '#41B77F'\nWindow.title(\"Trip Advisor Data Extractor & Analysis\")\nWindow.geometry(\"500x300\")\nWindow.maxsize(800, 500)\nframe=Frame(Window,bd=1,relief=SUNKEN)\nlabel_title=Label(frame,text=\"WELCOME TO TRIP DATA\",font=(\"Courrier\",20))\nlabel_title.pack()\n\nlabel_subtitle=Label(frame,text=\"This tool Generates You a Data File in csv Format\",font=(\"Courrier\",20),bg=\"#41B77F\",fg=\"white\")\nlabel_subtitle.pack()\nframe.pack(expand=YES)\n\nbutton=Button(frame,text=\"Acceder au site\",font=(\"Courrier\",15),fg='#41B77F',bg=\"#41B77F\",command=open_graven_channel)\nbutton.pack()\nlabel_subtitle1=Label(frame,text=\"Saisir le lien du site\",font=(\"Courrier\",10),bg=\"#41B77F\",fg=\"white\")\nlabel_subtitle1.pack()\nframe.pack(expand=YES)\nlien_entry=Entry(frame,font=(\"Courrier\",15),fg='#4878E6',bg=\"white\")\nlien_entry.pack()\nbutton1=Button(frame,text=\"Generate\",font=(\"Courrier\",20),fg='#41B77F',bg=\"#41B77F\",command=generate_lien)\nbutton1.pack()\nWindow.mainloop()\n","sub_path":"TripData.py/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"152259928","text":"import requests\nimport string\nfrom lxml import html\nfrom googlesearch import search\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nfrom datetime import datetime\nimport logging\n\n\nstop_wrods = [\n 'alors', 'au', 'aucuns', 'aussi', 'autre', 'avant', 'avec', 'avoir', 'bon',\n 'car', 'ce', 'cela', 'ces', 'ceux', 'chaque', 'ci', 'comme', 'comment',\n 'dans', 'des', 'du', 'dedans', 'dehors', 'depuis', 'devrait', 'doit',\n 'donc', 'dos', 'début', 'elle', 'elles', 'en', 'encore', 'essai', 'est',\n 'et', 'eu', 'fait', 'faites', 'fois', 'font', 'hors', 'ici', 'il', 'ils',\n 'je', 'juste', 'la', 'le', 'les', 'leur', 'là', 'ma', 'maintenant', 'mais',\n 'mes', 'mien', 'moins', 'mon', 'mot', 'même', 'ni', 'nommés', 'notre',\n 'nous', 'ou', 'où', 'par', 'parce', 'pas', 'peut', 'peu', 'plupart',\n 'pour', 'pourquoi', 'quand', 'que', 'quel', 'quelle', 'quelles', 'quels',\n 'qui', 'sa', 'sans', 'ses', 'seulement', 'si', 'sien', 'son', 'sont',\n 'sous', 'soyez', 'sur', 'ta', 'tandis', 'tellement', 'tels', 'tes', 'ton',\n 'tous', 'tout', 'trop', 'très', 'tu', 'voient', 'vont', 'votre', 'vous',\n 'vu', 'ça', 'étaient', 'état', 'étions', 'été', 'être', 'meteo', 'météo'\n 'à', '?', '!', '.', '', 'à'\n]\n\nHEADERS = {\n 'Accept':\n \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n 'Accept-Encoding': \"gzip, deflate, br\",\n 'Connection': \"keep-alive\",\n 'TE': \"Trailers\",\n 'Upgrade-Insecure-Requests': \"1\",\n 'User-Agent': \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:74.0) Gecko/20100101 Firefox/74.0\",\n 'Referer': \"www.google.com\"\n}\n\n\n# fonction qui va réaliser nos requetes (urllib/gsearch)\ndef bot_request(query):\n fail = 'Désolé je n\\'ai pas de réponses à votre question .'\n resultat = ''\n try:\n \"\"\" cas ou l'utilisateur veut connaitre la météo,\n on va filtrer sa question pour extraire le nom de la ville\n pour l'utiliser dans une requete avec l'api openweathermap\"\"\"\n if 'meteo' in query or 'temp' in query or 'météo' in query:\n req = list(\n filter(\n lambda x: x not in stop_wrods and bool(\n re.search(r'[A-Z]', x)), query.split(' ')))\n\n if not req:\n ville = 'Lille'\n else:\n ville = req[0]\n api_meteo = url_weather = \"http://api.openweathermap.org/data/2.5/weather?q=\" + ville + \"&APPID=beb97c1ce62559bba4e81e28de8be095&lang=fr&units=metric\"\n r_weather = requests.get(url_weather)\n data = r_weather.json()\n try:\n temp = data.get('weather', None)[0].get('description', None)\n temperature = data.get('main', None).get('temp', None)\n ressenti = data.get('main', None).get('feels_like', None)\n except:\n print('probleme lors de la récupération des donénes méteo')\n\n resultat = f'Actuellement sur la ville de {ville}, l\\'état du ciel: {temp} et la temperature est de: {temperature}°, ressenti: {ressenti}°'\n\n elif \"heure\" in query or 'date' in query:\n \"\"\" cas heure est demandé dans la requete\"\"\"\n resultat = f'{str(datetime.now())}'\n else:\n \"\"\" toute autre question posé par l'utilisateur,\n on va faire une requete avec google search pour avoir une liste d'urls et on va les requeter ensuite\n puis extraire des paragraphes et en afficher le résultat\"\"\"\n search_result_list = list(\n search(query, tld=\"co.in\", num=10, stop=3, pause=1))\n i = 0\n for i in range(3):\n page = requests.get(search_result_list[i], headers=HEADERS)\n if page.status_code == 200:\n tree = html.fromstring(page.content)\n soup = BeautifulSoup(page.content, features=\"lxml\")\n paragraphe = ''\n all_infos = soup.findAll('p')\n for element in all_infos[:2]:\n paragraphe += '\\n' + ''.join(\n element.findAll(text=True))\n paragraphe = paragraphe.replace('\\n', '')\n if paragraphe:\n paragraphe = paragraphe[:round((\n len(paragraphe) * 90 / 100))] if len(\n paragraphe\n ) > 1000 else paragraphe[:round(len(paragraphe))]\n break\n resultat = paragraphe if len(paragraphe) > 3 else fail\n\n return resultat\n except Exception as e:\n logging.warning(e)\n if len(resultat) == 0: resultat = fail\n return resultat\n","sub_path":"function_search.py","file_name":"function_search.py","file_ext":"py","file_size_in_byte":4759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"423583095","text":"import json\nimport matplotlib.pyplot as plt\n\nx = []\ny = []\n\nwith open('HousingData.json') as d:\n data = json.load(d)\n total_data = len(data['dataset']['data'])\n # print(total_data)\n # for eachData in range(total_data):\n listOfData = data['dataset']['data']\n for eachData in listOfData:\n x.append(eachData[0])\n y.append(eachData[1])\n print(\"Housing Date: {} || Price: {}\".format(eachData[0],eachData[1]))\n\nplt.plot(x,y)\nplt.show()\n","sub_path":"NYCHousingData_Parse.py","file_name":"NYCHousingData_Parse.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"264127054","text":"cont = 0\nNumerosPar = 0\nNumerosImpar = 0\nwhile cont < 10:\n Numeros = int(input(\"Quais são seus numeros? \"))\n cont = cont + 1\n if Numeros % 2 == 0:\n NumerosPar = NumerosPar + 1\n else:\n NumerosImpar = NumerosImpar + 1\nprint(\"Foram digitados uma quantidade de\",NumerosPar,\"numeros pares e\",NumerosImpar,\"numeros impares\")","sub_path":"Lista 3/lista03ex11.py","file_name":"lista03ex11.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"54277845","text":"from flask import Flask, jsonify\nfrom flask_cors import CORS\nfrom sqlalchemy import create_engine\nfrom uri import uri\n\nDEBUG = True\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\nCORS(app, resources={r'/*': {'origins': '*'}})\n\n\nengine = create_engine(uri)\n\n\n@app.route('/sentences', methods=['GET'])\ndef sentences():\n return jsonify('pong!')\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"465510944","text":"from base.Interpreter import *\n\n\ndef main():\n # while True:\n # try:\n # text = input(\"calc>>> \")\n #\n # except EOFError:\n # break\n #\n # if not text:\n # continue\n #\n # lexer = Lexer(text)\n # parser = Parser(lexer)\n # interpreter = Interpreter(parser)\n # result = interpreter.interpret()\n #\n # print(interpreter.GLOBAL_SCOPE)\n #\n # if result is not None:\n # print(result)\n file = open(\"main.lan\")\n lines = \"\".join(file.readlines())\n\n lexer = Lexer(lines)\n parser = Parser(lexer)\n interpreter = Interpreter(parser)\n result = interpreter.interpret()\n print(interpreter.GLOBAL_SCOPE)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"441446831","text":"# make new script to make contrasts that will be saved in\n# soma_fit/new_fits/...\n# script not using nilearn functions but glm defined in utils\n# in this way I can also save other stats and model predictions per voxel\n\n\nimport os, json\nimport sys, glob\nimport re \n\nimport numpy as np\nimport pandas as pd\n\nimport nibabel as nb\nfrom nilearn import surface\n\nfrom nistats.design_matrix import make_first_level_design_matrix\nfrom nistats.contrasts import compute_contrast\n\nfrom utils import * #import script to use relevante functions\n\nfrom joblib import Parallel, delayed\nfrom nistats.reporting import plot_design_matrix\n\n\n# define participant number and open json parameter file\nif len(sys.argv)<2:\t\n raise NameError('Please add subject number (ex:01) '\t\n 'as 1st argument in the command line!')\t\n\nelse:\n sj = str(sys.argv[1]).zfill(2) #fill subject number with 0 in case user forgets\t\n\n with open('analysis_params.json','r') as json_file:\t\n analysis_params = json.load(json_file)\t\n \n\n# define paths and variables\nwith_smooth = analysis_params['with_smooth']\nrsq_threshold = 0.5 \nz_threshold = analysis_params['z_threshold']\n\n\n# changes depending on data used\nif with_smooth=='True':\n # soma out path\n out_dir = os.path.join(analysis_params['soma_outdir'],'new_fits','sub-{sj}'.format(sj=sj),'smooth%d'%analysis_params['smooth_fwhm'])\n # last part of filename to use\n file_extension = 'sg_psc_smooth%d.func.gii'%analysis_params['smooth_fwhm']\nelse:\n # soma out path\n out_dir = os.path.join(analysis_params['soma_outdir'],'new_fits','sub-{sj}'.format(sj=sj))\n # last part of filename to use\n file_extension = 'sg_psc.func.gii'\n\n\n# path to save fits, for testing\nif not os.path.exists(out_dir): # check if path exists\n os.makedirs(out_dir)\n\nprint('files will be saved in %s'%out_dir)\n\n\nif sj == 'median':\n\n all_subs = ['01','02','03','04','05','08','09','11','12','13']\n\nelse:\n all_subs = [sj]\n\ndata = make_median_soma_sub(all_subs,file_extension,out_dir,median_gii=median_gii)\n \nevents_avg = make_median_soma_events(all_subs)\n\n# make DM\n\nTR = analysis_params[\"TR\"]\n\n# specifying the timing of fMRI frames\nframe_times = TR * (np.arange(data.shape[-1]))\n\n# Create the design matrix, hrf model containing Glover model \ndesign_matrix = make_first_level_design_matrix(frame_times,\n events=events_avg,\n hrf_model='glover'\n )\n\n# plot design matrix and save just to check if everything fine\nplot = plot_design_matrix(design_matrix)\nfig = plot.get_figure()\nfig.savefig(os.path.join(out_dir,'design_matrix.svg'), dpi=100,bbox_inches = 'tight')\n\nprint('fitting GLM to %d vertices'%data.shape[0])\nsoma_params = Parallel(n_jobs=16)(delayed(fit_glm)(vert, design_matrix.values) for _,vert in enumerate(data))\nsoma_params = np.vstack(soma_params)\n\n# save estimates in dir \nestimates_filename = os.path.join(out_dir,'sub-{sj}_ses-01_task-soma_run-median_space-fsaverage_hemi-both_{ext}'.format(sj=sj,ext=file_extension))\nestimates_filename = estimates_filename.replace('.func.gii','_estimates.npz')\n\nnp.savez(estimates_filename,\n model = soma_params[..., 0],\n betas = soma_params[..., 1],\n r2 = soma_params[..., 2],\n mse = soma_params[...,3])\n\n# load betas\nsoma_estimates = np.load(estimates_filename,allow_pickle=True)\nbetas = soma_estimates['betas']\n\n# mask the data\n# only use data where rsq of fit higher than X% (random percentage, see how it looks then ask T what to use)\nprint('masking data with %.2f rsq threshold'%rsq_threshold)\ndata_masked = data.copy()\nalpha_mask = np.array([True if val<= rsq_threshold or np.isnan(val) else False for _,val in enumerate(soma_estimates['r2'])])\ndata_masked[alpha_mask]=np.nan\n\n\n# now make simple contrasts\n\nprint('Computing simple contrasts')\n\nzmaps_all = {} # save all computed z_maps, don't need to load again\n\nreg_keys = list(analysis_params['all_contrasts'].keys()); reg_keys.sort() # list of key names (of different body regions)\nloo_keys = leave_one_out_lists(reg_keys) # loo for keys \n\nfor index,region in enumerate(reg_keys): # one broader region vs all the others\n \n print('contrast for %s ' %region)\n # list of other contrasts\n other_contr = np.append(analysis_params['all_contrasts'][loo_keys[index][0]],analysis_params['all_contrasts'][loo_keys[index][1]])\n \n contrast = make_contrast(design_matrix.columns,[analysis_params['all_contrasts'][str(region)],other_contr],[1,-len(analysis_params['all_contrasts'][str(region)])/len(other_contr)],num_cond=2)\n \n # compute contrast-related statistics\n soma_stats = Parallel(n_jobs=16)(delayed(compute_stats)(vert, design_matrix.values,contrast,betas[w]) for w,vert in enumerate(data_masked))\n soma_stats = np.vstack(soma_stats) # t_val,p_val,zscore\n # save estimates in dir \n stats_filename = os.path.join(out_dir,'z_%s_contrast_stats.npz' %(region))\n np.savez(stats_filename,\n t_val = soma_stats[..., 0],\n p_val = soma_stats[..., 1],\n zscore = soma_stats[..., 2])\n\n zmaps_all[str(region)]=soma_stats[..., 2]\n \n zscore_file = os.path.join(out_dir,'z_%s_contrast.npy' %(region))\n np.save(zscore_file,soma_stats[..., 2])\n\n\n# now do rest of the contrasts within region\n# do contrasts only in regions that are relevant (finger contrast only within hand region)\n\nprint('Using z-score of %0.2f as threshold for localizer' %z_threshold)\n\n# compute masked data for R+L hands and for face\n# to be used in more detailed contrasts\ndata_upmask = mask_data(data_masked.T,zmaps_all['upper_limb'],threshold=z_threshold,side='above')\ndata_facemask = mask_data(data_masked.T,zmaps_all['face'],threshold=z_threshold,side='above')\ndata_lowmask = mask_data(data_masked.T,zmaps_all['lower_limb'],threshold=z_threshold,side='above')\n\n\n# compare left and right\nprint('Right vs Left contrasts')\n\nlimbs = [['hand',analysis_params['all_contrasts']['upper_limb']],['leg',analysis_params['all_contrasts']['lower_limb']]]\n \nfor _,key in enumerate(limbs):\n print('For %s' %key[0])\n \n rtask = [s for s in key[1] if 'r'+key[0] in s]\n ltask = [s for s in key[1] if 'l'+key[0] in s]\n tasks = [rtask,ltask] # list with right and left elements\n \n contrast = make_contrast(design_matrix.columns,tasks,[1,-1],num_cond=2)\n \n # compute contrast-related statistics\n data4stat = data_lowmask.T if key[0]=='leg' else data_upmask.T\n \n soma_stats = Parallel(n_jobs=16)(delayed(compute_stats)(vert, design_matrix.values,contrast,betas[w]) for w,vert in enumerate(data4stat))\n soma_stats = np.vstack(soma_stats) # t_val,p_val,zscore\n # save estimates in dir \n stats_filename = os.path.join(out_dir,'z_right-left_'+key[0]+'_contrast_thresh-%0.2f_stats.npz' %(z_threshold))\n np.savez(stats_filename,\n t_val = soma_stats[..., 0],\n p_val = soma_stats[..., 1],\n zscore = soma_stats[..., 2])\n\n zmaps_all['RL_'+key[0]]=soma_stats[..., 2]\n\n zscore_file = os.path.join(out_dir,'z_right-left_'+key[0]+'_contrast_thresh-%0.2f.npy'%z_threshold)\n np.save(zscore_file,soma_stats[..., 2]) \n\n\n# compare each finger with the others of same hand\nprint('Contrast one finger vs all others of same hand')\n\nbhand_label = ['lhand','rhand']\n\nfor j,lbl in enumerate(bhand_label):\n \n print('For %s' %lbl)\n\n if lbl == 'lhand': # estou aqui, pensar melhor nisto\n data_RLmask = mask_data(data_upmask,zmaps_all['RL_hand'],side='below')\n elif lbl == 'rhand':\n data_RLmask = mask_data(data_upmask,zmaps_all['RL_hand'],side='above')\n \n hand_label = [s for s in analysis_params['all_contrasts']['upper_limb'] if lbl in s] #list of all fingers in one hand \n otherfings = leave_one_out_lists(hand_label) # list of lists with other fingers to contrast \n \n for i,fing in enumerate(hand_label):\n contrast = make_contrast(design_matrix.columns,[[fing],otherfings[i]],[1,-1/4.0],num_cond=2)\n \n soma_stats = Parallel(n_jobs=16)(delayed(compute_stats)(vert, design_matrix.values,contrast,betas[w]) for w,vert in enumerate(data_RLmask.T))\n soma_stats = np.vstack(soma_stats) # t_val,p_val,zscore\n # save estimates in dir \n stats_filename = os.path.join(out_dir,'z_%s-all_%s_contrast_thresh-%0.2f_stats.npz' %(fing,lbl,z_threshold))\n np.savez(stats_filename,\n t_val = soma_stats[..., 0],\n p_val = soma_stats[..., 1],\n zscore = soma_stats[..., 2])\n\n zscore_file = os.path.join(out_dir,'z_%s-all_%s_contrast_thresh-%0.2f.npy'%(fing,lbl,z_threshold))\n np.save(zscore_file,soma_stats[..., 2]) \n\n\n# compare each face region with the others\nprint('Contrast one face part vs all others within face')\n \nface = analysis_params['all_contrasts']['face']\notherface = leave_one_out_lists(face) # list of lists with other fingers to contrast \n\nfor i,part in enumerate(face):\n contrast = make_contrast(design_matrix.columns,[[part],otherface[i]],[1,-1/3.0],num_cond=2)\n \n soma_stats = Parallel(n_jobs=16)(delayed(compute_stats)(vert, design_matrix.values,contrast,betas[w]) for w,vert in enumerate(data_facemask.T))\n soma_stats = np.vstack(soma_stats) # t_val,p_val,zscore\n # save estimates in dir \n stats_filename = os.path.join(out_dir,'z_%s-other_face_areas_contrast_thresh-%0.2f_stats.npz' %(part,z_threshold))\n np.savez(stats_filename,\n t_val = soma_stats[..., 0],\n p_val = soma_stats[..., 1],\n zscore = soma_stats[..., 2])\n\n zscore_file = os.path.join(out_dir,'z_%s-other_face_areas_contrast_thresh-%0.2f.npy' %(part,z_threshold))\n np.save(zscore_file,soma_stats[..., 2]) \n\n\nprint('Success!')\n\n\n\n\n","sub_path":"analysis/soma_glmfit.py","file_name":"soma_glmfit.py","file_ext":"py","file_size_in_byte":9850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"271239756","text":"__author__ = 'bach'\r\n\r\nimport boto\r\nimport time\r\n\r\ns3 = boto.connect_s3(profile_name='bach')\r\n\r\nbucket = s3.create_bucket('boto-demo-%s' % int(time.time()))\r\n\r\nkey = bucket.new_key('mykey')\r\nkey.set_contents_from_string(\"Hello, World!\")\r\n\r\ntime.sleep(2)\r\n\r\nprint(key.get_contents_as_string())\r\n","sub_path":"aws/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"277254285","text":"import os, sys, time\r\nimport numpy as np\r\n\r\ndef generator_getClassifiedItems(clf, generator, classified):\r\n temp_X = []\r\n temp_y = []\r\n for idx in range(generator.step_per_epoch):\r\n batch_x, batch_y = generator.__getitem__(idx)\r\n for i, val in enumerate(batch_x):\r\n c = clf.predict([val.flatten()])[0]\r\n if classified == c:\r\n temp_X.append(batch_x[i])\r\n temp_y.append(batch_y[i])\r\n return np.array(temp_X), np.array(temp_y)\r\n \r\ndef SaveSummary(model, path):\r\n with open(path + '/report.txt', 'w') as fh:\r\n model.summary(print_fn=lambda x: fh.write(x + '\\n'))\r\n\r\nclass ShowProcess():\r\n i = 0 \r\n max_steps = 0 \r\n max_arrow = 50 \r\n infoDone = 'Done'\r\n\r\n \r\n def __init__(self, max_steps, infoDone=None):\r\n self.max_steps = max_steps\r\n self.i = 0\r\n self.infoDone = infoDone\r\n\r\n def show_process(self, i=None):\r\n if i is not None:\r\n self.i = i\r\n else:\r\n self.i += 1\r\n num_arrow = int(self.i * self.max_arrow / self.max_steps)\r\n num_line = self.max_arrow - num_arrow \r\n percent = self.i * 100.0 / self.max_steps \r\n process_bar = '[' + '>' * num_arrow + '-' * num_line + ']'\\\r\n + '%.2f' % percent + '%' + '\\r' \r\n sys.stdout.write(process_bar) \r\n sys.stdout.flush()\r\n if self.i >= self.max_steps:\r\n self.close()\r\n\r\n def close(self):\r\n print('')\r\n if self.infoDone:\r\n print(self.infoDone)\r\n self.i = 0\r\n\r\n","sub_path":"CustomUtils.py","file_name":"CustomUtils.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"517245905","text":"from typing import List\n\nfrom fb_post_auth.dtos.fb_post import UserDTO\nfrom fb_post_auth.interactors.storages.storage_interface import \\\n StorageInterface\nfrom fb_post_auth.models import User\n\n\nclass StorageImplementation(StorageInterface):\n\n def get_user_details_dtos(self, user_ids: List[int]) -> List[UserDTO]:\n users = User.objects.filter(id__in=user_ids)\n user_dtos = []\n for user in users:\n user_dto = self._convert_user_object_to_dto(user=user)\n user_dtos.append(user_dto)\n return user_dtos\n\n @staticmethod\n def _convert_user_object_to_dto(user):\n return UserDTO(user_id=user.id,\n name=user.name,\n profile_pic_url=user.profile_pic_url)\n","sub_path":"fb_post_auth/storages/storage_implementation.py","file_name":"storage_implementation.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"337531152","text":"# Copyright 2016 Mirantis Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfrom glanceclient import exc as glance_exc\nimport mock\nfrom tests import test\n\nfrom cloudferrylib.base import exception\nfrom cloudferrylib.os.actions import check_filter\n\n\nclass CheckFilterTestCase(test.TestCase):\n def setUp(self):\n super(CheckFilterTestCase, self).setUp()\n\n fake_src_cloud = mock.Mock()\n self.fake_src_image = mock.Mock()\n\n fake_src_cloud.resources = {\n 'image': self.fake_src_image,\n }\n\n self.fake_init = {\n 'src_cloud': fake_src_cloud,\n }\n\n def test_check_opts_img_with_error_in_filter_config(self):\n fake_action = check_filter.CheckFilter(self.fake_init,\n cloud='src_cloud')\n\n opts = {\n 'images_list': 'foo',\n 'exclude_images_list': 'bar',\n }\n\n self.assertRaises(exception.AbortMigrationError,\n fake_action._check_opts_img,\n opts)\n\n def test_check_opts_img_if_image_exists(self):\n fake_action = check_filter.CheckFilter(self.fake_init,\n cloud='src_cloud')\n image = mock.Mock()\n\n opts = {\n 'images_list': [image.id]\n }\n self.fake_src_image.glance_client.images.get.return_value = image\n\n fake_action._check_opts_img(opts)\n\n self.fake_src_image.glance_client.images.\\\n get.assert_called_once_with(image.id)\n\n def test_check_opts_img_if_doesnt_image_exist(self):\n fake_action = check_filter.CheckFilter(self.fake_init,\n cloud='src_cloud')\n image = mock.Mock()\n opts = {\n 'images_list': [image.id]\n }\n self.fake_src_image.glance_client.images.\\\n get.side_effect = glance_exc.HTTPNotFound\n\n self.assertRaises(glance_exc.HTTPNotFound,\n fake_action._check_opts_img,\n opts)\n\n self.fake_src_image.glance_client.images.\\\n get.assert_called_once_with(image.id)\n","sub_path":"tests/cloudferrylib/os/actions/test_check_filter.py","file_name":"test_check_filter.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"370800906","text":"#!/usr/bin/env python\n\nimport wx\n\nclass MouseEventFrame(wx.Frame):\n\n def __init__(self, parent, id):\n wx.Frame.__init__(self, parent, id, 'Emotional Button',\n size=(300,100))\n #EVT Handling procedure being explored below\n #Looking for the bound handler function...\n #...Goes from triggering object up the container hierarchy\n #Only instances of wx.CommandEvent propogate\n self.panel = wx.Panel(self)\n #Bind to panel\n self.button = wx.Button(self.panel, label=\"Hello!\", pos=(100,15))\n #Bind to frame\n self.Bind(wx.EVT_BUTTON, self.OnButtonClick, self.button)\n #Bind to button\n #Mouse events are not subclasses of wx.CommandEvent,\n #...do not propogate up and not function or will affect whole frame\n self.button.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)\n self.button.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)\n\n def OnButtonClick(self, event):\n if self.panel.BackgroundColour != 'Red':\n self.panel.SetBackgroundColour('Red')\n self.panel.Refresh()\n else:\n self.panel.SetBackgroundColour('White')\n self.panel.Refresh()\n\n def OnEnterWindow(self, event):\n self.button.SetLabel(\"WHOOP!\")\n #calling Skip requests further processing\n #invoking the default functionality not contained within the button\n event.Skip()\n\n def OnLeaveWindow(self, event):\n if self.panel.BackgroundColour != 'Red':\n self.button.SetLabel(\":'(\")\n if self.panel.BackgroundColour == 'Red':\n self.button.SetLabel(\":D\")\n event.Skip()\n\nif __name__ == '__main__':\n app = wx.App(False)\n frame = MouseEventFrame(parent=None, id=-1)\n frame.Show()\n app.MainLoop()\n","sub_path":"mouseevents.py","file_name":"mouseevents.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69556660","text":"import json\nimport re\n\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\n\nfrom ceng445.models import Paper\nfrom ceng445.repository.DjangoRepository import _databasePaperToActualPaper\nfrom ceng445.service.PController import Pcontroller\n\nfrom socket import *\n\nwebSocketSender = socket(AF_INET,SOCK_DGRAM)\nserverAddress = ('127.0.0.1',9999)\n\nallConnectedClients= []\n\nnewWatchers = []\nidWatchers = []\nkeywordWatchers = []\n\n\ndef sendNotification(receiverId,message,type=\"update\"):\n sendindDict = {}\n sendindDict[\"id\"] = str(receiverId)\n if(type == \"alert\"):\n sendindDict[\"notificationType\"] = \"alert\"\n else:\n sendindDict[\"notificationType\"] = \"update\"\n\n sendindDict[\"message\"] = message\n\n webSocketSender.sendto(json.dumps(sendindDict).encode(),serverAddress)\n\n\n\ndef sendUpdateNotifications(message,entryClient):\n for client in allConnectedClients:\n if(client != entryClient):\n sendNotification(client,message)\n\n\ndef sendAlertNotifications(notificationType,paper):\n for client in newWatchers:\n if(notificationType == \"add\"):\n message = \"A new paper with ID: \" + str(paper.id) + \" has been added!\"\n sendNotification(client,message,\"alert\")\n\n for client in idWatchers:\n notificationId = client[\"paperId\"]\n clientId = client[\"clientId\"]\n if(notificationId == paper.id):\n if(notificationType == \"add\"):\n message = \"A new paper with ID: \" + str(paper.id) + \" has been added!\"\n elif(notificationType == \"delete\"):\n message = \"The paper with ID: \" + str(paper.id) + \" has been deleted!\"\n else:\n message = \"The paper with ID: \" + str(paper.id) + \" has been edited!\"\n sendNotification(clientId,message,\"alert\")\n\n for client in keywordWatchers:\n clientId = client[\"clientId\"]\n watchKeyword = client[\"keyword\"]\n\n if(watchKeyword in paper.wordContent):\n if(notificationType == \"add\"):\n message = \"A new paper with keyword: \" + watchKeyword +\" that has ID: \"+ str(paper.id) + \" has been added!\"\n elif(notificationType == \"delete\"):\n message = \"The paper that had keyword: \" + watchKeyword + \" that has ID: \" + str(paper.id) + \" has been deleted!\"\n else:\n message = \"The paper that has keyword: \" + watchKeyword + \" that has ID: \" + str(paper.id) + \" has been edited!\"\n sendNotification(clientId,message,\"alert\")\n\n\ndef index(request):\n context = {}\n\n paperList = list(Paper.objects.all())\n\n context[\"paperList\"] = paperList\n # jsonModelContent = serializers.serialize(\"json\",Paper.objects.all())\n\n\n # return render(request,'index.html',context)\n sendNotification(123,\"hebele\")\n return render(request,\"newIndex.html\")\n\ndef getIndexPaperContent(request):\n paperList = list(Paper.objects.all())\n\n\n allConnectedClients.append(request.GET[\"webSocketId\"])\n jsonStringList = []\n\n for p in paperList:\n paperDict = p.getString()\n\n\n jsonStringList.append(paperDict)\n\n response = JsonResponse(json.dumps(jsonStringList),safe=False)\n\n return response\n\ndef download(request,paperId):\n requestedPaper = Paper.objects.get(id=paperId)\n\n response = HttpResponse(requestedPaper.content,content_type=\"application/pdf\")\n return response\n\n\n\ndef showMeta(request,paperId):\n dbPaper = Paper.objects.get(id=paperId)\n print(dbPaper.metaData)\n # returnDictString = dbPaper.metaData.replace(', \\'',',\\n\\'')\n returnDictString = re.sub(r',([ ]*)\\'', ',\\n\\'',dbPaper.metaData)\n print(returnDictString)\n\n return HttpResponse('
'+returnDictString+'
')\n\ndef addPaper(request):\n from ceng445.service import Paper as paper\n\n newPaper = paper.Paper(saveToDatabase=True)\n requestDict = request.POST\n\n if(requestDict[\"metaData\"] != \"\"):\n newPaper.setMetaByBibtex(requestDict[\"metaData\"])\n if(len(request.FILES) > 0):\n paperFile = request.FILES[\"file\"]\n newPaper.upload(paperFile.read())\n\n p = Paper.objects.get(id=newPaper.id)\n paperDict = p.getString()\n\n entryClient = request.POST[\"clientId\"]\n\n updateNotificationMessage = {}\n\n\n updateNotificationMessage[\"actionType\"] = \"add\"\n updateNotificationMessage[\"paper\"] = paperDict\n\n sendUpdateNotifications(updateNotificationMessage,entryClient)\n\n sendAlertNotifications(\"add\",p)\n\n\n\n\n return JsonResponse(json.dumps(paperDict),safe=False)\n\n\n\ndef editPaper(request,paperId):\n requestDict = request.POST\n\n dbPaper = Paper.objects.get(id=paperId)\n newPaper = _databasePaperToActualPaper(dbPaper)\n\n if (requestDict[\"metaData\"] != \"\"):\n newPaper.setMetaByBibtex(requestDict[\"metaData\"])\n if (len(request.FILES) > 0):\n paperFile = request.FILES[\"file\"]\n newPaper.upload(paperFile.read())\n\n\n p = Paper.objects.get(id=newPaper.id)\n paperDict = p.getString()\n\n entryClient = request.POST[\"clientId\"]\n\n updateNotificationMessage = {\n \"actionType\":\"edit\",\n \"paper\":paperDict\n }\n sendUpdateNotifications(updateNotificationMessage,entryClient)\n sendAlertNotifications(\"edit\",p)\n\n\n return JsonResponse(json.dumps(paperDict),safe=False)\n\n\ndef deletePaper(request,paperId):\n\n controller = Pcontroller()\n toBeDeletedPaper = controller.getPaper(paperId)\n\n\n updateNotificationMessage = {}\n\n\n updateNotificationMessage[\"actionType\"] = \"delete\"\n updateNotificationMessage[\"paperId\"] = paperId\n\n entryClient = request.GET[\"clientId\"]\n sendUpdateNotifications(updateNotificationMessage,entryClient)\n sendAlertNotifications(\"delete\",toBeDeletedPaper)\n\n controller.deletePaper(paperId)\n\n return HttpResponse()\n\n\ndef searchTitle(request):\n requestDict = request.POST\n\n title = requestDict[\"paperTitle\"]\n controller = Pcontroller()\n if(title != \"\"):\n\n papers = controller.searchbyTitle(title)\n context = {\"paperList\": papers}\n else:\n context = {}\n\n return render(request,\"index.html\",context)\n\n\ndef searchAuthor(request):\n requestDict = request.POST\n\n author = requestDict[\"paperAuthor\"]\n controller = Pcontroller()\n if (author != \"\"):\n\n papers = controller.searchbyAuthor(author)\n context = {\"paperList\": papers}\n else:\n context = {}\n\n return render(request, \"index.html\", context)\n\ndef searchContent(request):\n requestDict = request.POST\n\n words = requestDict[\"paperWords\"]\n controller = Pcontroller()\n if (words != \"\"):\n\n papers = controller.searchbyContent(words)\n returnJson = [p.getString() for p in papers]\n context = {\"paperList\": papers}\n else:\n returnJson = []\n context = {}\n\n return JsonResponse(json.dumps(returnJson),safe=False)\n\ndef searchScholar(request):\n requestDict = request.POST\n\n author = requestDict[\"scholarAuthor\"]\n title = requestDict[\"scholarTitle\"]\n num = requestDict[\"scholarNum\"]\n if(num == ''):\n num = 10\n else:\n num = int(num)\n\n controller = Pcontroller()\n\n response = controller.searchScholar(author,title,num)\n returnString = \"\"\n for r in response:\n returnString += re.sub(r',([ ]*)\\'', ',\\n\\'',str(r)) + '\\n'\n\n return HttpResponse(\"
\"+returnString+\"
\")\n\n\ndef watchPaper(request):\n queryDict = request.POST\n\n if(queryDict[\"type\"] == \"new\"):\n newWatchers.append(queryDict[\"clientId\"])\n elif(queryDict[\"type\"] == \"id\"):\n idWatchers.append({\"clientId\":queryDict[\"clientId\"],\"paperId\":int(queryDict[\"watchPaperId\"])})\n else:\n keywordWatchers.append({\"clientId\":queryDict[\"clientId\"],\"keyword\":queryDict[\"watchKeyword\"]})\n return HttpResponse()","sub_path":"ceng445/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"102043700","text":"import os\nimport glob\nimport re\nimport sys\n\ndef search_sequence_in_tds(case_name, tdsfile):\n with open(tdsfile, 'r') as fh:\n case_found = False\n sequence_found = False\n exitsequence_found = False\n head_spaces = 0\n for line in fh:\n if (not case_found) and re.match('%s:$' % case_name, line):\n print (tdsfile)\n print(line.rstrip())\n #import pdb; pdb.set_trace()\n case_found = True\n elif case_found and re.search(' Sequence:', line, re.IGNORECASE):\n print(line.rstrip())\n head_spaces = line.count(' ')\n #print('line is %d' % head_spaces\n sequence_found = True\n elif case_found and re.search(' ExitSequence:', line, re.IGNORECASE):\n print(line.rstrip())\n head_spaces = line.count(' ')\n #print('line is %d' % head_spaces\n exitsequence_found = True\n elif sequence_found and ((line.count(' ') > head_spaces) or line == \"\\n\"):\n print(line.rstrip())\n elif exitsequence_found and ((line.count(' ') > head_spaces) or line == \"\\n\"):\n print(line.rstrip())\n elif case_found and line.count(' ') == 0:\n break\n \n # below 2 conditions can be omitted\n elif sequence_found and line.count(' ') == head_spaces:\n sequence_found = False\n elif exitsequence_found and line.count(' ') == head_spaces:\n exitsequence_found = False\n\ndef main(case_name, root='health'):\n tds_root = '/home/jian/%s/vdnet/automation/TDS/EsxServer' % root\n files = glob.glob(os.path.join(tds_root, '*'))\n\n for folder in files:\n yaml_files = glob.glob(os.path.join(folder, '*.yaml'))\n for yf in yaml_files:\n search_sequence_in_tds(case_name, yf)\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 1:\n print(\"Usage: %s [root_path]\" % sys.argv[0])\n elif len(sys.argv) == 2:\n main(sys.argv[1])\n elif len(sys.argv) == 3:\n main(sys.argv[1], sys.argv[2])\n","sub_path":"show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":2166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"337844026","text":"# -*- coding: utf-8 -*-\nimport json\nimport scrapy\nfrom locations.items import GeojsonPointItem\nfrom locations.hours import OpeningHours\n\nweekdays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']\nday_mapping = {'sunday': 'Su', 'monday': 'Mo', 'tuesday': 'Tu', 'wednesday': 'We',\n 'thursday': 'Th', 'friday': 'Fr', 'saturday': 'Sa'}\n\n\ndef convert_24hour(time):\n \"\"\"\n Takes 12 hour time as a string and converts it to 24 hour time.\n \"\"\"\n # Check if 12:00 AM\n if time[-2:] == \"AM\" and time[:2] == \"12\":\n return \"00\" + time[2:-2]\n\n # Remove AM\n elif time[-2:] == \"AM\":\n return time[:-2]\n\n # Check if 12:00 PM\n elif time[-2:] == \"PM\" and time[:2] == \"12\":\n return time[:-2]\n\n else:\n # add 12 hours and remove PM\n return str(int(time[:2]) + 12) + time[2:-2]\n\n\nclass ChristmasTreeShopsSpider(scrapy.Spider):\n name = \"christmas_tree_shops\"\n item_attributes = { 'brand': \"Christmas Tree Shops\" }\n allowed_domains = ['www.christmastreeshops.com']\n start_urls = [\n 'https://www.christmastreeshops.com/store-locator',\n ]\n\n def parse(self, request):\n url = 'https://www.christmastreeshops.com/api/commerce/storefront/locationUsageTypes/SP/locations/'\n yield scrapy.Request(url, self.parse_store)\n\n def parse_store(self, response):\n json_data = json.loads(response.text)\n stores = json_data[\"items\"]\n for store_data in stores:\n properties = {\n 'name': store_data[\"name\"],\n 'ref': store_data[\"code\"],\n 'addr_full': store_data[\"address\"][\"address1\"],\n 'city': store_data[\"address\"][\"cityOrTown\"],\n 'state': store_data[\"address\"][\"stateOrProvince\"],\n 'postcode': store_data[\"address\"][\"postalOrZipCode\"],\n 'country': store_data[\"address\"][\"countryCode\"],\n 'phone': store_data.get(\"phone\"),\n 'lat': float(store_data[\"geo\"][\"lat\"]),\n 'lon': float(store_data[\"geo\"][\"lng\"]),\n }\n\n hours = self.parse_hours(store_data.get(\"regularHours\"))\n if hours:\n properties[\"opening_hours\"] = hours\n\n yield GeojsonPointItem(**properties)\n\n def parse_hours(self, open_hours):\n opening_hours = OpeningHours()\n\n for weekday in weekdays:\n day = day_mapping[weekday]\n day_hours = open_hours.get(weekday).get('label')\n\n # Check if store is closed that day\n if day_hours in ('x', ''):\n continue\n\n open_time = convert_24hour(day_hours.split('-')[0])\n close_time = convert_24hour(day_hours.split('-')[1])\n opening_hours.add_range(day=day,\n open_time=open_time,\n close_time=close_time)\n\n return opening_hours.as_opening_hours()\n","sub_path":"locations/spiders/christmas_tree_shops.py","file_name":"christmas_tree_shops.py","file_ext":"py","file_size_in_byte":2964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"611114656","text":"import xml.etree.ElementTree as ET\nimport urllib.request\nimport urllib.parse\nimport urllib.error\n\nurl = 'http://py4e-data.dr-chuck.net/comments_275915.xml' # 指定URL\nuh = urllib.request.urlopen(url)\ndata = uh.read() #获取网页数据\n\nprint('Retrived', len(data), 'characters')\ntree = ET.fromstring(data)\ncounts = tree.findall('.//count') #查找count标签\nprint('Count:', len(counts))\n\nres = 0\nfor count in counts:\n res = res + int(count.text)\n\nprint('Sum:', res)\n","sub_path":"summer-2019/python-task/xml-count.py","file_name":"xml-count.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"296123809","text":"def p_factorization_t(n):\n if n == 1: return []\n pf_cnt = []\n temp = n\n for i in range(2, int(-(-n**0.5//1))+1):\n if temp%i == 0:\n cnt = 0\n while temp%i == 0:\n cnt += 1\n temp //= i\n pf_cnt.append((i,cnt))\n\n if temp != 1: pf_cnt.append((temp,1))\n return pf_cnt\n\nn=int(input())\nanss = {}\n\nfor i in range(2,n+1):\n facs = p_factorization_t(i)\n for k,v in facs:\n if not k in anss:\n anss[k]=v\n else:\n anss[k] = max(anss[k], v)\n\nans=1\nfor k,v in anss.items():\n ans *= pow(k,v)\n\nprint(ans+1)\n","sub_path":"1_contest/previous/arc110/a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410592200","text":"from kafka import KafkaConsumer\nimport json\nimport time\n\n''' CONSUMER CLASS '''\nclass ConsumerServer(KafkaConsumer): \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.bootstrap_servers=\"localhost:9092\"\n self.value_deserializer=lambda m: json.loads(m.decode('utf-8'))\n \n ''' reading messages'''\n def consume(self):\n for message in self:\n print (message.value)\n \n''' consumer instance with topic subscription ''' \npolice_calls_kfk = ConsumerServer(\"udacity.project2.police.calls_3\")\n\n''' invoking reading function '''\npolice_calls_kfk.consume()","sub_path":"consumer_server.py","file_name":"consumer_server.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"489065132","text":"\n# coding: utf-8\n\n# # Data Analysis\n\n# In[7]:\n\n\nimport math\nimport IPython\nimport time\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\n\nfrom sklearn import preprocessing, decomposition, discriminant_analysis, tree\n\npd.options.display.max_columns = None\n\n\n# In[3]:\n\n\nraw_train_credit_application = pd.read_csv('data/application_train.csv')\nraw_test_credit_application = pd.read_csv('data/application_test.csv')\n\nraw_bureau = pd.read_csv('data/bureau.csv')\n# raw_bureau_balance = pd.read_csv('data/bureau_balance.csv')\n# raw_credit_card_balance = pd.read_csv('data/credit_card_balance.csv')\n# raw_installments_payments = pd.read_csv('data/installments_payments.csv')\n# raw_pos_cash_balance = pd.read_csv('data/pos_cash_balance.csv')\n# raw_previous_application = pd.read_csv('data/previous_application.csv')\n\n\n# In[4]:\n\n\nall_features = list(set(raw_train_credit_application.columns.values.tolist()) - set(['SK_ID_CURR', 'TARGET']))\n\nnon_features = ['SK_ID_CURR', 'TARGET']\n\ncategorical_features = ['NAME_CONTRACT_TYPE', 'NAME_TYPE_SUITE', 'NAME_INCOME_TYPE', \n 'NAME_EDUCATION_TYPE', 'NAME_FAMILY_STATUS', 'NAME_HOUSING_TYPE', \n 'OCCUPATION_TYPE', 'WEEKDAY_APPR_PROCESS_START', 'ORGANIZATION_TYPE', \n 'FONDKAPREMONT_MODE', 'HOUSETYPE_MODE', 'WALLSMATERIAL_MODE', \n 'EMERGENCYSTATE_MODE',\n ]\n\nflag_features = ['CODE_GENDER', \n 'FLAG_OWN_CAR', 'FLAG_OWN_REALTY', 'FLAG_MOBIL', 'FLAG_EMP_PHONE', \n 'FLAG_WORK_PHONE', 'FLAG_CONT_MOBILE', 'FLAG_PHONE', 'FLAG_EMAIL', \n 'FLAG_DOCUMENT_2', 'FLAG_DOCUMENT_3', 'FLAG_DOCUMENT_4', 'FLAG_DOCUMENT_5', \n 'FLAG_DOCUMENT_6', 'FLAG_DOCUMENT_7', 'FLAG_DOCUMENT_8', 'FLAG_DOCUMENT_9', \n 'FLAG_DOCUMENT_10', 'FLAG_DOCUMENT_11', 'FLAG_DOCUMENT_12', 'FLAG_DOCUMENT_13', \n 'FLAG_DOCUMENT_14', 'FLAG_DOCUMENT_15', 'FLAG_DOCUMENT_16', 'FLAG_DOCUMENT_17', \n 'FLAG_DOCUMENT_18', 'FLAG_DOCUMENT_19', 'FLAG_DOCUMENT_20', 'FLAG_DOCUMENT_21',\n 'REG_REGION_NOT_LIVE_REGIONREG_REGION_NOT_LIVE_REGION', 'REG_REGION_NOT_WORK_REGION', \n 'LIVE_REGION_NOT_WORK_REGION', 'REG_CITY_NOT_LIVE_CITY', 'REG_CITY_NOT_WORK_CITY', \n 'LIVE_CITY_NOT_WORK_CITY',\n ]\n\nnumerical_features = list(set(all_features) - set(non_features) - set(categorical_features) - set(flag_features))\n\n\n# # Feature Engineering I\n\n# In[5]:\n\n\ntrain_SK_ID_CURR = raw_train_credit_application['SK_ID_CURR'].unique()\ntest_SK_ID_CURR = raw_test_credit_application['SK_ID_CURR'].unique()\n\n\n# In[ ]:\n\n\nadd_columns = [\n 'SK_ID_CURR',\n \n 'BUR_credit_active',\n 'BUR_credit_closed',\n 'BUR_credit_sold',\n 'BUR_credit_bad_debt',\n]\n\nadd_train_credit_application = pd.DataFrame(columns=add_columns)\nindex = 0\nfor SK_ID_CURR in train_SK_ID_CURR:\n if index % 1000 == 0:\n print(index, time.time())\n bureau_SK_ID_CURR = raw_bureau.loc[raw_bureau['SK_ID_CURR'] == SK_ID_CURR]\n credit_active_value_counts = bureau_SK_ID_CURR['CREDIT_ACTIVE'].value_counts()\n \n BUR_credit_active = credit_active_value_counts['Active'] if 'Active' in credit_active_value_counts else 0\n BUR_credit_closed = credit_active_value_counts['Closed'] if 'Closed' in credit_active_value_counts else 0\n BUR_credit_sold = credit_active_value_counts['Sold'] if 'Sold' in credit_active_value_counts else 0\n BUR_credit_bad_debt = credit_active_value_counts['Bad Debt'] if 'Bad Debt' in credit_active_value_counts else 0\n \n add_train_credit_application.loc[index] = [SK_ID_CURR, \n BUR_credit_active,\n BUR_credit_closed,\n BUR_credit_sold,\n BUR_credit_bad_debt,]\n \n index = index + 1\n\n\n# In[ ]:\n\n\n\nadd_test_credit_application = pd.DataFrame(columns=add_columns)\nindex = 0\nfor SK_ID_CURR in test_SK_ID_CURR:\n if index % 1000 == 0:\n print(index)\n bureau_SK_ID_CURR = raw_bureau.loc[raw_bureau['SK_ID_CURR'] == SK_ID_CURR]\n credit_active_value_counts = bureau_SK_ID_CURR['CREDIT_ACTIVE'].value_counts()\n \n BUR_credit_active = credit_active_value_counts['Active'] if 'Active' in credit_active_value_counts else 0\n BUR_credit_closed = credit_active_value_counts['Closed'] if 'Closed' in credit_active_value_counts else 0\n BUR_credit_sold = credit_active_value_counts['Sold'] if 'Sold' in credit_active_value_counts else 0\n BUR_credit_bad_debt = credit_active_value_counts['Bad Debt'] if 'Bad Debt' in credit_active_value_counts else 0\n \n add_test_credit_application.loc[index] = [SK_ID_CURR, \n BUR_credit_active,\n BUR_credit_closed,\n BUR_credit_sold,\n BUR_credit_bad_debt,]\n \n index = index + 1\n\n\n# In[ ]:\n\n\ntrain_credit_application_1 = pd.merge(left=raw_train_credit_application, right=add_train_credit_application, left_on='SK_ID_CURR', right_on='SK_ID_CURR', how='outer')\ntest_credit_application_1 = pd.merge(left=raw_test_credit_application, right=add_test_credit_application, left_on='SK_ID_CURR', right_on='SK_ID_CURR', how='outer')\n\n\n# In[ ]:\n\n\ntrain_credit_application_1.to_pickle('train_credit_application_1')\ntest_credit_application_1.to_pickle('test_credit_application_1')\n","sub_path":"data_model.py","file_name":"data_model.py","file_ext":"py","file_size_in_byte":5612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"24540649","text":"import socket\nimport unittest\n\nfrom hypothesis import given, settings\nfrom hypothesis.strategies import integers\n\nimport lib.utils as utils\n\nclass TestUtils(unittest.TestCase):\n def test_extract_schema_from_snapshot(self):\n snapshot_path = 'test/unittest/00000000000000000003.snap'\n v = utils.extract_schema_from_snapshot(snapshot_path)\n self.assertEqual(v, (2, 3, 1))\n\n @settings(max_examples=5)\n @given(port=integers(65100, 65535))\n def test_check_port(self, port):\n def open_socket(p):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind(('localhost', p))\n s.listen(0)\n return s\n status = utils.check_port(port, rais=False, ipv4=True, ipv6=False)\n self.assertEqual(status, True)\n s = open_socket(port)\n status = utils.check_port(port, rais=False, ipv4=True, ipv6=False)\n s.close()\n self.assertEqual(status, False)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/unittest/test_lib_utils.py","file_name":"test_lib_utils.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"536028991","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom preggy import expect\n\nfrom holmes.models import Violation, Key\nfrom holmes.utils import _\nfrom tests.unit.base import ApiTestCase\nfrom tests.fixtures import ViolationFactory, KeyFactory, DomainFactory\n\n\nclass TestViolations(ApiTestCase):\n def test_can_create_violation(self):\n violation = ViolationFactory.create(\n key=Key(name='some.random.fact'), value='value', points=1203\n )\n\n loaded_violation = self.db.query(Violation).get(violation.id)\n\n expect(loaded_violation.value).to_equal('value')\n expect(loaded_violation.key.name).to_equal('some.random.fact')\n expect(loaded_violation.points).to_equal(1203)\n expect(str(loaded_violation)).to_be_like('%s: %s' % (\n violation.key.name,\n violation.value,\n ))\n\n def test_to_dict(self):\n violation = ViolationFactory.create(\n key=Key(name='some.random.fact'),\n value='value',\n points=1203,\n )\n\n violations_definitions = {'some.random.fact': {}}\n\n expect(violation.to_dict(violations_definitions, _)).to_be_like({\n 'key': 'some.random.fact',\n 'description': 'value',\n 'title': 'undefined',\n 'points': 1203,\n 'category': 'undefined'\n })\n\n def test_to_dict_with_violations_definitions_params(self):\n violation1 = ViolationFactory.create(\n key=Key(name='some.random.fact.1'),\n value='value',\n points=120,\n )\n\n violation2 = ViolationFactory.create(\n key=Key(name='some.random.fact.2'),\n value='violations',\n points=500,\n )\n\n violation3 = ViolationFactory.create(\n key=Key(name='some.random.fact.3'),\n value={'page_url': 'http://globo.com'},\n points=300,\n )\n\n violation4 = ViolationFactory.create(\n key=Key(name='some.random.fact.4'),\n value=None,\n points=100,\n )\n\n violations_definitions = {\n 'some.random.fact.1': {'description': 'test'},\n 'some.random.fact.2': {'description': 'test for: %s'},\n 'some.random.fact.3': {'description': 'url: %(page_url)s'},\n 'some.random.fact.4': {'description': 'my description'},\n }\n\n expect(violation1.to_dict(violations_definitions, _)).to_be_like({\n 'key': 'some.random.fact.1',\n 'description': 'test',\n 'title': 'undefined',\n 'points': 120,\n 'category': 'undefined'\n })\n\n expect(violation2.to_dict(violations_definitions, _)).to_be_like({\n 'key': 'some.random.fact.2',\n 'description': 'test for: violations',\n 'title': 'undefined',\n 'points': 500,\n 'category': 'undefined'\n })\n\n expect(violation3.to_dict(violations_definitions, _)).to_be_like({\n 'key': 'some.random.fact.3',\n 'description': 'url: http://globo.com',\n 'title': 'undefined',\n 'points': 300,\n 'category': 'undefined'\n })\n\n expect(violation4.to_dict(violations_definitions, _)).to_be_like({\n 'key': 'some.random.fact.4',\n 'description': 'my description',\n 'title': 'undefined',\n 'points': 100,\n 'category': 'undefined'\n })\n\n\n def test_can_get_most_common_violations_names(self):\n for i in range(3):\n key = KeyFactory.create(name='some.random.fact.%s' % i)\n for j in range(i):\n ViolationFactory.create(key=key)\n\n violations = Violation.get_most_common_violations_names(self.db)\n\n expect(violations).to_be_like([('some.random.fact.1', 1), ('some.random.fact.2', 2)])\n\n def test_get_group_by_key_id_for_all_domains(self):\n domains = [DomainFactory.create(name='g%d.com' % i) for i in range(2)]\n keys = [KeyFactory.create(name='random.fact.%s' % i) for i in range(3)]\n\n for i in range(3):\n for j in range(i + 1):\n ViolationFactory.create(\n key=keys[i],\n domain=domains[j % 2]\n )\n\n violations = Violation.get_group_by_key_id_for_all_domains(self.db)\n\n expect(violations).to_length(5)\n expect(violations[0]).to_be_like((keys[2].id, 'g0.com', 2))\n\n def test_can_get_group_by_value_for_key(self):\n self.db.query(Key).delete()\n self.db.query(Violation).delete()\n keys = [KeyFactory.create(name='random.key.%s' % i) for i in range(3)]\n\n for i in range(3):\n for j in range(i + 1):\n ViolationFactory.create(\n key=keys[i],\n value='random.value.%d' % i\n )\n\n violations = Violation.get_group_by_value_for_key(self.db, keys[0].name)\n expect(violations).to_be_like([('random.value.0', 1)])\n\n violations = Violation.get_group_by_value_for_key(self.db, keys[1].name)\n expect(violations).to_be_like([('random.value.1', 2)])\n\n violations = Violation.get_group_by_value_for_key(self.db, keys[2].name)\n expect(violations).to_be_like([('random.value.2', 3)])\n\n def test_can_get_top_in_category_for_all_domains(self):\n domains = [DomainFactory.create(name='g%d.com' % i) for i in range(2)]\n keys = [KeyFactory.create(name='random.fact.%s' % i) for i in range(3)]\n\n for i in range(3):\n for j in range(i + 1):\n ViolationFactory.create(\n key=keys[i],\n domain=domains[j % 2]\n )\n violations = Violation.get_top_in_category_for_all_domains(self.db)\n\n expect(violations).to_length(5)\n top = ('g0.com', keys[2].category_id, str(keys[2]), 2)\n expect(violations[0]).to_be_like(top)\n","sub_path":"tests/unit/models/test_violations.py","file_name":"test_violations.py","file_ext":"py","file_size_in_byte":5946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"310068382","text":"from math import pi, atan, sin, cos\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import spatial\nfrom tqdm import tqdm\n\nimport seaborn\nseaborn.set()\nfrom Generic import images, filedialogs\nfrom ParticleTracking import dataframes, statistics\n\nfrom labvision import images\n\nimages.crop_polygon()\n\ndef run(direc, lattice_spacing=5):\n files = filedialogs.get_files_directory(direc + '/*.png')\n savename = direc + '/data.hdf5'\n\n N = len(files)\n\n # Load images\n ims = [images.load(f, 0) for f in tqdm(files, 'Loading images')]\n\n # Find Circles\n circles = [images.find_circles(im, 27, 200, 7, 16, 16)\n for im in tqdm(ims, 'Finding Circles')]\n\n # Save data\n data = dataframes.DataStore(savename, load=False)\n for f, info in tqdm(enumerate(circles), 'Adding Circles'):\n data.add_tracking_data(f, info, ['x', 'y', 'r'])\n\n # Calculate order parameter\n calc = statistics.PropertyCalculator(data)\n calc.order()\n\n # Get the course graining width\n cgw = get_cgw(data.df.loc[0]) / 2\n\n # Create the lattice points\n x = np.arange(0, max(data.df.x), lattice_spacing)\n y = np.arange(0, max(data.df.y), lattice_spacing)\n x, y = np.meshgrid(x, y)\n\n # Calculate the coarse order fields\n fields = [coarse_order_field(data.df.loc[f], cgw, x, y)\n for f in tqdm(range(N), 'Calculating Fields')]\n\n # Calculate the field threshold\n field_threshold = get_field_threshold(fields, lattice_spacing, ims[0])\n\n # Find the contours representing the boundary in each frame\n contours = [find_contours(f, field_threshold)\n for f in tqdm(fields, 'Calculating contours')]\n\n # Multiply the contours by the lattice spacing\n contours = [c * lattice_spacing for c in contours]\n\n # Find the angle of the image to rotate the boundary to the x-axis\n a, c, p1, p2 = get_angle(ims[0])\n\n # Rotate the selection points and the contours by the angle\n p1 = rotate_points(np.array(p1), c, a)\n p2 = rotate_points(np.array(p2), c, a)\n contours = [rotate_points(contour.squeeze(), c, a)\n for contour in contours]\n\n xmin = int(p1[0])\n xmax = int(p2[0])\n h = int(p1[1])\n\n # Get the heights of the fluctuations from the straight boundary\n hs = [get_h(contour, ims[0].shape, xmin, xmax, h)\n for contour in tqdm(contours, 'Calculating heights')]\n\n # Calculate the fourier transforms for all the frames\n L = xmax - xmin\n pixels_to_mms = 195/L\n print('One pixel is {:.2f} mm'.format(pixels_to_mms))\n\n #convert to mm\n hs = [h * pixels_to_mms for h in hs]\n L = L * pixels_to_mms\n\n k, yplot = get_fourier(hs, L)\n\n return k, yplot\n\n\ndef get_cgw(df):\n tree = spatial.cKDTree(df[['x', 'y']].values)\n dists, _ = tree.query(tree.data, 2)\n cgw = np.mean(dists[:, 1])\n return cgw\n\n\ndef coarse_order_field(df, cgw, x, y, no_of_neighbours=20):\n \"\"\"\n Calculate the coarse-grained field characterising local orientation order\n \"\"\"\n\n order = df.order.values\n\n # Generate the lattice nodes to query\n # x, y = np.meshgrid(x, y)\n r = np.dstack((x, y))\n\n # Get the positions of all the particles\n particles = df[['x', 'y']].values\n\n # Generate the tree from the particles\n tree = spatial.cKDTree(particles)\n\n # Query the tree at all the lattice nodes to find the nearest n particles\n # Set n_jobs=-1 to use all cores\n dists, indices = tree.query(r, no_of_neighbours, n_jobs=-1)\n\n # Calculate all the coarse-grained delta functions (Katira ArXiv eqn 3\n cg_deltas = np.exp(-dists ** 2 / (2 * cgw ** 2)) / (2 * pi * cgw ** 2)\n\n # Multiply by the orders to get the summands\n summands = cg_deltas * order[indices]\n\n # Sum along axis 2 to calculate the field\n field = np.sum(summands, axis=2)\n\n return field\n\n\ndef get_field_threshold(fields, ls, im):\n # Draw a box around an always ordered region of the image to\n # calculate the phi_o\n fields = np.dstack(fields)\n line_selector = LineSelector(im)\n op1, op2 = line_selector.points\n phi_o = np.mean(\n fields[op1[1] // ls:op2[1] // ls, op1[0] // ls:op2[0] // ls, :])\n\n # Repeat for disordered\n line_selector = LineSelector(im)\n dp1, dp2 = line_selector.points\n phi_d = np.mean(\n fields[dp1[1] // ls:dp2[1] // ls, dp1[0] // ls:dp2[0] // ls, :])\n\n field_threshold = (phi_o + phi_d) / 2\n return field_threshold\n\n\nclass LineSelector:\n def __init__(self, im):\n cv2.namedWindow('line', cv2.WINDOW_NORMAL)\n cv2.resizeWindow('line', 960, 540)\n cv2.setMouseCallback('line', self.record)\n self.points = []\n while True:\n cv2.imshow('line', im)\n key = cv2.waitKey(1) & 0xFF\n if len(self.points) == 2:\n break\n cv2.destroyAllWindows()\n\n def record(self, event, x, y, flags, param):\n if event == cv2.EVENT_LBUTTONDOWN:\n self.points.append([x, y])\n\n\ndef find_contours(f, t):\n t_low = t - 0.02 * t\n t_high = t + 0.02 * 5\n new_f = (f < t_high) * (f > t_low)\n new_f = np.uint8(new_f)\n contours = images.find_contours(new_f)\n contours = images.sort_contours(contours)\n return contours[-1]\n\n\ndef get_angle(im):\n ls = LineSelector(im)\n p1, p2 = ls.points\n m = (p2[1] - p1[1]) / (p2[0] - p1[0])\n a = -atan(m)\n c = np.array([i // 2 for i in np.shape(im)])[::-1]\n return a, c, p1, p2\n\n\ndef rotate_points(points, center, a):\n rot = np.array(((cos(a), -sin(a)), (sin(a), cos(a))))\n a1 = points - center\n a2 = rot @ a1.T\n a3 = a2.T + center\n return a3\n\n\ndef get_h(contour, shape, xmin, xmax, h):\n xs = []\n ys = []\n im = np.zeros((shape[0] * 2, shape[1] * 2))\n im = cv2.polylines(im, [contour.astype('int32')], True, (255, 255, 255))\n im = images.dilate(im, (3, 3))\n for x in np.arange(xmin, xmax):\n crossings = np.argwhere(im[:, x] == 255)\n dists = crossings - h\n closest = np.argmin((crossings - h) ** 2)\n crossing = crossings[closest]\n ys.append(crossing[0])\n xs.append(x)\n hs = np.array([y - h for y in ys])\n return hs\n\n\ndef get_fourier(hs, L):\n sp = [np.fft.fft(h) for h in hs]\n N = len(hs[0])\n freq = np.fft.fftfreq(N)\n\n y = np.stack(sp)\n y = np.mean(y, axis=0).squeeze()\n\n xplot = freq[1:N // 2]\n yplot = L * np.abs(y[1:N // 2]) ** 2\n return xplot, yplot\n\n\ndef plot(k, y):\n p, cov = np.polyfit(np.log(k), np.log(y), 1, cov=True)\n p1 = np.poly1d(p)\n\n # Plot the results\n plt.figure()\n plt.plot(np.log(k), np.log(y))\n plt.plot(np.log(k), p1(np.log(k)))\n plt.legend(\n ['Data',\n 'Fit with gradient ${:.2f} \\pm {:.2f}$'.format(p[0],\n cov[0][0] ** 0.5)])\n plt.xlabel('log($k [$mm$^{-1}]$)')\n plt.ylabel('$log( < |\\delta h_k|^2 > L [$mm$^3] $)')\n\n\n plt.figure()\n plt.loglog(k, yplot, '.')\n plt.loglog(k, np.exp(p1(np.log(k))))\n plt.legend(['Data', 'Fit'])\n plt.xlabel('$k$ [mm$^{-1}$]')\n plt.ylabel(r'$\\langle \\left| \\delta h_k \\right|^2L$ [mm$^3$]')\n\n\nif __name__ == \"__main__\":\n direc = filedialogs.open_directory()\n k, yplot = run(direc, 5)\n plot(k, yplot)\n # Calculate the best fit line for the fourier\n","sub_path":"first_order/interface/old_capillary_fluctuations.py","file_name":"old_capillary_fluctuations.py","file_ext":"py","file_size_in_byte":7289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69873806","text":"#!/usr/bin/python\n# -*- coding:utf-8 -*- \nimport unittest\nfrom devicewrapper.android import device as d\n\nclass CameraTest(unittest.TestCase):\n def setUp(self):\n super(CameraTest, self).setUp()\n d.wakeup()\n #d.start_activity(action='android.intent.action.DIAL', data='tel:13581739891', flags=0x04000000)\n d.press('back')\n d.press('back')\n d.press('back')\n d.press('home')\n\n def tearDown(self):\n super(CameraTest, self).tearDown()\n d.press('back')\n d.press('back')\n d.press('back')\n d.press('home')\n\n def testTakePicture(self):\n assert d.exists(text='Camera') , 'camera app not appear on home screen'\n #assert d.exists(text='Apps')\n d(text='Camera').click.wait()\n d(description='Shutter button').click.wait()\n d(description='Most recent photo').click.wait()\n assert d(text=\"Delete\").wait.exists(timeout=3000), 'unable to take picture'\n d(text=\"Delete\").click.wait()\n d(text=\"OK\").click.wait()\n assert d(description=\"Shutter button\").wait.exists(timeout=5000), 'unable to delete picture!'\n\n \n \n\n\n","sub_path":"testcases/scripts/testcases/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"240800205","text":"import gzip\nimport re\nimport http.cookiejar\nimport urllib.request\nimport urllib\nimport os\n\n\ndef ungzip(data):\n try: # 尝试解压\n print('正在解压.....')\n data = gzip.decompress(data)\n print('解压完毕!')\n except:\n print('未经压缩, 无需解压')\n return data\n\n\n\ndef getOpener(head={\n 'Connection': 'Keep-Alive',\n 'Accept': 'text/html, application/xhtml+xml, */*',\n 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'\n}):\n cj = http.cookiejar.CookieJar()\n opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))\n header = []\n for key, value in head.items():\n elem = (key, value)\n header.append(elem)\n opener.addheaders = header\n return opener\n\n\nheader = {\n 'Connection': 'Keep-Alive',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',\n 'Accept-Encoding': 'gzip, deflate, sdch, br',\n 'Host': 'www.eloancn.com',\n 'DNT': '1'\n}\n\ndef saveFile(data,path):\n save_path = path\n f_obj = open(save_path, 'wb') # w 表示打开方式\n #f_obj.mkdir()\n f_obj.write(data)\n f_obj.close()\n\n\n\n\nfrom collections import deque\n\nqueue = deque()\nvisited = set()\n\nurl = 'http://bbs.eloancn.com' # 入口页面, 可以换成别的\n\nqueue.append(url)\ncount = 0\n\nwhile queue:\n url = queue.popleft() # 队首元素出队\n visited |= {url} # 标记为已访问\n\n print('已经抓取: ' + str(count) + ' 正在抓取 <--- ' + url)\n count += 1\n try:\n oper = getOpener()\n uop = oper.open(url, timeout=3000)\n #data = uop.read().decode()\n # data = op.read()\n #urlop = ungzip(data) # 解压\n\n\n #urlop = urllib.request.urlopen(url)\n #urlop = op;\n if 'html' not in uop.getheader('Content-Type'):\n continue\n\n # 避免程序异常中止, 用try..catch处理异常\n\n #data = op.read().decode('utf-8')\n #data = op.read()\n data = uop.read()\n dedata = data.decode()\n path = 'D:\\\\python\\\\yld\\\\'+str(count)+'.html'\n #os.mkdir(path);\n print(data)\n saveFile(data,path)\n # print(data.decode())\n #data = ungzip(data)\n except Exception as err:\n print(err)\n continue\n\n # 正则表达式提取页面中所有队列, 并判断是否已经访问过, 然后加入待爬队列\n linkre = re.compile('href=\\\"(.+?)\\\"')\n for x in linkre.findall(dedata):\n if 'http' in x and x not in visited and 'eloancn' in x:\n # print('php地址-->'+'http://bbs.eloancn.com/'+x)\n queue.append(x)\n print('加入队列 ---> ' + x)","sub_path":"com/eloancn/yld.py","file_name":"yld.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"60400082","text":"# python translation of applyController.m\n# to override the matlab dynamic cart pole solver and use the one from OpenAI gym\n#################################################################\n## applyController.m\n# *Summary:* Script to apply the learned controller to a (simulated) system\n#\n## High-Level Steps\n# # Generate a single trajectory rollout by applying the controller\n# # Generate many rollouts for testing the performance of the controller\n# # Save the data\n\nimport roll_cp as roll #python version of rollout.m\n\ndef visualize_cost(matlab):\n if matlab.workspace.plotting.verbosity>0 : \n if ~matlab.workspace.ishandle(3):\n matlab.eval('figure(3)')\n else:\n matlab.eval(\"set(0,'CurrentFigure',3)\")\n matlab.eval(\"hold on\")\n matlab.eval(\"plot(1:length(realCost{J+j}),realCost{J+j},'r');\") \n matlab.eval(\"drawnow\")\n # if plotting.verbosity > 0\n # if ~ishandle(3); figure(3); else set(0,'CurrentFigure',3); end\n # hold on; plot(1:length(realCost{J+j}),realCost{J+j},'r'); drawnow;\n # end\n\n\ndef apply(matlab):\n # 1. Generate trajectory rollout given the current policy\n # if isfield(plant,'constraint'), HH = maxH; else HH = H; end\n matlab.eval(\"if isfield(plant,'constraint'), HH = maxH; else HH = H; end\")\n # if matlab.eval(\"isfield(plant,'constraint')\"):\n # matlab.eval(\"HH = maxH;\")\n # else:\n # matlab.eval(\"HH = H;\")\n \n # =================================== ROLLOUT\n # [xx, yy, realCost{j+J}, latent{j}] = rollout(gaussian(mu0, S0), policy, HH, plant, cost); # As follows:\n matlab.eval(\"start_py = gaussian(mu0, S0)\") #BEGINNING OF WORKAROUND for rollout function\n matlab.eval(\"policy_py = policy\")\n matlab.eval(\"H_py = HH\")\n matlab.eval(\"plant_py = plant\")\n matlab.eval(\"cost_py = cost\")\n roll.rollout(matlab) # FUNCTION ====\n matlab.workspace.xx = matlab.workspace.x_py\n matlab.workspace.yy = matlab.workspace.y_py\n matlab.eval(\"realCost{j+J} = L_py;\")\n matlab.eval(\"latent{j} = latent_py;\")\n matlab.eval(\"clear x_py\") \n matlab.eval(\"clear y_py\")\n matlab.eval(\"clear L_py\")\n matlab.eval(\"clear latent_py\") #END OF WORKAROUND \n # ===================================\n print(matlab.workspace.xx) # disp(xx); # display states of observed trajectory\n matlab.eval(\"x = [x; xx]; y = [y; yy];\") # augment training sets \n visualize_cost(matlab)\n # if plotting.verbosity > 0\n # if ~ishandle(3); figure(3); else set(0,'CurrentFigure',3); end\n # hold on; plot(1:length(realCost{J+j}),realCost{J+j},'r'); drawnow;\n # end\n\n # # 2. Make many rollouts to test the controller quality\n if matlab.workspace.plotting.verbosity>1 : \n matlab.eval(\"lat = cell(1,10);\")\n for i in range(1,10+1):\n matlab.workspace.i = i\n # =================================== ROLLOUT\n # [~,~,~,lat{i}] = rollout(gaussian(mu0, S0), policy, HH, plant, cost); # As follows:\n matlab.eval(\"start_py = gaussian(mu0, S0)\") #BEGINNING OF WORKAROUND for rollout function\n matlab.eval(\"policy_py = policy\")\n matlab.eval(\"H_py = HH\")\n matlab.eval(\"plant_py = plant\")\n matlab.eval(\"cost_py = cost\")\n roll.rollout(matlab) # FUNCTION ====\n matlab.eval(\"lat{i} = latent_py;\")\n matlab.eval(\"clear x_py\") \n matlab.eval(\"clear y_py\")\n matlab.eval(\"clear L_py\")\n matlab.eval(\"clear latent_py\") #END OF WORKAROUND \n # ===================================\n if ~matlab.workspace.ishandle(4):\n matlab.eval('figure(4)')\n else:\n matlab.eval(\"set(0,'CurrentFigure',4)\")\n matlab.eval(\"clf(4)\")\n\n matlab.eval(\"ldyno = length(dyno);\")\n for i in range(1,matlab.workspace.ldyno.astype(int)+1): #for i=1:ldyno # plot the rollouts on top of predicted error bars\n matlab.workspace.i = i\n matlab.eval(\"subplot(ceil(ldyno/sqrt(ldyno)),ceil(sqrt(ldyno)),i); hold on;\")\n matlab.eval(\"errorbar( 0:length(M{j}(i,:))-1, M{j}(i,:), 2*sqrt(squeeze(Sigma{j}(i,i,:))) );\")\n for ii in range (1,10+1): # for ii=1:10\n matlab.workspace.ii = ii\n matlab.eval(\"plot( 0:size(lat{ii}(:,dyno(i)),1)-1, lat{ii}(:,dyno(i)), 'r' );\")\n matlab.eval(\"plot( 0:size(latent{j}(:,dyno(i)),1)-1, latent{j}(:,dyno(i)),'g');\")\n matlab.eval(\"axis tight\")\n matlab.eval(\"drawnow;\")\n\n # # 3. Save data\n matlab.eval(\"filename = [basename num2str(j) '_H' num2str(H)]; save(filename);\")\n","sub_path":"pilco-matlab/scenarios/cartPole_dynamicFromOpenAIgym/applyController_cp.py","file_name":"applyController_cp.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"72754232","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport datetime\r\nimport mysql.connector\r\nimport time\r\nstart=time.time()\r\ndatabase_name='big'\r\ntable_name='matches'\r\nmydb = mysql.connector.connect(host=\"localhost\", user=\"root\", password=\"1234\", database=database_name,\r\n auth_plugin='mysql_native_password')\r\n\r\ndef delete_duplicates():\r\n global mycursor,mydb,table_name\r\n mycursor.execute(\"Select * from \"+table_name+\" group by teams having count(*)>1\")\r\n result = mycursor.fetchall()\r\n # print(result)\r\n if len(result)>0:\r\n print(\"deleting the following duplicates \")\r\n for idm in result:\r\n mycursor.execute(\"DELETE FROM \"+table_name+\" WHERE id=\"+str(idm[0]))\r\n print(idm)\r\n f.write(\"Duplicate found: \"+str(idm)+'\\n')\r\n mydb.commit()\r\n else:\r\n print(\"no duplicates\")\r\n\r\ndef insert_oneteam(team):\r\n global url_dict, f, mycursor,mydb\r\n resp = requests.get(url_dict.get(team))\r\n soup = BeautifulSoup(resp.text, 'html.parser')\r\n\r\n home = soup.find_all('span', class_='matches__item-col matches__participant matches__participant--side1')\r\n away = soup.find_all('span', class_='matches__item-col matches__participant matches__participant--side2')\r\n time = soup.find_all('span', class_='matches__date')\r\n date = soup.find_all('h4', class_='fixres__header2')\r\n if len(date)>0:\r\n for ho, aw, tim, dt in zip(home, away, time, date):\r\n s = dt.text.strip().split(\" \")\r\n if len(s[1]) == 4: # 1st or 22nd\r\n day = s[1][:2]\r\n else:\r\n day = s[1][:1]\r\n mnth = calendar.get(s[2]) # month\r\n curr_time = datetime.date.today()\r\n match_date = datetime.date(curr_time.year, mnth, int(day))\r\n team = ho.text.strip() + \" vs \" + aw.text.strip()\r\n rs = str(int(tim.text.strip()[:2])+2)+tim.text.strip()[2:] # RO Time\r\n match = str(match_date) + \" \" + rs + \" \" + team\r\n f.write(match + '\\n')\r\n mycursor.execute(\"INSERT INTO \"+table_name+\"(date, time, teams) VALUES(%s,%s,%s)\",\r\n (match_date, rs, team))\r\n else:\r\n print(teamName +\" doesn't have matches scheduled\")\r\n mydb.commit()\r\n\r\n# You can add more teams but make sure u put their fixtures link from skysports in the dictionary\r\nurl_dict = {\r\n 'Barcelona': 'https://www.skysports.com/barcelona-fixtures',\r\n 'Bayern': 'https://www.skysports.com/bayern-munich-fixtures',\r\n 'Juventus': \"https://www.skysports.com/juventus-fixtures\",\r\n \"Manchester City\": \"https://www.skysports.com/manchester-city-fixtures\",\r\n \"Liverpool\": \"https://www.skysports.com/liverpool-fixtures\",\r\n \"Real Madrid\":'https://www.skysports.com/real-madrid-fixtures'\r\n}\r\ncalendar = {\"January\": 1,\r\n \"February\": 2,\r\n \"March\": 3,\r\n \"April\": 4,\r\n \"May\": 5,\r\n \"June\": 6,\r\n \"July\": 7,\r\n \"August\": 8,\r\n \"September\": 9,\r\n \"October\": 10,\r\n \"November\": 11,\r\n \"December\": 12\r\n }\r\n\r\n\r\nmycursor = mydb.cursor()\r\nf = open(\"RaportInsert.txt\", 'a+t')\r\nif __name__ == \"__main__\":\r\n # stuff only to run when not called via 'import' here\r\n f.write(\"\\n\")\r\n\r\n for teamName in url_dict.keys():\r\n insert_oneteam(teamName)\r\n f.write(\"\\n\")\r\n delete_duplicates()\r\n f.write(\"----------------------------------------------------\\n\")\r\n f.write(\"IT MAY CONTAIN DUPLICATES HERE BUT NOT IN THE DB \"+\"raport updated on \" + str(datetime.datetime.now()))\r\n mydb.close()\r\n\r\n print(\"It took \",time.time()-start,\" seconds \")\r\n f.close()\r\n exit()\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"351281018","text":"\"\"\"\nFor CommonsCloud copyright information please see the LICENSE document\n(the \"License\") included with this software package. This file may not\nbe used in any manner except in compliance with the License\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\"\"\"\nFor CommonsCloud copyright information please see the LICENSE document\n(the \"License\") included with this software package. This file may not\nbe used in any manner except in compliance with the License\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\n\"\"\"\nImport Python Dependencies\n\"\"\"\nimport re\nimport uuid\nimport datetime\n\nfrom collections import OrderedDict\n\nfrom migrate.changeset import *\nfrom sqlalchemy import MetaData\n\n\"\"\"\nImport Flask Dependencies\n\"\"\"\nfrom flask import abort\nfrom flask import request\n\nimport json\n\nfrom geoalchemy2.types import Geometry\n\nfrom sqlalchemy.orm import ColumnProperty\n\nfrom flask.ext.restless.helpers import to_dict\n\n\"\"\"\nImport Commons Cloud Dependencies\n\"\"\"\nfrom CommonsCloudAPI.extensions import db\nfrom CommonsCloudAPI.extensions import logger\nfrom CommonsCloudAPI.extensions import status as status_\n\nfrom CommonsCloudAPI.format.format_csv import CSV\nfrom CommonsCloudAPI.format.format_geojson import GeoJSON\nfrom CommonsCloudAPI.format.format_json import JSON\n\nfrom geoalchemy2.elements import WKBElement\nimport geoalchemy2.functions as func\n\n\nclass CommonsModel(object):\n\n __public__ = {}\n __public_relationships__ = None\n\n def __init__(self):\n pass\n\n \"\"\"\n In order to be able to work with an object it needs to be serialized,\n otherwise we can turn it into any type of file\n\n @requires\n from collections import OrderedDict\n\n @param (object) self\n The object we are acting on behalf of\n\n @return (dict) result\n A dictionary of the contents of our objects\n\n \"\"\"\n def serialize_object(self, object_, single=False):\n\n result = OrderedDict()\n\n if hasattr(object_, '__mapper__'):\n for key in object_.__mapper__.c.keys():\n value = getattr(object_, key)\n if key in self.__public__['default']:\n result[key] = self.serialize_field(key, value)\n elif single is True:\n result[key] = self.serialize_field(key, value)\n elif hasattr(object_, 'keys'):\n for key in object_.keys():\n value = object_.get(key, None)\n if key in self.__public__['default']:\n result[key] = self.serialize_field(key, value)\n elif single is True:\n result[key] = self.serialize_field(key, value)\n else:\n logger.error('Could not serialize object')\n\n\n return result\n\n\n \"\"\"\n Serializing fields properly is extremely important if the content will be passed\n off to another service within the API such as the GeoJSON, JSON, or CSV formatter.\n \"\"\"\n def serialize_field(self, key, value):\n\n if 'geometry' in key and isinstance(value, WKBElement):\n if db.session is not None:\n geojson = str(db.session.scalar(func.ST_AsGeoJSON(value))) # To change precision of the geometry add a numeric value after the `value` variable\n return json.loads(geojson)\n elif 'geometry' in key and isinstance(value, dict):\n return value\n elif 'geometry' in key and isinstance(value, str):\n return json.loads(value)\n elif isinstance(value, datetime.date):\n return value.isoformat()\n elif isinstance(value, int) or isinstance(value, float) or isinstance(value, str) or isinstance(value, unicode):\n return value\n elif value is None:\n return None\n elif isinstance(value, list):\n return self.serialize_list(value)\n else:\n pass\n\n \"\"\"\n In order to be able to work with an object it needs to be serialized,\n otherwise we can turn it into any type of file\n\n @requires\n from collections import OrderedDict\n\n @param (object) self\n The object we are acting on behalf of\n\n @return (dict) result\n A dictionary of the contents of our objects\n\n \"\"\"\n def serialize_list(self, _content):\n\n list_ = []\n\n for object_ in _content:\n\n result = self.serialize_object(object_)\n\n list_.append(result)\n\n return list_\n\n \"\"\"\n Remove all characters except for spaces and alpha-numeric characters,\n replace all spaces in a string with underscores, change all uppercase\n letters to lowercase letters, and return the updated string.\n \"\"\"\n def generate_machine_name(self, human_name):\n machine_name = re.sub('[^A-Za-z0-9_]+', '', human_name.replace(' ','_').lower())\n return machine_name\n\n\n \"\"\"\n This function simply creates a machine readable name with an optional\n prefix and/or suffix\n \"\"\"\n def generate_template_hash(self, _prefix='type_', _suffix=''):\n\n unique_collection = str(uuid.uuid4()).replace('-', '')\n collection_string = _prefix + unique_collection + _suffix\n\n return collection_string\n\n\n \"\"\"\n Generate a PostgreSQL data type based off of a list of known strings. The\n reason we do this is to abstract away some details from the user making it\n easier for them to create new fields\n\n @param (object) field\n A fully qualified Field object\n \"\"\"\n def generate_field_type(self, field, template):\n\n fields = {\n \"float\": db.Float(),\n \"whole_number\": db.Integer(),\n \"text\": db.String(255),\n \"email\": db.String(255),\n \"phone\": db.String(255),\n \"url\": db.String(255),\n \"textarea\": db.Text(),\n \"boolean\": db.Boolean(),\n \"date\": db.Date(),\n \"time\": db.Time(),\n \"list\": db.String(255)\n }\n\n if field.data_type == 'relationship':\n return self.generate_relationship_field(field, template)\n elif field.data_type == 'file':\n return self.generate_attachment_field(field, template)\n\n return fields[field.data_type]\n\n def generate_relationship_field(self, field, template):\n\n \"\"\"\n Make sure that the table we need to use for creating the relationship is loaded\n into our db.metadata, otherwise the whole process will fail\n \"\"\"\n existing_table = db.Table(field.relationship, db.metadata, autoload=True, autoload_with=db.engine)\n\n \"\"\"\n Create a name for our new field relationship table\n \"\"\"\n table_name = self.generate_template_hash(_prefix='ref_')\n\n \"\"\"\n Create a new Association Table in our database, based up the two existing Tables\n we've previously created\n \"\"\"\n parent_foreign_key_id = ('%s.%s') % (template.storage,'id')\n child_foreign_key_id = ('%s.%s') % (field.relationship,'id')\n\n new_table = db.Table(table_name, db.metadata,\n db.Column('parent_id', db.Integer, db.ForeignKey(parent_foreign_key_id), primary_key=True),\n db.Column('child_id', db.Integer, db.ForeignKey(child_foreign_key_id), primary_key=True)\n )\n\n db.metadata.bind = db.engine\n\n \"\"\"\n Make sure everything commits to the database\n \"\"\"\n db.create_all()\n\n return {\n 'type': 'relationship',\n 'association': table_name,\n 'relationship': field.relationship\n }\n\n def generate_attachment_field(self, field, template):\n\n \"\"\"\n Before we can create a relationship between Attachments and a Template\n we need to create a Table in the database to retain our attachments\n \"\"\"\n attachment_table_name = self.generate_template_hash(_prefix='attachment_')\n\n new_table = db.Table(attachment_table_name, db.metadata,\n db.Column('id', db.Integer, primary_key=True),\n db.Column('caption', db.String(255)),\n db.Column('credit', db.String(255)),\n db.Column('credit_link', db.String(255)),\n db.Column('filename', db.String(255)),\n db.Column('filepath', db.String(255)),\n db.Column('filetype', db.String(255)),\n db.Column('filesize', db.Integer()),\n db.Column('created', db.DateTime()),\n db.Column('status', db.String(24), nullable=False)\n )\n\n db.metadata.bind = db.engine\n\n db.create_all()\n\n \"\"\"\n Next we update the relationship field\n \"\"\"\n field.relationship = attachment_table_name\n\n\n \"\"\"\n Finally we can create the actual relationship\n \"\"\"\n relationship_ = self.generate_relationship_field(field, template)\n\n return {\n 'type': 'file',\n 'association': relationship_['association'],\n 'relationship': attachment_table_name\n }\n\n \"\"\"\n Storage name\n \"\"\"\n def validate_storage(self, storage_name):\n\n if storage_name.startswith('attachment_') or storage_name.startswith('type_'):\n return storage_name\n\n return str('type_' + storage_name)\n\n\n \"\"\"\n Create a table in the database that contains a base line of defaults\n \"\"\"\n def create_storage(self, table_name=\"\"):\n\n if not table_name:\n table_name = self.generate_template_hash()\n\n\n \"\"\"\n Why are we closing the session, what gives?\n\n http://docs.sqlalchemy.org/en/rel_0_9/faq.html#my-program-is-hanging-when-i-say-table-drop-metadata-drop-all\n\n \"\"\"\n # db.session.close()\n\n\n \"\"\"\n Create a new custom table for a Feature Type\n \"\"\"\n new_table = db.Table(table_name, db.metadata,\n db.Column('id', db.Integer(), primary_key=True),\n db.Column('created', db.DateTime(), default=datetime.datetime.now()),\n db.Column('updated', db.DateTime(), default=datetime.datetime.now()),\n db.Column('geometry', Geometry('GEOMETRY'), nullable=True),\n db.Column('status', db.String(24), nullable=False)\n )\n\n\n \"\"\"\n Make sure everything commits to the database\n \"\"\"\n db.create_all()\n\n return table_name\n\n\n \"\"\"\n Create a table in the database that contains a base line of defaults\n \"\"\"\n def create_storage_permissions(self, table_name):\n\n \"\"\"\n Take the existing table name and append the '_users' extension to it\n \"\"\"\n users_table_name = table_name + '_users'\n\n \"\"\"\n \"\"\"\n feature_id = table_name + '.id'\n\n \"\"\"\n Create a new custom table for a Feature Type\n \"\"\"\n new_table = db.Table(users_table_name, db.metadata,\n db.Column('user_id', db.Integer(), db.ForeignKey('user.id'), primary_key=True),\n db.Column('feature_id', db.Integer(), db.ForeignKey(feature_id), primary_key=True),\n db.Column('read', db.Boolean()),\n db.Column('write', db.Boolean()),\n db.Column('is_admin', db.Boolean())\n )\n\n \"\"\"\n Make sure everything commits to the database\n \"\"\"\n db.create_all()\n\n return users_table_name\n\n\n \"\"\"\n Create a table in the database that contains a base line of defaults\n\n @param (object) template\n A fully qualified Template object\n\n @param (object) field\n A fully qualfied Field object\n\n @see Documentation on the db.Column.create() functionality\n https://sqlalchemy-migrate.readthedocs.org/en/latest/changeset.html#column-create\n \"\"\"\n def create_storage_field(self, template, field):\n\n if not template.storage or not hasattr(field, 'data_type'):\n return abort(404)\n\n \"\"\"\n Create a new custom table for a Feature Type\n \"\"\"\n existing_table = db.Table(template.storage, db.metadata, autoload=True, autoload_with=db.engine)\n\n \"\"\"\n We must bind the engine to the metadata here in order for our fields to\n recognize the existing Table we have loaded in the following steps\n \"\"\"\n db.metadata.bind = db.engine\n\n \"\"\"\n Retrieve the appropriate field data type that we'll be using to create the\n field in our database table\n \"\"\"\n field_type = self.generate_field_type(field, template)\n\n if field.data_type == 'relationship':\n return field_type\n\n if field.data_type == 'file':\n return field_type\n\n \"\"\"\n Create the new column just like we would if we were hard coding the model\n \"\"\"\n new_column = db.Column(field.name, field_type)\n new_column.create(existing_table)\n\n \"\"\"\n Finally we need to make sure that the existing table knows that we've have\n just added a new column, otherwise we won't be able to use it until we\n restart the application, which would be very bad\n \"\"\"\n assert new_column is existing_table.c[field.name]\n\n\n # \"\"\"\n # We must bind the engine to the metadata here in order for our fields to\n # recognize the existing Table we have loaded in the following steps\n # \"\"\"\n # db.metadata.bind = db.engine\n\n # \"\"\"\n # Create a new custom table for a Feature Type\n # \"\"\"\n # existing_table = db.Table(template.storage, db.metadata, autoload=True, autoload_with=db.engine)\n\n return new_column\n\n\n def create_owner_field(self, template):\n\n if not template.storage:\n return abort(404)\n\n \"\"\"\n Create a new custom table for a Feature Type\n \"\"\"\n existing_table = db.Table(template.storage, db.metadata, autoload=True, autoload_with=db.engine)\n\n \"\"\"\n We must bind the engine to the metadata here in order for our fields to\n recognize the existing Table we have loaded in the following steps\n \"\"\"\n db.metadata.bind = db.engine\n\n \"\"\"\n Create the new column just like we would if we were hard coding the model\n \"\"\"\n new_column = db.Column('owner', db.Integer, db.ForeignKey('user.id'))\n new_column.create(existing_table)\n\n \"\"\"\n Finally we need to make sure that the existing table knows that we've have\n just added a new column, otherwise we won't be able to use it until we\n restart the application, which would be very bad\n \"\"\"\n assert new_column is existing_table.c['owner']\n\n return new_column\n\n def get_storage(self, template, fields=[], is_relationship=False, relationship=True):\n\n if type(template) is str:\n class_name = str(template)\n relationships = []\n else:\n class_name = str(template.storage)\n\n \"\"\"\n Check to see if we need to load the full model or a slim model.\n\n A full model includes all relationships, a slim model only includes\n first level field and excludes all attachments and relationships.\n \"\"\"\n if relationship:\n relationships = self.get_relationship_fields(template.fields)\n else:\n relationships = []\n\n logger.debug('Dynamic Model executed for %s', class_name)\n\n arguments = {\n \"class_name\": class_name,\n \"relationships\": relationships\n }\n\n class_arguments = self.get_class_arguments(**arguments)\n\n Model = type(class_name, (db.Model,), class_arguments)\n\n\n \"\"\"\n For the API to return items properly, we should check to see if the fields\n we are attempting to call are marked as listed or not.\n \"\"\"\n if fields or hasattr(template, 'fields'):\n\n if is_relationship:\n public_fields = ['id', 'name', 'created', 'updated', 'status', 'filename', 'filepath', 'caption', 'credit', 'credit_link']\n else:\n public_fields = ['id', 'name', 'created', 'updated', 'geometry', 'status', 'filename', 'filepath', 'caption', 'credit', 'credit_link']\n\n for field in fields:\n if field.is_listed and field.data_type == 'relationship':\n public_fields.append(field.relationship)\n elif field.is_listed and field.data_type == 'file':\n public_fields.append(field.relationship)\n elif field.is_listed:\n public_fields.append(field.name)\n\n # Remove all duplicate names before passing along to public fields\n # self.__public__ = list(set(public_fields))\n self.__public__['default'] = public_fields\n\n return Model\n\n\n \"\"\"\n Create a dictionary of Class Arguments to assist\n us in building reliable SQLAlchemy models capable\n of handling many-to-many relationships.\n \"\"\"\n def get_class_arguments(self, class_name, relationships):\n\n \"\"\"\n Start an empty object to store all of our Class Arguments\n \"\"\"\n class_arguments = {}\n\n\n \"\"\"\n Automatically load all of our basic table fields and other\n meta information\n \"\"\"\n class_arguments['__table__'] = db.Table(class_name, db.metadata, autoload=True, autoload_with=db.engine)\n class_arguments['__tablename__'] = class_name\n class_arguments['__table_args__'] = {\n \"extend_existing\": True\n }\n\n\n \"\"\"\n Unfortunately we have to manually load the relationships that\n our models need to work properly.\n\n To build relationships out properly we need a few things:\n\n 'type_5740f6daa55f4fc790e7eeacb96d726e' : db.relationship('type_5740f6daa55f4fc790e7eeacb96d726e', secondary=our_reference_table, backref=db.backref(class_name))\n\n 1. We need the name of the association table (e.g., ref_XXXXXXXXXXXXXXXXXXXXX)\n 2. We need the name of the other table that actually contains the content to\n be referenced (e.g., type_XXXXXXXXXXXXXXXXXXX)\n 3. We should have a model class for the association table\n 4. We need the name of the class or 'storage' of the Class being acted on\n\n \"\"\"\n relationship_message = 'No relationships'\n \n if relationships:\n relationship_message = 'Relationships found'\n for relationship in relationships:\n\n logger.debug('Adding relationship %s (%s) to model', relationship.name, relationship.relationship)\n\n table_name = str(relationship.relationship)\n\n RelationshipModel = self.get_storage(table_name, is_relationship=True)\n\n\n \"\"\"\n Setup our association table for each relationship that we have\n in our fields list\n \"\"\"\n parent_id_key = str(class_name) + '.id'\n child_id_key = table_name + '.id'\n\n association_table = db.Table(str(relationship.association), db.metadata,\n db.Column('parent_id', db.Integer, db.ForeignKey(parent_id_key), primary_key=True),\n db.Column('child_id', db.Integer, db.ForeignKey(child_id_key), primary_key=True),\n extend_existing = True,\n autoload = True,\n autoload_with = db.engine\n )\n\n class_arguments[table_name] = db.relationship(RelationshipModel, secondary=association_table, cascade=\"\", backref=class_name)\n \n logger.debug('Relationships > %s', relationship_message)\n\n return class_arguments\n\n\n \"\"\"\n Create a list of fields that need to have relationships loaded\n for them to operate properly\n \"\"\"\n def get_relationship_fields(self, fields):\n\n relationships = []\n\n for field in fields:\n if 'relationship' in field.data_type or 'file' in field.data_type:\n relationships.append(field)\n\n return relationships\n\n\n \"\"\"\n Delete a column from a table in the database\n\n @param (object) field\n A fully qualfied Field object\n\n @see Documentation on the db.Column.drop() functionality\n https://sqlalchemy-migrate.readthedocs.org/en/latest/api.html \\\n #migrate.changeset.schema.ChangesetColumn.drop\n\n Documentation on selecting the existing column\n http://docs.sqlalchemy.org/en/rel_0_8/orm/mapper_config.html \\\n #naming-columns-distinctly-from-attribute-names\n \"\"\"\n def delete_storage_field(self, template, field):\n\n \"\"\"\n Create a new custom table for a Feature Type\n \"\"\"\n existing_table = db.Table(template.storage, db.metadata, autoload=True, autoload_with=db.engine)\n\n \"\"\"\n We must bind the engine to the metadata here in order for our fields to\n recognize the existing Table we have loaded in the following steps\n \"\"\"\n db.metadata.bind = db.engine\n\n \"\"\"\n Delete the column just like we would if we were hard coding the model\n \"\"\"\n if not field.data_type is 'relationship' or not field.data_type is 'file':\n existing_table.c[field.name].drop()\n\n # existing_table = db.Table(template.storage, MetaData(db.engine), autoload=True, autoload_with=db.engine)\n # db.metadata.bind = db.engine\n\n # db.engine.execute('ALTER TABLE %s DROP COLUMN %s' % (template.storage, field.name))\n db.session.close()\n db.engine.connect()\n\n return True\n\n\n \"\"\"\n Create a valid response to be served to the user\n\n @param (object) self\n\n @param (object)/(list) the_content\n A list of templates or a single template object to be delivered\n\n @param (str) list_name\n If the `the_content` is really a list then we should give int\n a name for the list to be keyed as in the returned JSON object\n\n @return (object)\n An JSON object either contianing the formatted content or an error\n message describing why the content couldn't be delivered\n\n \"\"\"\n def endpoint_response(self, the_content, extension='json', list_name='', exclude_fields=[], code=200, last_modified=\"\", **extras):\n\n \"\"\"\n Make sure the content is ready to be served\n \"\"\"\n if type(the_content) is list:\n the_content = {\n list_name: self.serialize_list(the_content)\n }\n else:\n the_content = self.serialize_object(the_content, single=True)\n\n \"\"\"\n If the user is properly authenticated, then proceed to see if they\n have requests a type of content we serve\n \"\"\"\n if (extension == 'json'):\n\n this_data = JSON(the_content, list_name=list_name, exclude_fields=exclude_fields, **extras)\n return this_data.create(), code\n\n elif (extension == 'geojson'):\n\n this_data = GeoJSON(the_content, list_name=list_name, exclude_fields=exclude_fields, **extras)\n return this_data.create(), code\n\n elif (extension == 'csv'):\n\n this_data = CSV(the_content, exclude_fields=exclude_fields)\n return this_data.create(), code\n\n \"\"\"\n If the user hasn't requested a specific content type then we should\n tell them that, by directing them to an \"Unsupported Media Type\"\n \"\"\"\n return status_.status_415(), 415\n\n \"\"\"\n *********************************************************************\n *********************************************************************\n *********************************************************************\n *********************************************************************\n *********************************************************************\n\n THIS SECTION DEALS SPECIFICALLY WITH USER PERMISSIONS AS THEY APPLY\n TO OUR VARIOUS DATA MODELS\n\n *********************************************************************\n *********************************************************************\n *********************************************************************\n *********************************************************************\n *********************************************************************\n *********************************************************************\n \"\"\"\n\n \"\"\"\n Get a list of application ids from the current user and convert\n them into a list of numbers so that our SQLAlchemy query can\n understand what's going on\n\n @param (object) self\n\n @return (list) applications_\n A list of applciations the current user has access to\n \"\"\"\n def allowed_applications(self, permission_type='read'):\n\n applications_ = []\n\n if not hasattr(self.current_user, 'id'):\n logger.warning('User did\\'t submit their information %s', \\\n self.current_user)\n return status_.status_401('You need to be logged in to access applications'), 401\n\n for application in self.current_user.applications:\n if permission_type and getattr(application, permission_type):\n applications_.append(application.application_id)\n\n return applications_\n\n \"\"\"\n Get a list of template ids from the current user and convert\n them into a list of numbers so that our SQLAlchemy query can\n understand what's going on\n\n @param (object) self\n\n @return (list) templates_\n A list of templates the current user has access to\n \"\"\"\n def allowed_templates(self, permission_type='read'):\n\n templates_ = []\n\n if not hasattr(self.current_user, 'id'):\n logger.warning('User did\\'t submit their information %s', \\\n self.current_user)\n return status_.status_401('You need to be logged in to access applications'), 401\n\n for template in self.current_user.templates:\n if permission_type and getattr(template, permission_type):\n templates_.append(template.template_id)\n\n return templates_\n","sub_path":"CommonsCloudAPI/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":24258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"642949565","text":"# import sys\r\n# sys.path.append(\r\n# \"C:/Users/900226/Desktop/exercicios/atividade_dupla/Trabalho2/\")\r\n\r\nfrom flask import Flask, render_template, redirect, request\r\n\r\nfrom dao.listar import Listar\r\nfrom dao.dao_pessoas import Pessoa_db\r\nfrom dao.dao_linguagens import Linguagem_db\r\nfrom dao.dao_funcionarios import Funcionario_db\r\nfrom dao.dao_equipes import Equipe_db\r\n\r\nfrom model.pessoas import Pessoa\r\nfrom model.equipes import Equipe\r\nfrom model.linguagens import Linguagem\r\nfrom model.funcionarios import Funcionario\r\n\r\n\r\napp = Flask(__name__\r\n # , template_folder='../templates',\r\n # static_folder='../static'\r\n )\r\n\r\n\r\n# Rota de cadastro\r\n@app.route('/')\r\ndef home():\r\n return render_template('home.html')\r\n\r\n# Rota de listagem\r\n@app.route('/listagem')\r\ndef listagem():\r\n listar = Listar()\r\n lista_pessoa = listar.listar_pessoas()\r\n lista_funcionario = listar.listar_funcionarios()\r\n lista_equipe = listar.listar_equipes()\r\n lista_linguagem = listar.listar_linguagens()\r\n return render_template('listagem.html', pessoa=lista_pessoa, funcionario=lista_funcionario, equipe=lista_equipe, linguagem=lista_linguagem)\r\n\r\n# Rota que cadastra a pessoa\r\n@app.route('/salvar_pessoa')\r\ndef salvar_pessoa():\r\n pessoa = Pessoa_db()\r\n nome = request.args[\"nome\"]\r\n cpf = request.args[\"cpf\"]\r\n telefone = request.args[\"telefone\"]\r\n pessoa.set_cadastrar(nome, cpf, telefone)\r\n pessoa.cadastrar_db(pessoa.get_cadastrar())\r\n return redirect('/listagem')\r\n\r\n# Rota que cadastra o funcionário\r\n@app.route('/salvar_funcionario')\r\ndef salvar_funcionario():\r\n funcionario = Funcionario_db()\r\n idpessoal = request.args[\"id-pessoal\"]\r\n cargo = request.args[\"cargo\"]\r\n salario = request.args[\"salario\"]\r\n funcionario.set_cadastrar(cargo, salario, idpessoal)\r\n funcionario.cadastrar_db(funcionario.get_cadastrar())\r\n return redirect('/listagem')\r\n\r\n# Rota que cadastra a linguagem\r\n@app.route('/salvar_linguagem')\r\ndef salvar_linguagem():\r\n linguagem = Linguagem_db()\r\n nome = request.args[\"linguagem\"]\r\n linguagem.set_cadastrar(nome)\r\n linguagem.cadastrar_db(linguagem.get_cadastrar())\r\n return redirect('/listagem')\r\n\r\n# Rota que cadastra a equipe\r\n@app.route('/salvar_equipe')\r\ndef salvar_equipe():\r\n equipe = Equipe_db()\r\n funcionario1 = request.args[\"funcionario1\"]\r\n funcionario2 = request.args[\"funcionario2\"]\r\n funcionario3 = request.args[\"funcionario3\"]\r\n funcionario4 = request.args[\"funcionario4\"]\r\n equipe.set_cadastrar(funcionario1, funcionario2,\r\n funcionario3, funcionario4)\r\n equipe.cadastrar_db(equipe.get_cadastrar())\r\n return redirect('/listagem')\r\n\r\n# Rota de edição (individual)\r\n@app.route('/editar')\r\ndef editar():\r\n\r\n retornar = Listar()\r\n\r\n if 'id_pessoal' in request.args.keys():\r\n lista = retornar.funcionario_individual(request.args['id_pessoal'])\r\n elif 'id_equipe' in request.args.keys():\r\n lista = retornar.equipe_individual(request.args['id_equipe'])\r\n elif 'id_linguagem' in request.args.keys():\r\n lista = retornar.linguagem_individual(request.args['id_linguagem'])\r\n\r\n return render_template('editar.html', pessoa=lista)\r\n\r\n# Rota que edita ou deleta um funcionario e a pessoa\r\n@app.route('/editar_funcionario', methods=['POST'])\r\ndef editar_funcionario():\r\n func = Funcionario_db()\r\n pess = Pessoa_db()\r\n if 'deletar' in request.form.keys():\r\n func.deletar_db(request.form['id_funcionario'])\r\n pess.deletar_db(request.form['id_pessoal'])\r\n elif 'alterar' in request.form.keys():\r\n func.set_editar(request.form['id_funcionario'],\r\n request.form['cargo'], request.form['salario'])\r\n func.editar_db(func.get_editar())\r\n pess.set_editar(request.form['id_pessoal'], request.form['nome'],\r\n request.form['cpf'], request.form['telefone'])\r\n pess.editar_db(pess.get_editar())\r\n\r\n return redirect('/listagem')\r\n\r\n# Rota que edita ou deleta a linguagem\r\n@app.route('/editar_linguagem', methods=['POST'])\r\ndef editar_linguagem():\r\n lg = Linguagem_db()\r\n if 'deletar' in request.form.keys():\r\n lg.deletar_db(request.form['id_linguagem'])\r\n elif 'alterar' in request.form.keys():\r\n lg.set_editar(request.form['id_linguagem'],\r\n request.form['nome'])\r\n lg.editar_db(lg.get_editar())\r\n\r\n return redirect('/listagem')\r\n\r\n# Rota que edita ou deleta a equipe\r\n@app.route('/editar_equipe', methods=['POST'])\r\ndef editar_equipe():\r\n eq = Equipe_db()\r\n if 'deletar' in request.form.keys():\r\n eq.deletar_db(request.form['id_equipe'])\r\n elif 'alterar' in request.form.keys():\r\n eq.set_editar(request.form['id_equipe'],\r\n request.form['id1'], request.form['id2'], request.form['id3'], request.form['id4'])\r\n eq.editar_db(eq.get_editar())\r\n\r\n return redirect('/listagem')\r\n\r\n\r\napp.run(debug=True)\r\n","sub_path":"atividades_em_dupla/isabel_e_gustavo/atividade/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"459065947","text":"###################\n# Funktiotehtavia #\n###################\n\n#1.Etsi pienempi\ndef pienempi(a,b):\n\tif a < b:\n\t\treturn a\n\treturn b\n\n#2.Etsi suurempi\ndef suurempi(a,b):\n\tif a > b:\n\t\treturn a\n\treturn b\n\n#3.Onko toinen luku x...\ndef paljonisompi(a,b,x):\n\tif a+x > b:\n\t\treturn 0\n\treturn 1\n\n#4.Tee funktio, joka palauttaa löydetyn alkion naapurit\ndef palautanaapurit(li, alkio):\n\ti = 0\n\tfor x in li:\n\t\tif x == alkio:\n\t\t\treturn li[i-1], li[i+1]\n\t\ti += 1\n\n\n###################\n# Talukkotehtavia #\n###################\n\n#5.Sama ja naapurit\ndef sama_naap(li, alkio, raja):\n\ti = 0\n\tfor x in li:\n\t\tif x == alkio:\n\t\t\treturn li[i-raja:i+raja+1]\n\t\ti += 1\n\n#1.Palauta joka toinen\ndef jokatoinen(li):\n\treturn li[0::2]\n\n#2.Tee funktio, joka tuottaa kaksi taulukkoa...\ndef erottele(li):\n\tparilliset, parittomat = [], []\n\tfor x in li:\n\t\tif x % 2 == 0:\n\t\t\tparilliset.append(x)\n\t\telse:\n\t\t\tparittomat.append(x)\n\treturn parilliset, parittomat\n\n#3.Tee funktio, joka poistaa taulukosta alkion\ndef poista_alkio(li, alkio):\n\tnewli = []\n\tfor x in li:\n\t\tif x != alkio:\n\t\t\tnewli.append(x)\n\treturn newli\n\n#4.Tee funktio, joka poistaa annetusta taulukosta..\ndef poista_alkiot(li_a, li_b):\n\tnewli = []\n\tfor x in li_a:\n\t\tif x not in li_b:\n\t\t\tnewli.append(x)\n\treturn newli\n\n#5.Tee funktio, joka kääntää taulukon\n\n#a) and b)\ndef kaanna(thingy):\n\treturn thingy[::-1]\n\n#c)\ndef interactive():\n\tword = input(\"Anna data: \")\n\treturn word[::-1]\n\n#6.Tee funktio, joka etsii taulukosta pienimmän arvon\ndef etsi_pienin(li):\n\tnew = 0\n\tfor x in li:\n\t\tif not new:\n\t\t\tnew = x\n\t\tif x < new:\n\t\t\tnew = x\n\treturn new\n\n#7.Tee functio, joka etsii taulukosta suurimman arvon\ndef etsi_suurin(li):\n\tnew = 0\n\tfor x in li:\n\t\tif not new:\n\t\t\tnew = x\n\t\tif x > new:\n\t\t\tnew = x\n\treturn new\n\n#8.Tee funktio, joka palauttaa taulukon keskiarvon\ndef keskiarvo(li):\n\ttulos = 0\n\tfor x in li:\n\t\ttulos += x\n\treturn int(tulos/len(li))\n\n#9.Tee funktio, joka summaa yhteen kahden taulukon alkiot\ndef summaa(li_a, li_b):\n\tnew = []\n\tfor x in range(len(li_a)):\n\t\tnew.append(li_a[x] + li_b[x])\n\treturn new\n\n#10.Tee funktio, joka summaa yhteen kahden erimittaisen...\ndef summaa_erimittaiset(li_a, li_b):\n\tnew = []\n\tlyhyt = None\n\tif len(li_a) < len(li_b):\n\t\tlyhyt = li_a\n\telse:\n\t\tlyhyt = li_b\n\n\tfor x in range(len(lyhyt)):\n\t\tnew.append(li_a[x] + li_b[x])\n\treturn new\n\n#11.Tee funktio, joka yhdistää kahden erimittaisen...\ndef yhdista(li_a, li_b):\n\tlyhyt = li_b\n\tnew = []\n\tif len(li_a) < len(li_b):\n\t\tlyhyt = li_a\n\t\n\tfor x in range(len(lyhyt)):\n\t\tnew.append(li_a[x])\n\t\tnew.append(li_b[x])\n\n\treturn new\n\n\n###########################\n# Moniulotteiset taulukot #\n###########################\n\n#12.Litistäminen\ndef litista(*args):\n\tnew = []\n\tfor x in args:\n\t\tfor y in x:\n\t\t\tnew.append(y)\n\treturn new\n\n#13.Tee kertotaulufunktio niin, että tuloksena on kaksiulotteinen...\ndef kertotaulutaulukossa():\n\tli = []\n\tfor x in range(1,11):\n\t\tl = []\n\t\tfor y in range(1,11):\n\t\t\tl.append(x*y)\n\t\tli.append(l)\n\treturn li\n\n\n################\n# Oliotehtäviä #\n################\n\n#tein funktionin sisään, jotta ei tuu erroria kun koitan muita tehtäviä\n#14.Määrittele olioluokka\ndef oliotehtava():\n\n\tclass Auto:\n\t\tdef __init__(self, tunniste):\n\t\t\tself.tunniste = tunniste\n\n\tautot = []\n\tfor x in range(1,11):\n\t\tautot.append(Auto(x))\n\n\tfor auto in autot:\n\t\tprint(f'{auto} - Tunniste: {auto.tunniste}')\n\n\n####################\n# Nimigeneraattori #\n####################\n\ndef nimigeneraattori():\n\timport string\n\tfrom random import choice\n\ta = [\"a\", \"e\", \"i\", \"o\", \"u\", \"y\"]\n\tb = [x for x in string.ascii_lowercase if x not in a]\n\teka_tavu = [choice(a), choice(b), choice(a)]\n\ttoka_tavu = [choice(b), choice(a)]\n\tname = eka_tavu + toka_tavu\n\tresult = \"\"\n\tfor x in name:\n\t\tresult+=x\n\treturn result\n\n\n#################################\n# Tiedostojen kirjoitus ja luku #\n#################################\n\n#16.Kirjoita taulukon sisältö tekstitiedostoon\ndef kirjoitatiedostoon(li, fi): #list, file\n\twith open(fi, \"a\") as file:\n\t\tfor x in li:\n\t\t\tfile.write(x+\"\\n\")\n\n#17.Lue tyhjään taulukkoon arvot tekstitiedostosta\ndef taytataulu(li, fi): #list, file\n\twith open(fi, \"r\") as file:\n\t\tfor x in file.read().splitlines():\n\t\t\tli.append(x)\n\treturn li","sub_path":"python_tehtavia_marraskuu.py","file_name":"python_tehtavia_marraskuu.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"47087867","text":"import game\n\nwarrior = game.character(\"Warrior\", 500, 500, game.attack(30, [(1,0)]), 8, 3, True, game.b.grid[10][11])\n\nbarbarian = game.character(\"Barbarian\", 600, 600, game.attack(30, [(1,0),(1,1),(1,-1),(0,1),(0,-1),(-1,0),(-1,-1),(-1,1)]), 0, 3, True, game.b.grid[10][10])\n\nmage = game.character(\"Mage\", 300, 300, game.attack(50, [(2,0), (2,1),(2,-1)]), 2, 3, True, game.b.grid[11][11])\n\npriest = game.character(\"Priest\", 350, 350, game.attack(-20, [(1,0),(2,0),(3,0)]), 2, 2, True, game.b.grid[11][10])\n\narcher = game.character(\"Archer\", 200, 200, game.attack(60, [(5,0)]), 3, 2, True, game.b.grid[11][9])\n\ncavalry = game.character(\"Cavalry\", 450, 450, game.attack(40, [(1,0),(2,0)]), 10, 5, True, game.b.grid[10][9])\n\n\n\nminion=game.character(\"minion\",100,100,game.attack(20,[(1,0)]),2,2,False,game.b.grid[1][0])\nminion2=game.character(\"minion2\",100,100,game.attack(20,[(1,0)]),2,2,False,game.b.grid[1][1])\nminion3=game.character(\"minion3\",100,100,game.attack(20,[(1,0)]),2,2,False,game.b.grid[1][2])\ndemon=game.character(\"demon\",1000,1000,game.attack(150,[(1,0),(1,1),(1,-1)]),15,3,False,game.b.grid[0][0])\nskelton=game.character(\"skelton\",50,50,game.attack(50,[(1,0)]),0,4,False,game.b.grid[1][3])\nskelton2=game.character(\"skelton2\",50,50,game.attack(50,[(1,0)]),0,4,False,game.b.grid[1][4])\nskelton3=game.character(\"skelton3\",50,50,game.attack(50,[(1,0)]),0,4,False,game.b.grid[1][5])\n\n\ncharactersDict = {\"Warrior\":warrior, \"Barbarian\":barbarian, \"Mage\":mage, \"Priest\":priest, \"Archer\":archer, \"Cavalry\":cavalry}","sub_path":"characters.py","file_name":"characters.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"493406203","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.contrib.auth.models import User\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom rest_framework import status\n\nimport json \nimport pytest\nfrom mixer.backend.django import mixer\n\nfrom .base import PostsBaseTest\n\n# 한글로 주석 쓰려고 맨위에 저런걸 달아요\npytestmark = pytest.mark.django_db\n\n\nclass PostViewsTests(PostsBaseTest):\n\n def test_create_fake_data_then_send_get_request_via_user_viewset(self):\n # create 50 users\n for cnt in range(50):\n mixer.blend('auth.User', is_active=True)\n url = reverse('user-list')\n response = self.client.get(url, format='json')\n assert response.status_code == status.HTTP_200_OK\n\n def test_send_get_request_via_user_viewset(self):\n # list GET : POST\n # retrive / patch / des / GET:PUT:DELETE\n url = reverse('user-list')\n response = self.client.get(url, format='json')\n assert response.status_code == status.HTTP_200_OK\n\n def test_send_post_request_via_user_viewset(self):\n # list GET : POST\n # retrive / patch / des / GET:PUT:DELETE\n url = reverse('user-list')\n data = {\n 'username': 'HiDaniel',\n 'password': 'Hello_Ela',\n 'email': 'elastic7327@gmail.com',\n 'is_active': True,\n }\n response = self.client.post(url, data=data, format='json')\n print(response.content)\n print(User.objects.get(pk=1).username)\n assert response.status_code == status.HTTP_201_CREATED\n assert User.objects.get(pk=1).username == 'HiDaniel'\n\n def test_send_retrive_update_destroy_request_via_user_viewset(self):\n\n # POST 를 이용해서 유져생성\n url = reverse('user-list')\n data = {\n 'username': 'HiDaniel',\n 'password': 'Hello_Ela',\n 'email': 'elastic7327@gmail.com',\n 'is_active': True,\n }\n response = self.client.post(url, data=data, format='json')\n assert response.status_code == status.HTTP_201_CREATED\n assert User.objects.get(pk=1).username == 'HiDaniel'\n\n url = reverse('user-detail', args=[1])\n response = self.client.get(url, format='json')\n assert response.status_code == status.HTTP_200_OK\n\n url = reverse('user-detail', args=[1])\n data = {\n 'is_active': False,\n }\n\n response = self.client.patch(\n url,\n data=json.dumps(data),\n content_type='application/json'\n )\n print(response.content)\n assert response.status_code == status.HTTP_200_OK\n","sub_path":"src/posts/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349342316","text":"# https://atcoder.jp/contests/apc001/tasks/apc001_d\nimport sys\nsys.setrecursionlimit(2147483647)\nINF=float(\"inf\")\nMOD=10**9+7\ninput=lambda:sys.stdin.readline().rstrip()\ndef resolve():\n n,m=map(int,input().split())\n k=n-m-1 # merge する回数\n if(k==0):\n print(0)\n return\n if(n<2*k):\n print(\"Impossible\")\n return\n\n # cost の小さい方から使いたい\n A=[[a,i] for i,a in enumerate(map(int,input().split()))]\n A.sort()\n E=[[] for _ in range(n)]\n for _ in range(m):\n x,y=map(int,input().split())\n E[x].append(y)\n E[y].append(x)\n\n cnt=0\n col=[None]*n # 連結成分に分解\n def dfs(v)->bool:\n if(col[v] is not None): return False\n col[v]=cnt\n Q=[v]\n while(Q):\n v=Q.pop()\n for nv in E[v]:\n if(col[nv] is not None): continue\n col[nv]=cnt\n Q.append(nv)\n return True\n\n for v in range(n):\n cnt+=dfs(v)\n\n # 各連結成分(n-m 個)から1個ずつ選ぶ\n ans=0\n used=[0]*cnt\n for i in range(n):\n a,v=A[i]\n if(not used[col[v]]):\n ans+=a\n used[col[v]]=1\n A[i][0]=INF\n\n # 残りの頂点から 2k-(n-m) 個選ぶ\n A.sort()\n for a,v in A[:2*k-(n-m)]:\n ans+=a\n\n print(ans)\nresolve()\n","sub_path":"AtCoder_Petrozavodsk_Contest_001/d_forest.py","file_name":"d_forest.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"120076794","text":"'''\nAuthor: Copyright(c) 2020 Suwings\nDate: 2020-12-01 18:52:39\nLastEditTime: 2020-12-01 21:01:52\nDescription: 用于爬取方舟创意工坊的爬虫脚本\n'''\nimport scrapy\n\n\nclass CreativeWorkshopSpider(scrapy.Spider):\n\n name = 'CreativeWorkshopSpider'\n start_urls = [\n 'https://steamcommunity.com/workshop/browse/?appid=346110&p=5',\n ]\n\n def parse(self, response):\n for workshop_item in response.css('div.workshopItem'):\n mod_id = workshop_item.css(\n '.ugc::attr(data-publishedfileid)').get()\n title = workshop_item.css('.workshopItemTitle::text').get()\n author = workshop_item.css('.workshopItemAuthorName>a::text').get()\n image = workshop_item.css(\n '.workshopItemPreviewImage::attr(src)').get()\n\n # print('[命中]', \"名字:\", title, \" 作者:\", author)\n\n oneline = {\n 'mod_id': mod_id,\n 'title': title,\n 'author': author,\n 'image': image\n }\n\n yield oneline\n\n self.log('[命中]', str(oneline))\n\n # next_page = response.css('li.next a::attr(\"href\")').get()\n # if next_page is not None:\n # yield response.follow(next_page, self.parse)\n","sub_path":"example/WorkshopSpider-Quick/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"152351194","text":"import sys\nimport os \nfrom PyQt5.QtWidgets import (QApplication, QLabel, QMainWindow, QWidget, QHBoxLayout,\\\n QVBoxLayout, QAction, QFileDialog, QGraphicsView, QGraphicsScene, QCheckBox, QComboBox, QPushButton,\\\n QInputDialog, qApp, QLineEdit, QMessageBox)\nfrom PyQt5.QtGui import QPixmap, QIcon, QImage, QWheelEvent, QPainter, QPen, QBrush, QCursor\nfrom PyQt5.QtCore import Qt, QPoint, QRect, QSize\nfrom PyQt5 import QtWidgets, QtCore\nimport natsort\nimport numpy as np\nimport SimpleITK as itk\nimport qimage2ndarray\nimport math\nimport copy\nimport voxel\n\nclass MyWidget(QWidget): \n def __init__(self): \n super().__init__() \n\n self.scene_1 = QGraphicsScene()\n self.scene_2 = QGraphicsScene()\n self.view_1 = QGraphicsView(self.scene_1) \n self.view_2 = QGraphicsView(self.scene_2)\n\n self.deleteCurMaskBtn = QPushButton('Delete Mask(Not exist)', self)\n self.addMaskBtn = QPushButton('&Add Mask', self)\n self.maskComboBox = QComboBox(self)\n self.maskCheckBox = QCheckBox('Masking', self)\n self.blendCheckBox = QCheckBox('Blended Mask on', self)\n self.penSizeEdit = QLineEdit(self)\n self.penSizeEdit.setFixedWidth(30)\n\n self.dialogBtn = QPushButton('&ImgNum', self) \n self.previousBtn = QPushButton('&previous', self)\n self.nextBtn = QPushButton('&next', self)\n\n self.lbl_pen_size = QLabel('Pen & Eraser size', self)\n self.lbl_pen_size.setAlignment(Qt.AlignCenter)\n self.lbl_pos = QLabel()\n self.lbl_pos.setAlignment(Qt.AlignCenter)\n \n self.hViewbox = QHBoxLayout()\n self.hViewbox.addWidget(self.view_1)\n self.hViewbox.addWidget(self.view_2)\n\n self.view_1.wheelEvent = self.wheelEvent\n self.view_2.wheelEvent = self.wheelEvent\n\n self.hOptionbox = QHBoxLayout()\n self.hOptionbox.addWidget(self.deleteCurMaskBtn)\n self.hOptionbox.addWidget(self.addMaskBtn)\n self.hOptionbox.addWidget(self.maskComboBox)\n self.hOptionbox.addWidget(self.lbl_pen_size)\n self.hOptionbox.addWidget(self.penSizeEdit)\n self.hOptionbox.addWidget(self.maskCheckBox)\n self.hOptionbox.addWidget(self.blendCheckBox)\n self.hOptionbox.addWidget(self.previousBtn)\n self.hOptionbox.addWidget(self.nextBtn)\n self.hOptionbox.addWidget(self.dialogBtn)\n \n self.vbox = QVBoxLayout()\n self.vbox.addLayout(self.hViewbox)\n self.vbox.addLayout(self.hOptionbox)\n self.vbox.addWidget(self.lbl_pos)\n \n self.setLayout(self.vbox)\n\n def resizeEvent(self, event):\n if event.oldSize().width() < 1 or event.oldSize().height() < 1:\n return\n self.view_1.scale(event.size().width()/event.oldSize().width(), \\\n event.size().height()/event.oldSize().height())\n self.view_2.scale(event.size().width()/event.oldSize().width(), \\\n event.size().height()/event.oldSize().height())\n \n\nclass MyApp(QMainWindow):\n def __init__(self):\n super().__init__()\n self.window_level = 220\n self.window_width = 740\n self.deltaWL = 0\n self.deltaWW = 0\n\n self.Nx = 0 \n self.Ny = 0 \n self.NofI = 0 \n\n self.cur_idx = 0 \n self.cur_image = [] \n self.EntireImage = [] \n \n self.is_opened = False\n self.Lclicked = False\n self.Rclicked = False\n self.lastPoint = QPoint()\n self.mask_arrList = []\n self.drawn_imgList = []\n self.onCtrl = False\n self.onShift = False\n self.pen_size = 10\n self.py_raw = voxel.PyVoxel()\n\n self.wg = MyWidget() \n self.setCentralWidget(self.wg)\n self.initUI()\n \n def initUI(self):\n openRaw = QAction('Open Raw File', self)\n openRaw.triggered.connect(self.openImageRaw)\n openIMA = QAction('Open IMA File', self)\n openIMA.triggered.connect(self.openImageIMA)\n exitAction = QAction('Quit', self)\n exitAction.triggered.connect(qApp.quit)\n saveNpyAction = QAction('Save Masks As Npy', self)\n saveNpyAction.triggered.connect(self.saveMasksAsNpy)\n saveBinAction = QAction('Save Masks As Bin', self)\n saveBinAction.triggered.connect(self.saveMasksAsBin)\n loadNpyAction = QAction('Load Masks From Npy', self)\n loadNpyAction.triggered.connect(self.loadMasksNpy)\n loadBinAction = QAction('Load Masks From Bin', self)\n loadBinAction.triggered.connect(self.loadBinMasks)\n adjustAction = QAction('Adjust', self)\n adjustAction.triggered.connect(self.adjustImage)\n\n self.statusBar()\n\n menubar = self.menuBar()\n menubar.setNativeMenuBar(False)\n filemenu = menubar.addMenu('&File')\n filemenu.addAction(openRaw)\n filemenu.addAction(openIMA)\n filemenu.addAction(saveNpyAction)\n filemenu.addAction(saveBinAction)\n filemenu.addAction(loadNpyAction)\n filemenu.addAction(loadBinAction)\n filemenu.addAction(exitAction)\n filemenu = menubar.addMenu('&Image')\n filemenu.addAction(adjustAction)\n \n self.wg.deleteCurMaskBtn.clicked.connect(self.deleteMask)\n self.wg.addMaskBtn.clicked.connect(self.addMask)\n self.wg.maskCheckBox.stateChanged.connect(self.onMasking)\n self.wg.blendCheckBox.stateChanged.connect(self.onBlendedMask)\n self.wg.maskComboBox.activated.connect(self.maskComboBoxActivated)\n self.wg.penSizeEdit.textChanged[str].connect(self.setPenSize)\n self.wg.penSizeEdit.setText(str(self.pen_size))\n\n self.wg.dialogBtn.clicked.connect(self.showDialog)\n self.wg.previousBtn.clicked.connect(self.previousBtn_clicked)\n self.wg.nextBtn.clicked.connect(self.nextBtn_clicked)\n\n self.wg.view_1.setMouseTracking(True)\n self.wg.view_2.setMouseTracking(True)\n\n self.wg.scene_1.mouseMoveEvent = self.mouseMoveEvent\n self.wg.scene_1.mousePressEvent = self.mousePressEvent\n self.wg.scene_1.mouseReleaseEvent = self.mouseReleaseEvent\n self.wg.scene_2.mouseMoveEvent = self.mouseMoveEvent\n self.wg.scene_2.mousePressEvent = self.mousePressEvent\n self.wg.scene_2.mouseReleaseEvent = self.mouseReleaseEvent\n\n self.setWindowTitle('Image Labeling')\n self.setGeometry(300, 300, 1100, 600)\n self.show()\n \n def openImageRaw(self):\n try:\n fname = QFileDialog.getOpenFileName(self, \"Select File\")[0]\n self.py_raw.ReadFromRaw(fname)\n ImgArray = self.py_raw.m_Voxel\n\n self.EntireImage = np.asarray(ImgArray, dtype=np.float32) \n self.EntireImage = np.squeeze(self.EntireImage)\n self.NofI = self.EntireImage.shape[0] \n self.Nx = self.EntireImage.shape[1] \n self.Ny = self.EntireImage.shape[2] \n self.mask_arrList = np.zeros((1, self.NofI, self.Nx, self.Ny))\n self.refresh()\n self.is_opened = True\n except:\n return\n\n def openImageIMA(self):\n try:\n self.folder_path = str(QFileDialog.getExistingDirectory(self, \"Select Directory\"))\n reader = itk.ImageSeriesReader() \n dicom_names = reader.GetGDCMSeriesFileNames(self.folder_path)\n dicom_names = natsort.natsorted(dicom_names)\n reader.SetFileNames(dicom_names)\n images = reader.Execute()\n ImgArray = itk.GetArrayFromImage(images)\n\n self.EntireImage = np.asarray(ImgArray, dtype=np.float32) \n self.EntireImage = np.squeeze(self.EntireImage)\n self.NofI = self.EntireImage.shape[0] \n self.Nx = self.EntireImage.shape[1] \n self.Ny = self.EntireImage.shape[2] \n self.mask_arrList = np.zeros((1, self.NofI, self.Nx, self.Ny))\n self.refresh()\n self.is_opened = True\n except:\n return\n\n def adjustImage(self):\n level, ok = QInputDialog.getInt(self, 'Level', 'Level Set', value=self.window_level)\n width, ok = QInputDialog.getInt(self, 'Width', 'Width Set', value=self.window_width)\n self.window_level = level\n self.window_width = width\n self.refresh()\n\n def showDialog(self):\n num, ok = QInputDialog.getInt(self, 'Input ImageNumber', 'Enter Num', value=self.cur_idx+1)\n self.cur_idx = num - 1\n if self.cur_idx > self.NofI-1:\n self.cur_idx = self.NofI-1\n elif self.cur_idx < 0:\n self.cur_idx = self.NofI-224\n self.refresh()\n\n def refresh(self): \n try:\n cur_mask_index = self.wg.maskComboBox.currentIndex()\n self.wg.maskComboBox.clear()\n for i in range(self.mask_arrList.shape[0]):\n self.wg.maskComboBox.addItem('Mask' + str(i + 1))\n if cur_mask_index >= 0: self.wg.maskComboBox.setCurrentIndex(cur_mask_index)\n\n self.cur_orginal_image = self.EntireImage[self.cur_idx]\n self.cur_img_arr = self.AdjustPixelRange(self.cur_orginal_image, self.window_level, self.window_width)\n self.cur_image = qimage2ndarray.array2qimage(self.cur_img_arr)\n cur_image = QPixmap.fromImage(QImage(self.cur_image))\n\n self.wg.scene_1.clear()\n self.wg.scene_2.clear()\n self.wg.scene_1.addPixmap(cur_image)\n self.wg.scene_2.addPixmap(cur_image)\n self.wg.view_1.setScene(self.wg.scene_1)\n self.wg.view_2.setScene(self.wg.scene_2)\n\n mask = self.label2image(self.mask_arrList[self.wg.maskComboBox.currentIndex(), self.cur_idx])\n self.cur_maskPixmap = QPixmap.fromImage(QImage(mask))\n self.drawn_arrList = [qimage2ndarray.byte_view(mask)]\n self.wg.scene_2.addPixmap(self.cur_maskPixmap)\n \n self.wg.deleteCurMaskBtn.setText('Delete Mask {}'.format(self.wg.maskComboBox.currentIndex()+1))\n if self.wg.maskCheckBox.isChecked(): self.wg.maskCheckBox.toggle()\n if self.wg.blendCheckBox.isChecked(): self.wg.blendCheckBox.toggle()\n except:\n return\n \n def previousBtn_clicked(self):\n try:\n if self.is_opened:\n self.cur_idx = self.cur_idx - 1\n if self.cur_idx < 0: \n self.cur_idx = 0\n self.refresh()\n except:\n return\n\n def nextBtn_clicked(self):\n try:\n if self.is_opened:\n self.cur_idx = self.cur_idx + 1\n if self.cur_idx > self.NofI-1:\n self.cur_idx = self.NofI-1\n self.refresh()\n except:\n return\n\n def AdjustPixelRange(self, image, level, width):\n Lower = level - (width/2.0)\n Upper = level + (width/2.0)\n range_ratio = (Upper - Lower) / 256.0\n img_adjusted = (image - Lower)/range_ratio\n image = img_adjusted.clip(0, 255)\n return image\n\n def wheelEvent(self, event):\n try:\n if self.is_opened:\n n_scroll = int(event.angleDelta().y() / 120)\n \n self.cur_idx = self.cur_idx + n_scroll\n if self.cur_idx < 0:\n self.cur_idx = 0\n if self.cur_idx > self.NofI-1:\n self.cur_idx = self.NofI-1\n self.refresh() \n except:\n return\n\n def mouseMoveEvent(self, event):\n try:\n if self.is_opened:\n if self.Lclicked and self.Rclicked:\n rX = self.lastPoint.x()\n rY = self.lastPoint.y()\n \n mX = event.scenePos().x()\n mY = event.scenePos().y()\n\n square = (rX - mX)*(rX - mX) + (rY - mY)*(rY - mY)\n dist = math.sqrt(square) / 5\n\n if rX < mX: self.deltaWL = dist \n else: self.deltaWL = -dist\n if rY < mY: self.deltaWW = -dist\n else: self.deltaWW = dist\n self.window_level = self.window_level + self.deltaWL\n self.window_width = self.window_width + self.deltaWW\n\n if self.window_width <= 0: self.window_width = 0\n elif self.window_width > 900: self.window_width = 900\n\n if self.window_level < -250: self.window_level = -250\n elif self.window_level > 100: self.window_level = 100\n self.refresh()\n\n if self.Lclicked:\n painter = QPainter(self.cur_maskPixmap)\n painter.setPen(QPen(Qt.red, self.pen_size, Qt.SolidLine))\n if self.onCtrl:\n painter.drawLine(self.lastPoint, event.scenePos().toPoint())\n elif self.onShift:\n r = QRect(self.lastPoint, self.pen_size * QSize())\n r.moveCenter(event.scenePos().toPoint())\n painter.setCompositionMode(QPainter.CompositionMode_Clear)\n painter.eraseRect(r)\n self.wg.scene_2.removeItem(self.wg.scene_2.items()[0])\n self.wg.scene_2.addPixmap(self.cur_maskPixmap)\n \n self.lastPoint = event.scenePos().toPoint()\n\n if (self.lastPoint.x() >= 0) and (self.lastPoint.x() < self.Nx):\n if (self.lastPoint.y() >= 0) and (self.lastPoint.y() < self.Ny):\n value = self.cur_orginal_image[self.lastPoint.x(), self.lastPoint.y()]\n else: value = -1\n else: value = -1\n\n txt = \"x={0}, y={1}, z={2}, image value={3}\".format(\\\n self.lastPoint.x(), self.lastPoint.y(), self.cur_idx+1, value) \n self.wg.lbl_pos.setText(txt)\n except:\n return\n\n def mousePressEvent(self, event):\n try:\n if event.button() == Qt.LeftButton:\n self.Lclicked = True\n if event.button() == Qt.RightButton:\n self.Rclicked = True\n except:\n return\n\n def mouseReleaseEvent(self, event):\n try:\n if event.button() == Qt.LeftButton:\n if self.Lclicked:\n self.mask_arrList[self.wg.maskComboBox.currentIndex(), self.cur_idx] = \\\n self.image2label(self.cur_maskPixmap.toImage())\n self.drawn_imgList.append(qimage2ndarray.byte_view(self.cur_maskPixmap.toImage()))\n self.refreshMaskView()\n self.Lclicked = False\n if event.button() == Qt.RightButton:\n self.Rclicked = False\n except:\n return\n\n def keyPressEvent(self, event):\n if event.key() == Qt.Key_Control:\n self.onCtrl = True\n if event.key() == Qt.Key_Shift:\n self.onShift = True\n if self.onCtrl and event.key() == Qt.Key_Z:\n self.erasePreviousLine()\n if self.onCtrl and event.key() == Qt.Key_Plus:\n self.wg.view_2.scale(1.25, 1.25)\n if self.onCtrl and event.key() == Qt.Key_Minus:\n self.wg.view_2.scale(0.8, 0.8)\n\n def keyReleaseEvent(self, event):\n if event.key() == Qt.Key_Control:\n self.onCtrl = False\n if event.key() == Qt.Key_Shift:\n self.onShift = False\n \n def erasePreviousLine(self):\n if len(self.drawn_imgList) > 1:\n del self.drawn_imgList[len(self.drawn_imgList)-1]\n self.cur_maskPixmap = QPixmap.fromImage(QImage(self.drawn_imgList[len(self.drawn_imgList)-1]))\n self.mask_arrList[self.wg.maskComboBox.currentIndex(), self.cur_idx] = \\\n self.image2label(self.cur_maskPixmap.toImage())\n self.refreshMaskView()\n\n def onMasking(self, state):\n try:\n if Qt.Checked == state:\n origin_qimg = self.cur_image\n masked_qimg = self.label2image(self.mask_arrList[self.wg.maskComboBox.currentIndex(), self.cur_idx])\n \n origin_arr = qimage2ndarray.rgb_view(origin_qimg)\n masked_alpha_arr = qimage2ndarray.alpha_view(masked_qimg)\n\n channel = origin_arr.shape[2]\n temp = np.zeros((self.Nx, self.Ny, channel))\n\n for i in range(self.Nx):\n for j in range(self.Ny):\n if masked_alpha_arr[i, j] != 0:\n temp[i, j] = origin_arr[i, j]\n \n self.masked_arr = temp\n self.masked_qimg = qimage2ndarray.array2qimage(self.masked_arr)\n self.masked_pixmap = QPixmap.fromImage(QImage(self.masked_qimg))\n\n self.wg.scene_2.addPixmap(self.masked_pixmap)\n else:\n self.wg.scene_2.removeItem(self.wg.scene_2.items()[0])\n except:\n return\n \n def onBlendedMask(self, state):\n try:\n if Qt.Checked == state:\n masked_qimg = self.label2image(self.mask_arrList[self.wg.maskComboBox.currentIndex(), self.cur_idx])\n masked_arr = self.bgra2rgba(qimage2ndarray.byte_view(masked_qimg))\n masked_alpha_arr = masked_arr[:, :, 3].copy()\n masked_arr[:, :, 3] = masked_alpha_arr * 0.5\n\n blended_mask = qimage2ndarray.array2qimage(masked_arr)\n blended_mask = QPixmap.fromImage(QImage(blended_mask))\n self.wg.scene_2.removeItem(self.wg.scene_2.items()[0])\n self.wg.scene_2.addPixmap(blended_mask)\n else:\n self.wg.scene_2.removeItem(self.wg.scene_2.items()[0])\n self.wg.scene_2.addPixmap(self.cur_maskPixmap)\n except:\n return\n\n def addMask(self):\n try:\n self.mask_arrList = np.concatenate((self.mask_arrList, np.zeros((1, self.NofI, self.Nx, self.Ny))), axis=0)\n self.wg.maskComboBox.addItem('Mask' + str(self.mask_arrList.shape[0]))\n self.maskComboBoxActivated(self.mask_arrList.shape[0]-1)\n self.wg.maskComboBox.setCurrentIndex(self.mask_arrList.shape[0]-1)\n except:\n return\n\n def deleteMask(self): \n try:\n if self.mask_arrList.shape[0] > 1:\n self.mask_arrList = np.delete(self.mask_arrList, self.wg.maskComboBox.currentIndex(), axis=0)\n self.wg.maskComboBox.removeItem(self.wg.maskComboBox.currentIndex())\n cur_mask_index = self.wg.maskComboBox.currentIndex()\n self.wg.maskComboBox.clear()\n for i in range(self.mask_arrList.shape[0]):\n self.wg.maskComboBox.addItem('Mask' + str(i + 1))\n self.maskComboBoxActivated(cur_mask_index)\n self.wg.maskComboBox.setCurrentIndex(cur_mask_index)\n else:\n return\n except:\n return\n\n def maskComboBoxActivated(self, index):\n mask = self.label2image(self.mask_arrList[index, self.cur_idx])\n self.cur_maskPixmap = QPixmap.fromImage(QImage(mask))\n self.drawn_arrList = [qimage2ndarray.byte_view(mask)]\n self.wg.deleteCurMaskBtn.setText('Delete Mask {}'.format(index+1))\n self.refreshMaskView()\n\n def rgb2gray(self, rgb):\n return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])\n\n def bgra2rgba(self, bgra):\n rgba = bgra.copy()\n rgba[:, :, 0], rgba[:, :, 2] = bgra[:, :, 2], bgra[:, :, 0]\n \n return rgba\n\n def image2label(self, image):\n alpha_arr = qimage2ndarray.alpha_view(image)\n return np.where(alpha_arr > 0, self.wg.maskComboBox.currentIndex() + 1, 0)\n\n def label2image(self, label):\n x, y = label.shape[0], label.shape[1]\n\n r_img_arr = np.array([[[255, 0, 0, 255]] * y] * x)\n new_label = label.copy().reshape(x, y, 1)\n return qimage2ndarray.array2qimage(np.multiply(r_img_arr, new_label))\n\n def refreshMaskView(self):\n self.wg.scene_2.clear()\n self.wg.scene_2.addPixmap(QPixmap.fromImage(QImage(self.cur_image)))\n self.wg.scene_2.addPixmap(self.cur_maskPixmap)\n if self.wg.maskCheckBox.isChecked(): self.wg.maskCheckBox.toggle()\n if self.wg.blendCheckBox.isChecked(): self.wg.blendCheckBox.toggle()\n\n def setPenSize(self, text):\n try:\n self.pen_size = int(text)\n except:\n return\n\n def saveMasksAsNpy(self):\n try:\n save_fname = QFileDialog.getSaveFileName(self, \"Save Masks as npy\", './untitled.npy')[0]\n if len(save_fname) < 1: \n return\n if '.npy' not in save_fname:\n save_fname = save_fname + '.npy'\n for i in range(self.mask_arrList.shape[0]):\n np.save(save_fname[:-4] + '_{}'.format(i+1) + save_fname[-4:], self.mask_arrList[i])\n QMessageBox.information(self, 'Save All Masks', \"All masks is saved.\", \\\n QMessageBox.Ok, QMessageBox.Ok)\n except:\n return\n\n def saveMasksAsBin(self):\n try:\n save_fname = QFileDialog.getSaveFileName(self, \"Save Masks as bin\", './untitled.bin')[0]\n if len(save_fname) < 1: \n return\n if '.bin' not in save_fname:\n save_fname = save_fname + '.bin'\n\n for i in range(self.mask_arrList.shape[0]):\n fname = save_fname[:-4] + '_{}'.format(i+1) + save_fname[-4:]\n self.py_raw.m_Voxel = self.mask_arrList[i]\n self.py_raw.WriteToBin(fname)\n\n QMessageBox.information(self, 'Save All Masks', \"All masks is saved.\", \\\n QMessageBox.Ok, QMessageBox.Ok)\n except:\n return\n\n def loadMasksNpy(self):\n try:\n load_fname = QFileDialog.getOpenFileName(self, 'Load Masks From Npy File')[0]\n self.mask_arrList = np.load(load_fname)\n self.mask_arrList = np.expand_dims(self.mask_arrList, axis=0)\n self.refresh()\n except:\n return\n\n def loadBinMasks(self):\n try:\n fname = QFileDialog.getOpenFileName(self, 'Load Masks From Bin File')[0]\n self.py_raw.ReadFromBin(fname)\n\n if self.NofI == self.py_raw.m_Voxel.shape[0]:\n self.mask_arrList = self.py_raw.m_Voxel.copy()\n self.mask_arrList = np.expand_dims(self.mask_arrList, axis=0)\n self.refresh()\n except:\n return\n \n \n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = MyApp()\n sys.exit(app.exec_())\n","sub_path":"Optimization/optimization_v1.py","file_name":"optimization_v1.py","file_ext":"py","file_size_in_byte":22827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"466750197","text":"import sys\nsys.path.insert(1,\"../../\")\nimport h2o\nfrom tests import pyunit_utils\n\n\n\n\ndef pubdev_2041():\n\n iris = h2o.import_file(pyunit_utils.locate(\"smalldata/iris/iris.csv\"))\n\n s = iris.runif(seed=12345)\n train1 = iris[s >= 0.5]\n train2 = iris[s < 0.5]\n\n m1 = h2o.deeplearning(x=train1[0:4], y=train1[4], epochs=100)\n\n # update m1 with new training data\n m2 = h2o.deeplearning(x=train2[0:4], y=train2[4], epochs=200, checkpoint=m1.model_id)\n\n\n\nif __name__ == \"__main__\":\n pyunit_utils.standalone_test(pubdev_2041)\nelse:\n pubdev_2041()\n","sub_path":"h2o-py/tests/testdir_jira/pyunit_pubdev_2041.py","file_name":"pyunit_pubdev_2041.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"349404876","text":"import pandas as pd\nimport numpy as np\nimport datetime\nfrom sklearn.linear_model import LinearRegression\nfrom bokeh.plotting import show, output_file, figure\nfrom bokeh.models import ColumnDataSource, LogScale, DatetimeAxis, DatetimeTicker, DaysTicker,Label\nfrom sklearn.linear_model import LinearRegression\noutput_file(str(datetime.date.today())+'.html')\n\n\nconfirmed_cases=pd.read_csv(\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv\")\n\n\n\ncases = confirmed_cases.groupby('Country/Region').sum().iloc[:,2:].transpose()\ncases['total'] = cases.sum(axis=1)\n\ncases.index=pd.to_datetime(cases.index)\ncases.index.name='Date'\n\n\ncases = cases/100\nsource = ColumnDataSource(cases)\nrecent_US = np.log(cases['US'][datetime.date.today()-datetime.timedelta(days=8):])\nrecent_Italy = np.log(cases['Italy'][datetime.date.today()-datetime.timedelta(days=8):])\nL = LinearRegression().fit(np.array(range(len(recent_US))).reshape(-1,1),recent_US)\nL1 = LinearRegression().fit(np.array(range(len(recent_Italy))).reshape(-1,1),recent_Italy)\npercent_rate = 100*(np.exp(L.coef_)-1)[0]\npercent_rate_Italy = 100*(np.exp(L1.coef_)-1)[0]\nF = figure(width=600,height=600,x_axis_type='datetime',y_axis_type='log',y_range=(.1,2000),x_range=(datetime.datetime(2020,2,1),datetime.datetime(2020,4,1)))\n\n\nF.line(x='Date',y='US',source=source,line_width=3,color='darkblue',legend_label='US')\nF.line(x='Date',y='Italy',source=source,line_width=3,color='green',legend_label='Italy')\nF.line(x='Date',y='Germany',source=source, line_width=3,color='green',line_dash='dotted',legend_label='Germany')\nF.line(x='Date',y='China',source=source,line_width=3,color='orange',legend_label='China')\n#F.line(x='Date',y='predicted',color='red',line_width=3,source=source,line_dash='dotted')\nF.line(x='Date',y='total',color='black',line_width=3,line_dash='dashed',source=source,legend_label='World')\nF.title.text = \"COVID-19 Confirmed Cases (https://github.com/CSSEGISandData/COVID-19)\"\n\nF.add_layout(Label(text_font_style='bold',text_font_size=\"10pt\",x=300,y=100,x_units='screen',y_units='screen',text='USDaily Growth Rate: {:.0f} %'.format(percent_rate)))\nF.legend.location='bottom_left'\nF.legend.background_fill_alpha=0.0\nF.add_layout(Label(text_font_style='bold',text_font_size=\"10pt\",x=300,y=85,x_units='screen',y_units='screen',text='Italy Daily Growth Rate: {:.0f} %'.format(percent_rate_Italy)))\nF.yaxis.axis_label = \"100's of cases (log scale)\"\nF.xaxis.axis_label=\"Date\"\nF.background_fill_color=\"#EEEEEE\"\nF.xgrid.grid_line_color=\"white\"\nF.ygrid.grid_line_color=\"white\"\nshow(F)\n","sub_path":"src/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"281071205","text":"import sys\r\nsys.path.insert(0, '..')\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.model_selection import GridSearchCV\r\n#from xgboost import XGBClassifier\r\n#from sklearn.externals import joblib\r\nimport joblib\r\n\r\nfrom src import feature_extraction as feat\r\nfrom src import pre_processing as pp\r\n\r\n# Initialize a FeatureExtractor object\r\nfeature_extractor = feat.get_feature_extractor()\r\n\r\n# Get Preproccess Raw data (For Data Analysis)\r\npreprocessed_raw = feature_extractor.load_preprocessed_data()\r\n# Get Train and Test data\r\nX_train_raw, X_test_raw, y_train, y_test = feature_extractor.get_train_test_split(test_size = 0.2, \r\n random_state = 1,\r\n scale = False)\r\n\r\n# Convert y_train and y_test to 1-d array\r\ny_train = np.array(y_train).reshape(-1)\r\ny_test = np.array(y_test).reshape(-1)\r\n\r\n\r\n# Hand pick some features\r\nbest_feat = ['nr.employed', 'poutcome_success', 'emp.var.rate', 'pdays', 'cons.conf.idx', 'euribor3m', 'job_transformed_no_income']\r\n\r\nX_train = X_train_raw[best_feat]\r\nX_test = X_test_raw[best_feat]\r\n\r\n# Logistic regression with these features\r\nclf = LogisticRegression(random_state=0, max_iter = 1000)\r\n\r\nclf.fit(X_train, y_train)\r\njoblib.dump(clf, 'LR_prediction.joblib')\r\npred = clf.predict(X_test)\r\nprobs = clf.predict_proba(X_test)\r\naccuracy = accuracy_score(y_test, pred)\r\nconf = confusion_matrix(y_test, pred)\r\n\r\n# enter the params and get the predicted probability\r\ndef dynamic_predict(nr_employed=0, poutcome_success=0, emp_var_rate=0, pdays=0, cons_conf=0, euribor=0, no_income=0):\r\n '''\r\n Create predictions for new customers. Enter the inputs and get the probability.\r\n \r\n :param nr_employed: number of employees - quarterly indicator (numeric)\r\n :type nr_employed: numpy.ndarray or list or int or float\r\n :param poutcome_success: outcome of the previous marketing campaign (binary: 1 if success, 0 otherwise)\r\n :type poutcome_success: numpy.ndarray or list or int or float\r\n :param emp_var_rate: employment variation rate - quarterly indicator (numeric)\r\n :type emp_var_rate: numpy.ndarray or list or int or float\r\n :param pdays: number of days that passed by after the client was last contacted from a previous campaign (numeric; 999 means client was not previously contacted)\r\n :type pdays: numpy.ndarray or list or int or float\r\n :param cons_conf: consumer confidence index - monthly indicator (numeric)\r\n :type cons_conf: numpy.ndarray or list or int or float\r\n :param euribor: euribor 3 month rate - daily indicator (numeric)\r\n :type euribor: numpy.ndarray or list or int or float\r\n :param no_income: binary income indicator, 1 if the customer job retired, student or unemployed\r\n :type no_income: numpy.ndarray or list or int or float\r\n :return: Array of predicted probabilities\r\n :rtype: numpy.ndarray\r\n '''\r\n #assert len(nr_employed) == len(poutcome_success) == len(emp_var_rate)\r\n assert isinstance(nr_employed, (list, int, float, np.ndarray))\r\n \r\n nr_employed = np.array(nr_employed)\r\n poutcome_success = np.array(poutcome_success)\r\n emp_var_rate = np.array(emp_var_rate)\r\n pdays = np.array(pdays)\r\n cons_conf = np.array(cons_conf)\r\n euribor = np.array(euribor)\r\n no_income = np.array(no_income)\r\n \r\n features = pd.DataFrame({'nr.employed' : nr_employed, \r\n 'poutcome_success': poutcome_success, \r\n 'emp.var.rate' : emp_var_rate, \r\n 'pdays' : pdays,\r\n 'cons.conf.idx' : cons_conf, \r\n 'euribor3m' : euribor, \r\n 'job_transformed_no_income' : no_income}, \r\n index = range(1))\r\n\r\n probs_new = clf.predict_proba(features)[:, 1]\r\n\r\n return probs_new\r\n\r\n\r\n# some examples\r\n \r\n# dynamic_predict(nr_employed = [5099], \r\n# poutcome_success = [0], \r\n# emp_var_rate = [-1.8], \r\n# pdays = [999], \r\n# cons_conf = [-46.2], \r\n# euribor = [1.244], \r\n# no_income = [0])\r\n\r\n# dynamic_predict(nr_employed = [5099, 5195.8], \r\n# poutcome_success = [0, 1], \r\n# emp_var_rate = [-1.8, -0.1], \r\n# pdays = [999, 6], \r\n# cons_conf = [-46.2, -42], \r\n# euribor = [1.244, 4.076], \r\n# no_income = [0, 0])","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"342364477","text":"import datetime\nfrom django import template\n\nregister = template.Library()\n\n\n@register.inclusion_tag('pagination.html', takes_context=True)\ndef paginate(context):\n paginator = context['paginator']\n num_pages = paginator.num_pages\n current_page = context['page_obj']\n page_no = current_page.number\n\n if num_pages <= 11 or page_no <= 6:\n pages = [x for x in range(1, min(num_pages + 1, 12))]\n elif page_no > num_pages - 6:\n pages = [x for x in range(num_pages - 10, num_pages + 1)]\n else:\n pages = [x for x in range(page_no - 5, page_no + 6)]\n\n return {\n 'pages': pages,\n 'num_pages': num_pages,\n 'page_no': page_no,\n }\n","sub_path":"myemoticon/emoticon/templatetags/paginate_tag.py","file_name":"paginate_tag.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"451766934","text":"# coding: utf-8\nfrom optparse import make_option\nfrom django.core.management.commands.test import Command as TestCommand\nfrom django import VERSION as DJANGO_VERSION\n\n\nclass DisableMigrations(object):\n\n def __contains__(self, item):\n return True\n\n def __getitem__(self, item):\n return \"notmigrations\"\n\n\nclass Command(TestCommand):\n def __init__(self):\n super(Command, self).__init__()\n\n # Optparse was deprecated on 1.8\n # So we only define option_list for Django 1.7\n if DJANGO_VERSION < (1, 8):\n self.option_list = super(Command, self).option_list + (\n make_option('-n', '--nomigrations', action='store_true', dest='nomigrations', default=False,\n help='Tells Django to NOT use migrations and create all tables directly.'),\n )\n\n def add_arguments(self, parser): # New API on Django 1.8\n super(Command, self).add_arguments(parser)\n\n parser.add_argument('-n', '--nomigrations',\n action='store_true', dest='nomigrations', default=False,\n help='Tells Django to NOT use migrations and create all tables directly.'),\n\n def handle(self, *test_labels, **options):\n from django.conf import settings\n\n if options['nomigrations']:\n settings.MIGRATION_MODULES = DisableMigrations()\n\n super(Command, self).handle(*test_labels, **options)\n","sub_path":"test_without_migrations/management/commands/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"213710775","text":"n=int(input())\n\ndowns=[]\nzeros=[]\nups=[]\n\nfor _ in range(n):\n a,b = map(int, input().split())\n if ab:\n ups.append((a,b))\n else:\n zeros.append((a,b))\n\ndowns.sort(key=lambda x: x[0])\nups.sort(key=lambda x: -x[1])\n\nabl = downs+zeros+ups\n\nans = 0\nv = 0\nfor a,b in abl:\n v+=a\n ans=max(v,ans)\n v-=b\n\nprint(ans)","sub_path":"2_kakomon/arc/arc053_c.py","file_name":"arc053_c.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568065672","text":"import datetime\nfrom flask import Flask, session, redirect, url_for\nfrom apps.admin.controller.database import bp as admindatabasebp\nfrom apps.admin.controller.log import bp as adminlogbp\nfrom apps.admin.controller.config_field import bp as adminconfig_fieldbp\nfrom apps.admin.controller.upload import bp as adminuploadbp\nfrom apps.admin.controller.index import bp as adminindexbp\nfrom apps.common.controller.tool import bp as commontoolbp\nimport config\nimport apps.admin.hooks\nfrom exts import db\nfrom flask_session import Session\nfrom apps.home.controller.index import bp as homeindexbp\nfrom apps.admin.controller.login import bp as adminloginbp, LoginView\nfrom apps.admin.controller.role import bp as adminrolebp\nfrom apps.admin.controller.admin import bp as adminadminbp\n# login required test\nfrom flask_login.login_manager import LoginManager\nfrom flask_login import login_user, logout_user, UserMixin\nfrom flask_bootstrap import Bootstrap\n\nclass User(UserMixin):\n def is_authenticated(self):\n return True\n def is_active(self):\n return True\n def is_anonymous(self):\n return False\n def get_id(self):\n return \"1\"\n\n# # # # # # # # # # # # # # # # # # # # # from think.library.build import Build\n# # # # # # # # # # # # # # # # # # # # # Build().run()\napp = Flask(__name__)\nbootstrap = Bootstrap(app)\n\napp.register_blueprint(admindatabasebp)\napp.register_blueprint(adminlogbp)\napp.register_blueprint(adminconfig_fieldbp)\napp.register_blueprint(adminuploadbp)\napp.register_blueprint(adminindexbp)\napp.register_blueprint(commontoolbp)\napp.config.from_object(config)\napp.register_blueprint(homeindexbp)\napp.register_blueprint(adminloginbp)\napp.register_blueprint(adminrolebp)\napp.register_blueprint(adminadminbp)\n# login required test\napp.secret_key = 's3cr3t'\nlogin_manager = LoginManager()\nlogin_manager.session_protection = 'strong'\nlogin_manager.login_view = 'login'\nlogin_manager.init_app(app)\nSession(app)\n# session.permanent = True\n# app.permanent_session_lifetime = datetime.timedelta(seconds=5) # 5秒真男人\ndb.init_app(app)\n\n@login_manager.user_loader\ndef load_user(user_id):\n # print(user_id)\n user = User()\n return user\n\n@app.route(\"/login/\")\ndef login():\n user = User()\n login_user(user)\n return redirect('/admin/login/login/')\n\n@app.template_global('table_sort')\ndef table_sort(param):\n '''\n 所有蓝图公用的点击排序\n :param param:排序的字段\n :return:\n '''\n param = str(param)\n from flask import request\n url_path = request.path\n faStr = 'fa-sort'\n get = request.args.to_dict()\n if '_pjax' in get:\n get.pop('_pjax')\n if '_sort' in get:\n sortArr = get.get('_sort').split(',')\n if sortArr[0] == param:\n if sortArr[1] == 'asc':\n faStr = 'fa-sort-asc'\n sort = 'desc'\n elif sortArr[1] == 'desc':\n faStr = 'fa-sort-desc'\n sort = 'asc'\n get['_sort'] = param+','+sort\n else:\n get['_sort'] = param+',asc'\n else:\n get['_sort'] = param+ ',asc'\n paramStr = [];\n for v in get:\n paramStr.append(v+'='+get[v])\n paramStrs = \"&\".join(paramStr)\n url_path = url_path + '?' + paramStrs\n return ''\n\n@app.template_global('search_url')\ndef search_url(param):\n '''\n 搜索\n :param param:\n :return:\n '''\n param = str(param)\n from flask import request\n url_path = request.path\n get = request.args.to_dict()\n if '_pjax' in get:\n get.pop('_pjax')\n if param in get:\n get.pop(param)\n if 'page' in get:\n get.pop('page')\n if get:\n paramStr = []\n for v in get:\n paramStr.append(v + '=' + get[v])\n paramStrs = \"&\".join(paramStr)\n url_path = url_path + '?' + paramStrs\n return url_path\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"102736762","text":"# -*- coding: utf-8 -*-\n\nimport kss\n\nimport sys\nsys.path.append('./textrank-master')\n\nfrom textrank import KeysentenceSummarizer\n\n\nsents = ' '\ninputArgs = sys.argv\nfor i in range(1, len(inputArgs)):\n # i is a number, from 1 to len(inputArgs)-1\n text = sys.argv[i]\n sents = sents + ' ' + text\n\ncharacters = '[]\"!?\\n'\n\nfor x in range(len(characters)):\n sents = sents.replace(characters[x],\"\")\n \nsts = []\nfor sent in kss.split_sentences(sents):\n sts.append(sent)\n\nsummarizer = KeysentenceSummarizer(\n tokenize = lambda x:x.split(),\n min_sim = 0.3,\n verbose = False\n)\nkeysents = summarizer.summarize(sts, topk=2)\nfor _, _, sent in keysents:\n print(sent)","sub_path":"src/main/java/kr/inhatc/spring/article_summary.py","file_name":"article_summary.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"618262432","text":"'''\nThis is a smoke test for tools.staticmap_for_gps.\n'''\nfrom staticmap import Line\nimport matplotlib.pyplot as plt\nimport os\nimport sys\nsys.path.append('..')\n\nfrom tools.data_manager import DataManager\nfrom tools.static_map_base_layer import StaticMapBaseLayer\nfrom tools.staticmap_for_gps import generate_coordinates\n\ndef plot_gps_on_map():\n '''\n This functions is used to plot gps points on map\n :return: (px, py)coordinates of every gps data\n '''\n data_manager = DataManager('2013-01-10')\n # Download and extract sensor data\n data_manager.setup_data_files('sensor_data')\n # load gps\n data_manager.load_gps()\n\n map = StaticMapBaseLayer(1000, 1000, 80)\n\n coordinates = generate_coordinates(data_manager.data_dict)\n # Put image in the corresponding data directory\n os.chdir(data_manager.data_dir)\n\n line = Line(coordinates, 'red', 4)\n map.add_line(line)\n\n image = map.render_without_features()\n image.save('umich_empty.png')\n\n points = map.extract_line_points()\n x_coords = [item[0] for item in points]\n y_coords = [item[1] for item in points]\n\n plt.imshow(image)\n plt.plot(x_coords, y_coords)\n plt.show(block=True) # block program until window is closed\n\n return points\n\nif __name__ == '__main__':\n plot_gps_on_map()\n","sub_path":"misc/test_staticmap_for_gps.py","file_name":"test_staticmap_for_gps.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"305751550","text":"from PyQt5.QtWidgets import (\n QVBoxLayout,\n QHBoxLayout,\n QLabel,\n QTextEdit,\n QFrame,\n QWidget\n)\n\nfrom PyQt5.QtGui import(\n QFont,\n QTextFormat,\n)\n\nfrom PyQt5.QtCore import(\n QVariant,\n Qt\n)\n\n#from PyQt5 import Qt\n\nfrom cemu.parser import CodeParser\n\nfrom .highlighter import Highlighter\n\n\nclass CodeInfoBarWidget(QWidget):\n def __init__(self, textedit_widget, *args, **kwargs):\n super(CodeInfoBarWidget, self).__init__()\n self.textedit_widget = textedit_widget\n layout = QHBoxLayout()\n self.label = QLabel(\"Line:1 Column:1\")\n layout.addWidget(self.label)\n self.setLayout(layout)\n self.textedit_widget.cursorPositionChanged.connect(self.UpdateLabel)\n return\n\n\n def UpdateLabel(self):\n pos = self.textedit_widget.textCursor().position()\n text = self.textedit_widget.toPlainText()\n pos_x = text[:pos].count('\\n') + 1\n pos_y = len(text[:pos].split('\\n')[-1]) + 1\n self.label.setText(\"Line:{:d} Column:{:d}\".format(pos_x, pos_y))\n return\n\n\nclass CodeEdit(QTextEdit):\n def __init__(self):\n super(CodeEdit, self).__init__()\n self.cursorPositionChanged.connect(self.UpdateHighlightedLine)\n return\n\n\n def UpdateHighlightedLine(self):\n selection = QTextEdit.ExtraSelection()\n selection.format.setBackground(self.palette().alternateBase())\n selection.format.setProperty(QTextFormat.FullWidthSelection, QVariant(True))\n selection.cursor = self.textCursor()\n selection.cursor.clearSelection()\n self.setExtraSelections([selection,])\n return\n\n\nclass CodeEditorFrame(QFrame):\n def __init__(self, *args, **kwargs):\n super(CodeEditorFrame, self).__init__()\n\n # init code pane\n self.editor = CodeEdit()\n self.editor.setFont(QFont('Courier', 11))\n self.editor.setFrameStyle(QFrame.Panel | QFrame.Plain)\n self.editor.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)\n self.highlighter = Highlighter(self.editor, \"asm\")\n\n # info bar\n self.infobar = CodeInfoBarWidget(self.editor)\n vbox = QVBoxLayout(self)\n vbox.setSpacing(0)\n vbox.addWidget(self.editor)\n vbox.addWidget(self.infobar)\n return\n\n\nclass CodeWidget(QWidget):\n def __init__(self, parent, *args, **kwargs):\n super(CodeWidget, self).__init__()\n self.parent = parent\n self.code_editor_frame = CodeEditorFrame()\n self.editor = self.code_editor_frame.editor\n layout = QVBoxLayout()\n layout.addWidget( QLabel(\"Code\") )\n layout.setSpacing(0)\n layout.addWidget(self.code_editor_frame)\n self.setLayout(layout)\n self.parser = CodeParser(self)\n return","sub_path":"cemu/ui/codeeditor.py","file_name":"codeeditor.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422303922","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def generateTrees(self, n):\n \"\"\"\n :type n: int\n :rtype: List[TreeNode]\n \"\"\"\n if not n:\n return []\n return self.traverse(1, n)\n\n def traverse(self, lo, hi):\n res = []\n if lo > hi:\n res.append(None)\n return res\n if lo == hi:\n res.append(TreeNode(lo))\n return res\n for i in range(lo, hi + 1):\n left = self.traverse(lo, i - 1)\n right = self.traverse(i + 1, hi)\n for l in left:\n for r in right:\n mid = TreeNode(i)\n mid.left = l\n mid.right = r\n res.append(mid)\n return res\n","sub_path":"leetcode_python/095_unique_binary_search_trees_II.py","file_name":"095_unique_binary_search_trees_II.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"98277170","text":"\nimport numpy as np\n\nclass GaussLegendre():\n\t\n\tdef __init__(self, N):\n\t\tself.eps = 3.E-16\n\t\t\n\t\tself.N = N\n\t\t\n\t\t# these values change/update for new integral ranges\n\t\tself.x = np.linspace(-1,1,N)\n\t\tself.w = np.linspace(-1,1,N)\n\t\t\n\t\t# these values are fixed, used for updating the range\n\t\tself.X = np.linspace(-1,1,N)\n\t\tself.W = np.linspace(-1,1,N)\n\t\t\n\t\tself.gauss()\n\t\n\t# finds the roots of the Legendre polynomials using Newton's method\n\tdef gauss(self):\n\t\tt\t= 0.\t# xi\n\t\tt1\t= 0.\t# old xi\n\t\tpp\t= 0.\t# P'(xi)\n\t\tp1=p2=p3=0.\t# Legendre polynomials, P(xi) for i=1,2,3, respectively\n\t\teps = self.eps\n\t\tn \t= self.N\n\t\tm\t= (n+1)/2\n\t\t\n\t\tfor i in range(1,m+1):\n\t\t\tt = np.cos(np.pi*(i-0.25)/(n+0.5))\n\t\t\tt1 = 1\n\t\t\twhile abs(t-t1) >= eps:\n\t\t\t\tp1 = 1.\n\t\t\t\tp2 = 0.\n\t\t\t\tfor j in range(1,n+1):\n\t\t\t\t\tp3 = p2\n\t\t\t\t\tp2 = p1\n\t\t\t\t\tp1 = ((2*j-1)*t*p2 - (j-1.)*p3)/j\t#recurrence relation for Legendre polynomials\n\t\t\t\tpp = n*(t*p1-p2)/(t**2-1)\t\t\t\t#identity for P'(xi)\n\t\t\t\tt1 = t\n\t\t\t\tt = t1 - float(p1)/pp \t\t\t\t\t#Newton's method for finding roots\n\t\t\t\n\t\t\tself.x[i-1] = -t\n\t\t\tself.x[n-i] = t\n\t\t\t\n\t\t\tself.w[i-1] = 2./((1-t**2)*pp**2)\n\t\t\tself.w[n-i] = self.w[i-1]\n\t\t\t\n\t\tself.X[:] = self.x[:]\n\t\tself.W[:] = self.w[:]\n\t\n\t# changes integration span from [-1,1] to [0,inf)\n\tdef rangeChange_0_inf(self, scale):\n\t\tX = np.linspace(-1,1,self.N)\n\t\tW = np.linspace(-1,1,self.N)\n\t\tfor i in range(0,len(X)):\n\t\t\tX[i] = scale*np.tan(np.pi*(self.x[i]+1)/4)\n\t\t\tW[i] = scale*self.w[i]*np.pi/(4*(np.cos(np.pi*(self.x[i]+1)/4))**2)\n\t\tself.x = X\n\t\tself.w = W\n\t\n\tdef updateRange_a_b(self, a, b):\n\t\tX = np.linspace(-1,1,self.N)\n\t\tW = np.linspace(-1,1,self.N)\n\t\tfor i in range(0,len(X)):\n\t\t\tX[i] = 0.5*(b-a)*self.X[i] + 0.5*(b+a)\n\t\t\tW[i] = 0.5*(b-a)*self.W[i]\n\t\tself.x = X\n\t\tself.w = W\n","sub_path":"Lippmann-Schwinger modular solver/General_functions/Gauss_Legendre.py","file_name":"Gauss_Legendre.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29477273","text":"from __future__ import annotations\n\nimport asyncio\nimport logging\nfrom asyncio import Queue\nfrom datetime import datetime\nfrom pathlib import Path\nfrom typing import Dict, Optional, Any, List\n\nimport aiohttp\nfrom chia.rpc.farmer_rpc_client import FarmerRpcClient\nfrom chia.rpc.full_node_rpc_client import FullNodeRpcClient\nfrom chia.rpc.harvester_rpc_client import HarvesterRpcClient\nfrom chia.rpc.rpc_client import RpcClient\nfrom chia.rpc.wallet_rpc_client import WalletRpcClient\nfrom chia.server.outbound_message import NodeType\nfrom chia.util.ints import uint16\n\nfrom monitor.collectors.collector import Collector\nfrom monitor.events import (BlockchainStateEvent, ChiaEvent, ConnectionsEvent,\n HarvesterPlotsEvent, WalletBalanceEvent)\n\n\nclass RpcCollector(Collector):\n full_node_client: FullNodeRpcClient\n wallet_client: WalletRpcClient\n harvester_client: HarvesterRpcClient\n farmer_client: FarmerRpcClient\n\n @staticmethod\n async def create(root_path: Path, net_config: Dict, event_queue: Queue[ChiaEvent]) -> RpcCollector:\n self = RpcCollector()\n self.log = logging.getLogger(__name__)\n self.event_queue = event_queue\n\n self_hostname = net_config[\"self_hostname\"]\n full_node_rpc_port = net_config[\"full_node\"][\"rpc_port\"]\n wallet_rpc_port = net_config[\"wallet\"][\"rpc_port\"]\n harvester_rpc_port = net_config[\"harvester\"][\"rpc_port\"]\n farmer_rpc_port = net_config[\"farmer\"][\"rpc_port\"]\n\n self.full_node_client = await FullNodeRpcClient.create(self_hostname, uint16(full_node_rpc_port),\n root_path, net_config)\n self.wallet_client = await WalletRpcClient.create(self_hostname, uint16(wallet_rpc_port),\n root_path, net_config)\n self.harvester_client = await HarvesterRpcClient.create(self_hostname,\n uint16(harvester_rpc_port), root_path,\n net_config)\n self.farmer_client = await FarmerRpcClient.create(self_hostname, uint16(farmer_rpc_port),\n root_path, net_config)\n return self\n\n async def get_wallet_balance(self) -> None:\n try:\n wallets = await self.wallet_client.get_wallets()\n confirmed_balances = []\n for wallet in wallets:\n balance = await self.wallet_client.get_wallet_balance(wallet[\"id\"])\n confirmed_balances.append(balance[\"confirmed_wallet_balance\"])\n except:\n raise ConnectionError(\"Failed to get wallet balance via RPC. Is your wallet running?\")\n event = WalletBalanceEvent(ts=datetime.now(), confirmed=str(sum(confirmed_balances)))\n await self.publish_event(event)\n\n async def get_plots(self) -> Optional[Dict[str, Any]]:\n plots = None\n try:\n plots = await self.harvester_client.get_plots()\n except Exception as e:\n if isinstance(e, aiohttp.ClientConnectorError):\n print(\n f\"Failed to get harvester via RPC. Is your wallet running?\")\n else:\n print(f\"Exception from 'harvester' {e}\")\n\n return plots\n\n async def get_all_plots(self, harvester_hosts: List[str]) -> Optional[Dict[str, Any]]:\n all_plots = None\n for host in harvester_hosts:\n plots = await self.get_plots()\n if plots is not None and plots[\"success\"]:\n if all_plots is None:\n all_plots = plots\n else:\n all_plots[\"plots\"] += plots[\"plots\"]\n return all_plots\n\n async def get_harvesters(self) -> List[str]:\n harvester_hosts = []\n try:\n connections = await self.farmer_client.get_connections()\n for c in connections:\n if c[\"type\"] == NodeType.HARVESTER:\n harvester_hosts.append(c[\"peer_host\"])\n except Exception as e:\n print(f\"Exception from 'farmer' {e}\")\n\n return harvester_hosts\n\n async def get_harvester_plots(self) -> None:\n try:\n # plots = await self.harvester_client.get_plots()\n harvesters = await self.get_harvesters()\n plots = await self.get_all_plots(harvesters)\n except:\n raise ConnectionError(\"Failed to get harvester plots via RPC. Is your harvester running?\")\n event = HarvesterPlotsEvent(ts=datetime.now(),\n plot_count=len(plots[\"plots\"]),\n plot_size=sum(plot[\"file_size\"] for plot in plots[\"plots\"]))\n await self.publish_event(event)\n\n async def get_blockchain_state(self) -> None:\n try:\n state = await self.full_node_client.get_blockchain_state()\n except:\n raise ConnectionError(\"Failed to get blockchain state via RPC. Is your full node running?\")\n event = BlockchainStateEvent(ts=datetime.now(),\n space=str(state[\"space\"]),\n diffculty=state[\"difficulty\"],\n peak_height=str(state[\"peak\"].height),\n synced=state[\"sync\"][\"synced\"])\n await self.publish_event(event)\n\n async def get_connections(self) -> None:\n peers = await self.full_node_client.get_connections()\n full_node_connections = [peer for peer in peers if NodeType(peer[\"type\"]) == NodeType.FULL_NODE]\n farmer_connections = [peer for peer in peers if NodeType(peer[\"type\"]) == NodeType.FARMER]\n wallet_connections = [peer for peer in peers if NodeType(peer[\"type\"]) == NodeType.WALLET]\n event = ConnectionsEvent(ts=datetime.now(),\n full_node_count=len(full_node_connections),\n farmer_count=len(farmer_connections),\n wallet_count=len(wallet_connections))\n await self.publish_event(event)\n\n async def task(self) -> None:\n while True:\n await asyncio.gather(self.get_wallet_balance(), self.get_harvester_plots(),\n self.get_blockchain_state(), self.get_connections())\n await asyncio.sleep(10)\n\n @staticmethod\n async def close_rpc_client(rpc_client: RpcClient) -> None:\n rpc_client.close()\n await rpc_client.await_closed()\n\n async def close(self) -> None:\n await RpcCollector.close_rpc_client(self.full_node_client)\n await RpcCollector.close_rpc_client(self.wallet_client)\n await RpcCollector.close_rpc_client(self.harvester_client)\n await RpcCollector.close_rpc_client(self.farmer_client)\n","sub_path":"monitor/collectors/rpc_collector.py","file_name":"rpc_collector.py","file_ext":"py","file_size_in_byte":6897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"262923981","text":"#!/usr/bin/env python\n\nimport asyncio\nimport serial.aio\nimport websockets\nimport random\nimport time\nimport functools\n\nwsdelay = 1\nMSGMAX = 100000\nLOOKBACK_INTERVAL = 10\n\nclass serPort(asyncio.Protocol):\n msgpart = \"\"\n msgs = []\n def connection_made(self, transport):\n self.transport = transport\n transport.serial.flush()\n print('port opened', transport)\n transport.serial.rts = False\n #transport.write(b'hello world\\n')\n def data_received(self, data):\n datastr = data.decode('utf-8')\n #print(\"msg is currently: {}\".format(self.msg))\n self.msgpart += datastr\n mparse = self.msgpart.split('\\n')\n if len(mparse) > 1:\n if len(mparse) == 2:\n m = mparse[0]\n if len(m.split(',')) == 5:\n self.msgs.append(m)\n print(\"{}\".format(m))\n self.msgpart = \"\"\n if len(self.msgs) > MSGMAX:\n self.msgs.pop(0)\n #self.transport.close()\n def connection_lost(self, exc):\n print('port closed')\n asyncio.get_event_loop().stop()\n\nasync def listener(websocket, path):\n name = await websocket.recv()\n return name\n\nasync def consumer(websocket, path, message):\n print(\"< {}\".format(message))\n greeting = \"Hello {}!\".format(message)\n await websocket.send(greeting)\n print(\"> {}\".format(greeting))\n\nasync def producer(websocket, ser):\n while True:\n await asyncio.sleep(wsdelay)\n #mstime = int(time.time()*1000)\n mstime = int(ser.msgs[-1].split(',')[0])\n val = ser.msgs[-1].split(',')[1:]\n message = \"{:d},{!s}\".format(mstime, ','.join(val).strip())\n return message\n \nasync def lookback(websocket, ser):\n print(len(ser.msgs))\n for msg in (ser.msgs[i] for i in range(0,len(ser.msgs),LOOKBACK_INTERVAL)):\n try:\n mstime = int(msg.split(',')[0])\n val = msg.split(',')[1:]\n message = \"{:d},{!s}\".format(mstime, ','.join(val).strip())\n await websocket.send(message)\n print(\"lookback: {}\".format(msg))\n except:\n pass\n\nasync def handler(websocket,path,mytasks=[],mycallbacks=[],ser=''):\n await lookback(websocket, ser)\n \n while True:\n listener_task = asyncio.ensure_future(listener(websocket, path))\n producer_task = asyncio.ensure_future(producer(websocket, ser))\n #print(\"my callbacks: {}\".format(mycallbacks))\n \n #tasks = mytasks.append(listener_task) \n tasks = [listener_task, producer_task]\n #print(\"mytasks: {}\".format(mytasks))\n #print(\"tasks: {}\".format(tasks))\n done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)\n \n if listener_task in done:\n ## new data has arrived from the websocket\n print(\"listener_task triggered!\")\n message = listener_task.result()\n await consumer(websocket, path, message)\n mycallbacks[0](message.encode('utf-8'))\n print(message.encode('utf-8'))\n else:\n listener_task.cancel()\n \n if producer_task in done:\n message = producer_task.result()\n await websocket.send(message)\n print(\"{} sent\".format(message))\n\n\ndef main():\n loop = asyncio.get_event_loop()\n coro = serial.aio.create_serial_connection(loop, serPort, url='/dev/arduino', baudrate=38400)\n ser_task = asyncio.ensure_future(coro)\n loop.run_until_complete(coro)\n ###print(\"ser_task result: {}\".format(ser_task.result()))\n ser_transport = ser_task.result()[0]\n ser_protocol = ser_task.result()[1]\n ###writer = asyncio.StreamWriter(ser_transport, ser_protocol, reader, loop)\n ###print(ser_transport)\n\n myhandler = functools.partial(handler,mytasks=[],mycallbacks=[ser_transport.write],ser=ser_protocol)\n #myhandler = functools.partial(handler,mytasks=[ser_task.result()[1].data_received])\n # replacing '0.0.0.0' restricts access to 'localhost'\n start_server = websockets.serve(myhandler, '0.0.0.0', 8765)\n ws_task = asyncio.ensure_future(start_server)\n asyncio.get_event_loop().run_until_complete(start_server)\n print(\"ws_task results: {}\".format(ws_task.result()))\n ws_serv = ws_task.result()\n\n #loop = asyncio.get_event_loop()\n #coro = serial.aio.create_serial_connection(loop, serPort, '/dev/arduino',baudrate=38400,timeout=0.2)\n #loop.run_until_complete(coro)\n asyncio.get_event_loop().run_forever()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"py/v6.py","file_name":"v6.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"458747812","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 12 15:58:44 2020\n\n@author: g_dic\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Poly3DCollection, Line3DCollection\n\n\n# Retrieve destrieux parcellation in fsaverage5 space from nilearn\nfrom nilearn import datasets\nfrom nilearn import plotting\n\ndestrieux_atlas = datasets.fetch_atlas_surf_destrieux()\n\n# The parcellation is already loaded into memory\nparcellation = destrieux_atlas['map_left']\n\n# Retrieve fsaverage5 surface dataset for the plotting background. It contains\n# the surface template as pial and inflated version and a sulcal depth maps\n# which is used for shading\nfsaverage = datasets.fetch_surf_fsaverage()\n\n# The fsaverage dataset contains file names pointing to the file locations\nprint('Fsaverage5 pial surface of left hemisphere is at: %s' %\n fsaverage['pial_left'])\nprint('Fsaverage5 inflated surface of left hemisphere is at: %s' %\n fsaverage['infl_left'])\nprint('Fsaverage5 sulcal depth map of left hemisphere is at: %s' %\n fsaverage['sulc_left'])\n\nimport numpy as np\nfrom nilearn import surface\n\natlas = destrieux_atlas\ncoordinates = []\nlabels = destrieux_atlas['labels']\nfor hemi in ['left', 'right']:\n vert = destrieux_atlas['map_%s' % hemi]\n rr, _ = surface.load_surf_mesh(fsaverage['pial_%s' % hemi])\n for k, label in enumerate(labels):\n if \"Unknown\" not in str(label): # Omit the Unknown label.\n # Compute mean location of vertices in label of index k\n coordinates.append(np.mean(rr[vert == k], axis=0))\n\ncoordinates = np.array(coordinates) # 3D coordinates of parcels\n\n# We now make a synthetic connectivity matrix that connects labels\n# between left and right hemispheres.\nn_parcels = len(coordinates)\ncorr = np.zeros((n_parcels, n_parcels))\nn_parcels_hemi = n_parcels // 2\ncorr[np.arange(n_parcels_hemi), np.arange(n_parcels_hemi) + n_parcels_hemi] = 1\ncorr = corr + corr.T\n\n# plotting.plot_connectome(corr, coordinates,\n# edge_threshold=\"90%\",\n# title='fsaverage Destrieux atlas')\n# plotting.show()\n\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n#faces = Poly3DCollection(edges, linewidths=1, edgecolors='k')\n#faces.set_facecolor((0,0,1,0.1))\n\n#ax.add_collection3d(faces)\n\n# Plot the points themselves to force the scaling of the axes\nax.scatter(coordinates[:,0], coordinates[:,1], coordinates[:,2], s=5)\n\n#ax.set_aspect('equal')\n\nfig.show()\n","sub_path":"nilearn_brainImage.py","file_name":"nilearn_brainImage.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"11052885","text":"import torch.nn.functional as F\nfrom tqdm import trange, tqdm\nimport torch.optim as optim\nimport torch.nn as nn\nimport numpy as np\nimport torch\n\n\nclass LSTM(nn.Module):\n\n\n def __init__(self, embedding_dim, hidden_dim, lr, nl):\n super(LSTM, self).__init__()\n\n self.embedding_dim = embedding_dim\n self.hidden_dim = hidden_dim\n self.label_to_ix = {}\n self.word_to_ix = {}\n self.lr = lr\n self.nl = nl\n\n\n def init_hidden(self):\n\n return (torch.zeros(self.nl, 1, self.hidden_dim // self.nl).cuda(), torch.zeros(self.nl, 1, self.hidden_dim // self.nl).cuda())\n\n\n def forward(self, sentence):\n\n embeds = self.word_embeddings(sentence)\n lstm_out, self.hidden = self.lstm(embeds.view(len(sentence), 1, -1), self.hidden)\n label_space = self.hidden2tag(lstm_out.view(len(sentence), -1))\n label_scores = F.log_softmax(label_space, dim=1)\n\n return label_scores\n\n\n def init(self, docs):\n\n self.init_vocab(docs)\n\n self.word_embeddings = nn.Embedding(len(self.word_to_ix), self.embedding_dim).cuda()\n self.lstm = nn.LSTM(self.embedding_dim, self.hidden_dim // self.nl, num_layers=self.nl).cuda()\n self.hidden2tag = nn.Linear(self.hidden_dim // self.nl, len(self.label_to_ix)).cuda()\n self.hidden = self.init_hidden()\n\n self.loss_function = nn.NLLLoss().cuda()\n self.optimizer = optim.Adagrad(self.parameters(), lr=self.lr)\n\n\n def init_vocab(self, docs):\n\n for doc, label in docs:\n\n for word in doc:\n if word not in self.word_to_ix:\n self.word_to_ix[word] = len(self.word_to_ix)\n\n if label not in self.label_to_ix:\n self.label_to_ix[label] = len(self.label_to_ix)\n\n self.word_to_ix['UNK'] = len(self.word_to_ix)\n self.ix_to_label = { self.label_to_ix[label]: label for label in self.label_to_ix.keys() }\n\n\n def train(self, docs, epochs):\n\n self.init(docs)\n\n for epoch in trange(epochs):\n for doc, label in tqdm(docs):\n\n self.zero_grad()\n self.hidden = self.init_hidden()\n\n sentence_idxs = [self.word_to_ix[w] for w in doc]\n sentence_in = torch.tensor(sentence_idxs, dtype=torch.long).cuda()\n\n target_idxs = [self.label_to_ix[label] for w in doc]\n targets = torch.tensor(target_idxs, dtype=torch.long).cuda()\n\n label_scores = self(sentence_in)\n\n loss = self.loss_function(label_scores, targets)\n loss.backward()\n self.optimizer.step()\n\n\n def predict(self, doc):\n\n with torch.no_grad():\n\n idxs = [self.word_to_ix[w] if w in self.word_to_ix else self.word_to_ix['UNK'] for w in doc]\n inputs = torch.tensor(idxs, dtype=torch.long).cuda()\n label_scores = self(inputs)\n lix = np.argmax(label_scores[-1]).item()\n\n return self.ix_to_label[lix]\n","sub_path":"src/bilstm/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"83703162","text":"# -*- coding: utf-8 -*-\n\nfrom urllib.request import urlopen\nimport json\nimport time\nimport urllib.parse\nfrom urllib.parse import quote\nfrom baidu_music_test.data import api_parameter_data\nfrom baidu_music_test.utils import log_utils\n\n\ndef __get_url(host='',method='',**kwargs):\n \"\"\"功能:\n 拼接出URL\n 参数:\n host:例子:http://tingapi.ting.baidu.com/v1/restserver/ting?\n method:接口\n **kwargs:因为不同接口需要不同的参数,就要传入不同的参数,\n 例子:\n 具体的歌单页面需要:\n list_id(歌单id),offset=‘0’,withsong=‘1’,withcount=‘1’,size(返回的歌曲数量)=‘100’\n 歌单页面需要:\n channelname(频道说明(用中文需要转码)),size=‘100’,offset=‘0’,order_type(排序方式0最新1最热)=‘1’\n 榜单页面需要:\n type(具体是那个榜单,如:1是新歌榜,2是热歌榜,具体可以到api文档中查询:http://apidoc.taihenw.com/interface/info.php?interface_id=16),\n offset='0',size='100',fields=''(这个是需要的字段,是一个长串,例子:song_id%2Ctitle%2Cauthor%2Calbum_title%2Cpic_big%2Cpic_small%2Chavehigh%2Call_rate%2Ccharge%2Chas_mv_mobile%2Clearn%2Csong_source%2Ckorean_bb_song)\"\"\"\n timestamp = int(time.time()) #获取时间戳\n\n\n base_parameter_list = {\n 'from' : api_parameter_data.from_android,\n 'version' : api_parameter_data.version,\n 'channel' : api_parameter_data.channel,\n 'operator' : api_parameter_data.operator,\n 'qa' : api_parameter_data.qa,\n 'method' : method,\n 'timestamp' : str(timestamp)\n }\n method_par = kwargs #可变参数串\n url = host+urllib.parse.urlencode(base_parameter_list)+'&'+urllib.parse.urlencode(method_par)\n #print('生成的url为:'+url)\n return url\n\ndef __get_info(url = '', number = 0):\n \"\"\"功能:\n 根据url获取页面json\n 返回值:\n dic:正常的返回信息\n 1:获取多次失败\"\"\"\n i = number\n page = urlopen(url)\n data = page.read()\n dic = json.loads(data)\n result = __check_result(dic)\n if result == 0:\n return dic\n elif (not result == 0) and i<3:\n i += 1\n log_utils.C_INFO('获取信息失败,第 %d 次重新获取信息' %i)\n if __get_info(url,i) == 1:\n return 1\n else:\n log_utils.F_ERROR('重新获取信息多次失败,请检查接口和url。URL:'+url)\n return 1\n\ndef __check_result(dic):\n \"\"\"功能:\n 验证错误码,打印对应信息\n 返回值:\n 0:正常\n 1:参数错误\"\"\"\n error_code = dic['error_code']\n log_utils.C_INFO('error_code:'+str(error_code))\n if error_code == 22000:\n log_utils.C_INFO('获取信息成功')\n return 0\n elif error_code == 22005:\n log_utils.F_ERROR('获取信息失败。')\n log_utils.F_ERROR('error_message:'+dic['error_message'])\n return 1\n else:\n log_utils.F_ERROR('未知错误码')\n log_utils.F_ERROR('error_message:'+dic['error_message'])\n return 2\n\ndef __get_cookie():\n \"\"\"login_id是账号,password是密码的md5加密\"\"\"\n url = 'http://passport.qianqian.com/login?login_id=13522113807&password=29eea60d91f9216d0ce950889eb637c9&device_id=v2pcweb-zkagfyuhly15132404684581&tpl=baidu_music&login_type=1'\n page = urlopen(url)\n data = page.read()\n dic = json.loads(data)\n if not dic['error_code'] == 0:\n log_utils.F_ERROR('获取token失败!错误码为:'+dic['error_code'])\n return 1\n\n token = dic['token']\n return token\n\ndef __get_first_list_id_from_playlist(mode,url = ''):\n \"\"\"功能:\n 获取对应歌单列表的一些信息\n 参数:\n mode:返回的内容:1:获取对应歌单列表的第一个歌单list_id\n 2:获取对应歌单列表的第一个歌单的title\n 返回值:\n 1:获取失败\n \"\"\"\n dic = __get_info(url)\n if dic == 1:\n log_utils.F_ERROR('获取信息失败')\n return 1\n\n if mode == 1:\n list_id = dic['diyInfo'][0]['list_id']\n log_utils.C_INFO('获取的list_id为:'+list_id)\n return list_id\n elif mode == 2:\n list_name = dic['diyInfo'][0]['title']\n return list_name\n\ndef __get_first_three_song_name_from_songlist(number,url = ''):\n \"\"\"功能:\n 获取新歌榜前number首歌曲名\n 参数:\n url:\n number:获取的歌曲名数量\n 返回值:\n 1:获取失败\"\"\"\n dic = __get_info(url)\n if dic == 1:\n log_utils.F_ERROR('获取信息失败')\n return 1\n\n log_utils.C_INFO('该榜单的前 %d 首歌曲名为:'% number)\n song_name_list={}\n i=0\n while i < number:\n song_name_list[i] = dic['song_list'][i]['title']\n log_utils.C_INFO(str(i+1)+':'+song_name_list[i])\n i += 1\n return song_name_list\n\ndef __get_first_three_song_name_from_playlist(number,url = ''):\n \"\"\"功能:\n 获取对应url歌单的前number首歌曲名\n 参数:\n number:获取的歌曲名数量\n 返回值:\n 1:获取失败\"\"\"\n\n dic = __get_info(url)\n if dic == 1:\n log_utils.F_ERROR('获取信息失败')\n return 1\n\n song_list_name = dic['result']['info']['list_title']\n log_utils.C_INFO('该歌单名为:'+song_list_name)\n song_name_list={}\n log_utils.C_INFO('该歌单的前 %d 首歌名为:'%number)\n i=0\n while i < number:\n song_name_list[i] = dic['result']['songlist'][i]['title']\n log_utils.C_INFO(str(i+1)+':'+song_name_list[i])\n i += 1\n return song_name_list\n\ndef __get_collector_user_id_list(url = ''):\n \"\"\"获取收藏此歌单的用户id\"\"\"\n dic = __get_info(url)\n if dic == 1:\n log_utils.F_ERROR('获取信息失败')\n return 1\n collect_num = dic['result']['collect_num']\n i=0\n user_id_list = {}\n if collect_num > 7:\n while i < collect_num:\n user_id_list[i] = dic['result']['collector'][i]['userid']\n i += 1\n else:\n while i < 7:\n user_id_list[i] = dic['result']['collector'][i]['userid']\n i += 1\n return user_id_list\n\ndef __get_first_song_have_mv_code(play_list_url):\n \"\"\"根据url获取对应歌单的第一首歌的has_mv的code\n 返回值:\n 1:获取失败\n “1”:有mv\n “0”:没有mv\"\"\"\n dic = __get_info(play_list_url)\n if dic == 1:\n log_utils.F_ERROR('获取信息失败')\n return 1\n has_mv_code = dic['result']['songlist'][0]['has_mv']\n return has_mv_code\n\ndef get_new_song_list_first_song_name(number):\n \"\"\"获取新歌榜的前number首歌曲的歌曲名\n 返回值:\n song_list:歌曲名列表\n 1:获取失败\"\"\"\n song_list_url = __get_url(api_parameter_data.common_host,api_parameter_data.song_list_method,\n type = '1',offset = '0' ,size = '100' , fields = 'song_id%2Ctitle%2Cauthor%2Calbum_title%2Cpic_big%2Cpic_small%2Chavehigh%2Call_rate%2Ccharge%2Chas_mv_mobile%2Clearn%2Csong_source%2Ckorean_bb_song') #获取榜单页面的具体信息\n\n song_list = __get_first_three_song_name_from_songlist(number,song_list_url) #根据榜单的url获取其中的前三首歌\n if song_list == 1:\n return 1\n return song_list\n\ndef get_play_list_collector_user_id_list():\n \"\"\"获取收藏歌单的用户id的列表\n 返回值:\n 在获取信息失败的时候会返回1\"\"\"\n list_url = __get_url(api_parameter_data.common_host,api_parameter_data.play_list_method,\n channename = urllib.parse.quote('全部'),order_type = '1',offset='0',size='100')\n\n list_id = __get_first_list_id_from_playlist(1,list_url) #获取list_id\n if list_id == 1:\n return 1\n play_list_url = __get_url(api_parameter_data.common_host,api_parameter_data.play_list_page_method,\n list_id = list_id,offset = '0',withsong = '1',withcount = '1',size = '100') #根据list_id获取具体歌单页面的url,从这里能得到歌单的信息\n\n user_id_list = __get_collector_user_id_list(play_list_url)\n return user_id_list\n\ndef get_first_play_list_name():\n \"\"\"获取当前最热歌单第一名的歌单的歌单名\n 步骤:\n 1.获取最热歌单列表的url\n 2.根据url,获取第一个歌单的list_id\n 返回值:\n song_list:歌曲名列表\n 1:获取失败\"\"\"\n list_url = __get_url(api_parameter_data.common_host,api_parameter_data.play_list_method,\n channelname = urllib.parse.quote('全部'),order_type = '1',offset='0',size='100')\n\n list_name = __get_first_list_id_from_playlist(2,list_url) #获取title\n if list_name == 1:\n return 1\n return list_name\n\ndef get_first_play_list_first_song_name(number):\n \"\"\"获取当前最热歌单第一名的歌单的前number首歌曲名\n 步骤:\n 1.获取最热歌单列表的url\n 2.根据url,获取第一个歌单的list_id\n 3.根据list_id,拼接出对应歌单的url\n 4.根据url,获取歌单中的歌曲信息\n 返回值:\n song_list:歌曲名列表\n 1:获取失败\"\"\"\n list_url = __get_url(api_parameter_data.common_host,api_parameter_data.play_list_method,\n channelname = urllib.parse.quote('全部'),order_type = '1',offset='0',size='100')\n\n list_id = __get_first_list_id_from_playlist(1,list_url) #获取list_id\n if list_id == 1:\n return 1\n\n play_list_url = __get_url(api_parameter_data.common_host,api_parameter_data.play_list_page_method,\n list_id = list_id,offset = '0',withsong = '1',withcount = '1',size = '100') #根据list_id获取具体歌单页面的url,从这里能得到歌单的信息\n\n song_list = __get_first_three_song_name_from_playlist(number,play_list_url) #根据具体的歌单id,获取歌单中的前三首歌名\n if song_list == 1:\n return 1\n return song_list\n\ndef get_first_play_list_first_song_have_mv():\n \"\"\"判断当前最热歌单第一名的歌单的第一首歌是否有mv\n 步骤:\n 1.获取最热歌单列表的url\n 2.根据url,获取第一个歌单的list_id\n 3.根据list_id,拼接出对应歌单的url\n 4.根据url,获取歌单中的歌曲信息,根据这些信息判断第一首歌是否有mv\n 返回值:\n 1:获取失败\"\"\"\n list_url = __get_url(api_parameter_data.common_host,api_parameter_data.play_list_method,\n channelname = urllib.parse.quote('全部'),order_type = '1',offset='0',size='100')\n\n list_id = __get_first_list_id_from_playlist(1,list_url) #获取list_id\n if list_id == 1:\n return 1\n\n play_list_url = __get_url(api_parameter_data.common_host,api_parameter_data.play_list_page_method,\n list_id = list_id,offset = '0',withsong = '1',withcount = '1',size = '100') #根据list_id获取具体歌单页面的url,从这里能得到歌单的信息\n\n first_song_have_mv_code = __get_first_song_have_mv_code(play_list_url) #跟据url获取第一首歌曲是否有mv的code\n if first_song_have_mv_code == 1:\n return 1\n\n return first_song_have_mv_code\n\ndef get_user_collect_song_list():\n \"\"\"根据token获取对应用户的收藏信息\n 返回值:\n 1:获取失败\"\"\"\n token = __get_cookie()\n if token == 1:\n return 1\n url = __get_url(api_parameter_data.common_host,api_parameter_data.get_collect_method,\n pn = '0',rn = '50',token_ = token)\n dic = __get_info(url)\n if dic == 1:\n return 1\n song_name_list = {}\n i = 0\n total = dic['total']\n while i < total:\n song_name_list[i] = dic['result'][i]['title']\n i += 1\n\n return song_name_list\n","sub_path":"baidu_music_test/utils/api_utils.py","file_name":"api_utils.py","file_ext":"py","file_size_in_byte":12230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"29748151","text":"#!/usr/bin/env python\n\"\"\"\npgoapi - Pokemon Go API\nCopyright (c) 2016 tjado \nModifications Copyright (c) 2016 j-e-k \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,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE\nOR OTHER DEALINGS IN THE SOFTWARE.\n\nAuthor: tjado \nModifications by: j-e-k \n\"\"\"\n\nimport os\nimport re\nimport json\nimport struct\nimport logging\nimport requests\nimport argparse\nfrom time import sleep\nfrom pgoapi import PGoApi\nfrom pgoapi.utilities import f2i, h2f\nfrom pgoapi.location import getNeighbors\n\nfrom google.protobuf.internal import encoder\nfrom geopy.geocoders import GoogleV3\nfrom s2sphere import CellId, LatLng\n\nlog = logging.getLogger(__name__)\nfrom threading import Thread\nfrom Queue import Queue\nfrom web import run_web\ndef get_pos_by_name(location_name):\n geolocator = GoogleV3()\n loc = geolocator.geocode(location_name)\n\n log.info('Your given location: %s', loc.address.encode('utf-8'))\n log.info('lat/long/alt: %s %s %s', loc.latitude, loc.longitude, loc.altitude)\n\n return (loc.latitude, loc.longitude, loc.altitude)\n\ndef init_configs():\n parser = argparse.ArgumentParser()\n config_file = \"config.json\"\n\n # If config file exists, load variables from json\n load = {}\n if os.path.isfile(config_file):\n with open(config_file) as data:\n load.update(json.load(data))\n\n # Read passed in Arguments\n parser.add_argument(\"-a\", \"--accounts\", help=\"config_index\", nargs='+', default=[0], type=int)\n # parser.add_argument(\"-d\", \"--debug\", help=\"Debug Mode\", action='store_true')\n # parser.set_defaults(DEBUG=False)\n config = parser.parse_args()\n loaded = [load['accounts'][i] for i in config.accounts]\n # Passed in arguments shoud trump\n return loaded\n\n\ndef main():\n # log settings\n # log format\n logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')\n # log level for http request class\n logging.getLogger(\"requests\").setLevel(logging.WARNING)\n # log level for main pgoapi class\n logging.getLogger(\"pgoapi\").setLevel(logging.INFO)\n # log level for internal pgoapi class\n logging.getLogger(\"rpc_api\").setLevel(logging.INFO)\n\n # FIXME\n # if config.debug:\n # logging.getLogger(\"requests\").setLevel(logging.DEBUG)\n # logging.getLogger(\"pgoapi\").setLevel(logging.DEBUG)\n # logging.getLogger(\"rpc_api\").setLevel(logging.DEBUG)\n queues = {}\n for config in init_configs():\n queues[config[\"username\"]] = Queue()\n position = get_pos_by_name(config['location'])\n # instantiate pgoapi\n pokemon_names = json.load(open(\"pokemon.en.json\"))\n api = PGoApi(config, pokemon_names)\n\n # provide player position on the earth\n api.set_position(*position)\n if not api.login(config[\"auth_service\"], config[\"username\"], config[\"password\"], config.get(\"cached\",False)):\n return\n try:\n t = Thread(target=api.main_loop, args=[queues[config[\"username\"]]])\n t.daemon = True\n t.start()\n except Exception as e:\n log.error('Error in main loop, restarting %s', e)\n # restart after sleep\n sleep(30)\n main()\n run_web(queues)\n t.join(1)\nif __name__ == '__main__':\n main()\n","sub_path":"pokecli.py","file_name":"pokecli.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"261795512","text":"from pathlib import Path\nfrom hedgedog.logging import get_logger\nfrom hedgedog.nlp.spacy.umls import UmlsCandidateGenerator\nfrom hedgedog.tf.estimator.ingredients import dataset_ingredient\nfrom el.data.text import Concept, Document, Span\nimport json\nfrom tqdm import tqdm\nimport traceback\n\nlog = get_logger(\"mm.data.clef\")\n\n\nclass ClefDocument(Document):\n def __init__(self, data_dir: Path, doc_id: str, umls, k, code2id, id2code, id2types, mention2idx):\n text = (data_dir / f\"{doc_id}.text\").read_text().replace('\\t', ' ')\n concepts = []\n with (data_dir / f\"{doc_id}.pipe\").open('r') as f:\n for line in f:\n line = line.strip()\n try:\n fields = line.split('||')\n _, cui = fields[1], fields[2]\n spans = []\n for i in range(3, len(fields), 2):\n start, end = int(fields[i]), int(fields[i + 1])\n spans.append(Span(start, end, text[start:end]))\n except ValueError as e:\n log.error(f\"Could not parse line: ##{line}##\")\n log.error(e)\n traceback.print_exc()\n exit()\n\n # grab semantic types\n types = ['UnknownType']\n if cui in code2id and code2id[cui] in id2types:\n types = [id2code[t] for t in id2types[code2id[cui]]]\n concepts.append(Concept(spans, types, cui))\n super().__init__(doc_id, text, concepts, umls, k, mention2idx)\n\n\n@dataset_ingredient.capture\ndef create_dataset(project_dir, data_dir, candidates_per_concept):\n raw_dir = Path(project_dir) / 'clef'\n dataset_dir = Path(data_dir)\n dev_ids = [x.strip() for x in (raw_dir / 'dev_files.txt').open()]\n train_ids = [x.replace('train/', '').replace('.text', '').strip() for x in (raw_dir / 'train_files.txt').open('r')\n if x.replace('train/', '').replace('.text', '').strip() not in dev_ids]\n test_ids = [x.replace('test/', '').replace('.text', '').strip() for x in (raw_dir / 'test_files.txt').open('r')]\n\n umls = UmlsCandidateGenerator()\n cui2id = json.load((Path(project_dir) / 'info' / 'cui2id.json').open())\n mention2idx = json.load((Path(project_dir) / 'info' / 'clef_mentions.json').open())\n id2types = {int(k): v for k, v in json.load((Path(project_dir) / 'info' / 'cui2semtypes.json').open()).items()}\n id2cui = {v: k for k, v in cui2id.items()}\n\n def process_documents(doc_ids, in_dir, brat_dir, json_dir):\n num = 0\n for did in tqdm(doc_ids, total=len(doc_ids)):\n doc = ClefDocument(in_dir, did, umls, candidates_per_concept, cui2id, id2cui, id2types, mention2idx)\n if num < 20:\n doc.to_brat(brat_dir)\n num += 1\n outfile = json_dir / f\"{did}.json\"\n json.dump(doc.to_json(), outfile.open('w+'))\n\n log.info(\"Processing Training set...\")\n process_documents(train_ids, raw_dir / 'train', raw_dir / 'brat' / 'train', dataset_dir / 'train')\n log.info(\"Processing Dev set...\")\n process_documents(dev_ids, raw_dir / 'train', raw_dir / 'brat' / 'dev', dataset_dir / 'dev')\n log.info(\"Processing Test set...\")\n process_documents(test_ids, raw_dir / 'test', raw_dir / 'brat' / 'test', dataset_dir / 'test')\n\n\n@dataset_ingredient.capture\ndef dump_mentions(project_dir):\n raw_dir = Path(project_dir) / 'clef'\n train_ids = [x.replace('train/', '').replace('.text', '').strip() for x in (raw_dir / 'train_files.txt').open('r')]\n test_ids = [x.replace('test/', '').replace('.text', '').strip() for x in (raw_dir / 'test_files.txt').open('r')]\n\n mentions = set()\n\n def process_documents(doc_ids, in_dir):\n for doc_id in tqdm(doc_ids, total=len(doc_ids)):\n text = (in_dir / f\"{doc_id}.text\").read_text().replace('\\t', ' ')\n with (in_dir / f\"{doc_id}.pipe\").open('r') as f:\n for line in f:\n line = line.strip()\n try:\n fields = line.split('||')\n spans = []\n for i in range(3, len(fields), 2):\n start, end = int(fields[i]), int(fields[i + 1])\n spans.append(text[start:end].strip())\n except ValueError as e:\n log.error(f\"Could not parse line: ##{line}##\")\n log.error(e)\n traceback.print_exc()\n exit()\n mentions.add(' '.join(spans))\n\n process_documents(train_ids, raw_dir / 'train')\n process_documents(test_ids, raw_dir / 'test')\n\n out_file = Path(project_dir) / 'info' / 'clef_mentions.json'\n json.dump({m: i for i, m in enumerate(mentions)}, out_file.open('w+'))\n","sub_path":"el/data/clef.py","file_name":"clef.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"426230037","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_bcrypt import Bcrypt\nfrom flask_login import LoginManager\nfrom flask_mail import Mail\nfrom flask_migrate import Migrate\nfrom flask_jwt_extended import JWTManager\n#from flask_talisman import Talisman\n\nfrom cryptography.fernet import Fernet\nimport stripe\n\n\n####### RESTART DB? #######\nRESTART_DB = False\n###########################\n\ndb = SQLAlchemy()\nmigrate = Migrate()\nmail = Mail()\nbcrypt = Bcrypt()\njwt = JWTManager()\nlogin_manager = LoginManager()\nlogin_manager.login_view = 'users.login'\nlogin_manager.login_message_category = 'info'\nlogin_manager.login_message = 'Por favor, faça login para acessar essa página'\n\n\ndef single_yes_or_no_question(question, default_no=True):\n choices = ' [y/N]: ' if default_no else ' [Y/n]: '\n default_answer = 'n' if default_no else 'y'\n reply = str(input(question + choices)).lower().strip() or default_answer\n if reply[0] == 'y':\n return True\n if reply[0] == 'n':\n return False\n else:\n return False if default_no else True\n\n\ndef create_app(config_class):\n app = Flask(__name__)\n\n print(f\"STARTING CONFIG MODE: {config_class.MODE}\")\n app.config.from_object(config_class)\n\n stripe.api_key = app.config['STRIPE_KEYS']['SECRET_KEY']\n app.config[\"cript\"] = Fernet(app.config['CRIPTO_KEY'])\n\n db.init_app(app)\n migrate.init_app(app, db)\n mail.init_app(app)\n bcrypt.init_app(app)\n login_manager.init_app(app)\n jwt.init_app(app)\n\n from flask_app.python.main.routes import main\n from flask_app.python.users.routes import users\n from flask_app.python.ecommerce.routes import ecommerce\n from flask_app.python.artes_e_telas.routes import artes_e_telas\n from flask_app.python.payments.routes import payments\n from flask_app.python.errors.handlers import errors\n app.register_blueprint(main)\n app.register_blueprint(users)\n app.register_blueprint(ecommerce)\n app.register_blueprint(artes_e_telas)\n app.register_blueprint(payments)\n app.register_blueprint(errors)\n\n # Talisman(\n # app,\n # content_security_policy=[]\n # )\n\n print(\"\\nRestart DB set to:\", RESTART_DB, '\\n')\n ### Populando DB para os testes ###\n if RESTART_DB is True:\n if single_yes_or_no_question('Quer mesmo restaurar o banco de dados?'):\n from flask_app.python.artes_e_telas.utils import populate_db\n with app.app_context():\n populate_db()\n print(\"Banco de dados restaurado. \\n\")\n else:\n print(\"Banco de dados não restaurado. \\n\")\n #####################\n\n return app\n","sub_path":"flask_app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"578231163","text":"import os\nimport pickle\nimport functions.f_rolling_connectedness as f_roll\nimport time\nimport json\nimport functions.f_about_path as fap\n# import pandas as pd\n\n\n# count the time span, start\nstart_time = time.time()\n\n\n# load Prerequisite\nfile_dir = os.path.dirname(os.path.abspath(__file__))\nwith open(file_dir + '/docs' + '/Prerequisite.json') as f:\n prerequisite = json.load(f)\n# print(prerequisite)\n\n\n# varibales from prerequisite\ntarget_folder = prerequisite[\"target_folder\"]\npredict_conns_periods = prerequisite[\"predict_conns_periods\"]\nmaximum_lag = prerequisite[\"maximum_lag\"]\nperiods_one_conn = prerequisite[\"periods_one_conn\"]\nstart_dt = prerequisite['start_dt']\nend_dt = prerequisite['end_dt']\n\n\n# the number of data\n# simple version for working with CWD\nfile_path = os.path.dirname(os.path.realpath(__file__))\nparent_path = fap.f_parent_path(file_path, 0)\nsave_path = parent_path + '/docs/' + target_folder\n# print(save_path)\nn_instruments = sum([len(files) for r, d, files in os.walk(save_path)])\n# print(n_instruments)\n\n\n# delete .DS_store\nif os.path.isfile(save_path + '/.DS_Store'):\n os.remove(save_path + '/.DS_Store')\n\n\n# load volatility_dataframe\nfile_path = os.path.dirname(os.path.realpath(__file__))\nsave_path = file_path + '/docs/' + 'volatility.pickle'\nwith open(save_path, 'rb') as f:\n volatility_dataframe = pickle.load(f)\n# print(len(list(volatility_dataframe)))\n# with pd.option_context('display.max_rows', None, 'display.max_columns', None):\n# print(volatility_dataframe)\n\n\n# start the rolling connectedness\nroll_conn = (f_roll.\n Rolling_Connectedness(volatility_dataframe,\n maximum_lag,\n periods_one_conn,\n predict_conns_periods))\nroll_conn.divide_vol_dataframe()\n\nfile_path = os.path.dirname(os.path.realpath(__file__))\nsaving_folder = file_path + '/docs/'\n# print(saving_folder)\nroll_conn.calculate_rolling(start_dt, end_dt, saving_folder)\n\n# count the time span, end\nelapsed_time = time.time() - start_time\nprint(\"the time span in calculating rolling connectedness:\", elapsed_time)\nprint(\"===================\")\n","sub_path":"roll_conn.py","file_name":"roll_conn.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"468467346","text":"from dbmanager.pf_collection_manager import PFCollectionManager\nfrom dbmanager.pf_device_collection_manager import PFDeviceCollectionManager\n\nclass PFUserCollectionManager(PFCollectionManager):\n __PROFILE_COLLCETION_PREFIX = 'profile_user_collection'\n cache_cursors = None\n cache_data = {}\n \n @staticmethod\n def final_getProfileTagLabel():\n return 'profile_tags'\n \n @staticmethod\n def final_getLabelAccountType():\n return 'account_type'\n \n @staticmethod\n def final_getLabelAccountName():\n return 'account_name'\n \n @staticmethod\n def final_getLabelDevices():\n return 'devices'\n \n #override \n def __getCollectionName__(self, params = None):\n return PFUserCollectionManager.__PROFILE_COLLCETION_PREFIX\n \n def insertOrUpdateCollection(self, cur, is_insert, collection = None): \n if collection is None:\n collection = self.mDBManager.getCollection(self.__getCollectionName__())\n if is_insert == 1:\n self.mDBManager.insert(cur, collection)\n else:\n self.mDBManager.update(self.__buildUid__(cur[PFCollectionManager.final_getUidLabel()]), cur, collection)\n \n '''\n def insertOrUpdateCollectionDevice(self, _id, valueMap, collection = None):\n if collection is None:\n collection = self.mDBManager.getCollection(self.__getCollectionName__())\n #check whether this document existed, checked by chunleiid.\n c = self.isDocExist(_id)\n \n if c is None:\n #insert.\n userMap = self.__buildDocUser__(_id)\n #userMap[PFUserCollectionManager.final_getLabelDevices()] = deviceIdLst\n valueMap[next(userMap.__iter__())] = userMap[next(userMap.__iter__())]\n self.mDBManager.insert(valueMap, collection)\n else:\n #update\n tmpLst = []\n userMap = c.__getitem__(0)\n for statName in valueMap: \n if statName == PFUserCollectionManager.final_getLabelDevices():\n for deviceId in valueMap[PFUserCollectionManager.final_getLabelDevices()]:\n if deviceId not in userMap[PFUserCollectionManager.final_getLabelDevices()]:\n tmpLst.append(deviceId)\n userMap[PFUserCollectionManager.final_getLabelDevices()].extend(tmpLst)\n else:\n userMap[statName] = valueMap[statName]\n self.mDBManager.update(self.__buildUid__(_id), userMap, collection) \n '''\n \n def updateCollectionTag(self, _id, tagMap, collection = None):\n if collection is None:\n collection = self.mDBManager.getCollection(self.__getCollectionName__())\n #check whether this document existed, checked by chunleiid.\n c = self.isDocExist(_id)\n userMap = {}\n if c is None:\n pass\n else:\n #update\n userMap = c.__getitem__(0)\n userMap[PFUserCollectionManager.final_getProfileTagLabel()] = tagMap[PFUserCollectionManager.final_getProfileTagLabel()]\n self.mDBManager.update(self.__buildUid__(_id), userMap, collection) \n \n #override\n def __buildDocUser__(self, _id):\n userMap = {}\n userMap[PFUserCollectionManager.final_getUidLabel()] = _id\n return userMap\n \n def getTagsByAccountId(self, accountId): \n c = self.__getDocByUid__(accountId)\n \n uidData = next(c.__iter__())\n if uidData.get(PFUserCollectionManager.final_getProfileTagLabel()) is None:\n return []\n else:\n return uidData.get(PFUserCollectionManager.final_getProfileTagLabel())\n \n \n @staticmethod \n def __get_tag_from_collection__(collection_name, key_list):\n collection_manager = None\n tag_list = []\n if collection_name == PFDeviceCollectionManager.getCollectionName():\n collection_manager = PFDeviceCollectionManager()\n for k in key_list:\n tg_list = collection_manager.__final_getTagsByUidWithCache__(k)\n tag_list.extend(tg_list)\n return tag_list\n ''' \n def getTagsByUid(self, uid): \n c = self.__getDocByUid__(uid)\n if c is None or c.count() == 0:\n return []\n uidData = next(c.__iter__())\n if uidData.get(PFUserCollectionManager.final_getProfileTagLabel()) is None:\n return []\n else:\n return uidData.get(PFUserCollectionManager.final_getProfileTagLabel())\n ''' \n \n def merge_new_data_map(self, cur, _id, value_map):\n isInsert = 0\n data_map = {}\n if cur is None:\n data_map = self.__buildDocUser__(_id)\n isInsert = 1\n else:\n #update\n data_map = cur\n '''For each of stat map: \n {\n statName1: [\n {'launch_count': 8, 'packagename': com.baidu.map, 'duration': 20}, \n {}, \n {}\n ], \n statName2: [],\n .......\n } \n ''' \n for statName in value_map: #valueMap[chunleiId]\n data_map[statName] = value_map[statName]\n return (data_map, isInsert) \n \n \n","sub_path":"dbmanager/pf_user_collection.py","file_name":"pf_user_collection.py","file_ext":"py","file_size_in_byte":5437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"352582476","text":"#! /usr/bin/env python3\n\nimport sys\nfrom socket import *\n\nBUFSIZE = 1024\n\ndef main():\n if len(sys.argv) != 3:\n usage()\n else:\n tool()\n\ndef usage():\n sys.stdout = sys.stderr\n print('Usage: udptool.py host port')\n sys.exit(2)\n\ndef tool():\n host = sys.argv[1]\n port = eval(sys.argv[2])\n addr = host, port\n\n client = socket(AF_INET, SOCK_DGRAM)\n client.settimeout(2)\n client.bind(('', 0))\n\n print('udp echo client ready, reading stdin')\n while 1:\n line = sys.stdin.readline()\n if not line:\n break\n client.sendto(bytes(line, \"utf-8\"), addr)\n try:\n data, fromaddr = client.recvfrom(BUFSIZE)\n print('client received %r from %r' % (data, fromaddr))\n except timeout:\n print('timed out')\nmain()\n","sub_path":"udptool.py","file_name":"udptool.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"629651873","text":"import matplotlib.pyplot as plt\nimport csv\nimport os.path\n#print os.getcwd()\n\nx1 = []\ny1 = []\nx2 = []\ny2 = []\n\nuserhome = os.path.expanduser('~')\ncsvfileNominal= os.path.join(userhome, 'git/dkstewart/University-Research/Experiments', 'probWBS_4wheelMonoData.csv')\ncsvfileFault= os.path.join(userhome, 'git/dkstewart/University-Research/Experiments', 'probWBS_4wheelCompData.csv')\n\nwith open(csvfileNominal,'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n for row in plots:\n x1.append(float(row[0]))\n y1.append(float(row[1]))\n\nwith open(csvfileFault,'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n for row in plots:\n x2.append(float(row[0]))\n y2.append(float(row[1]))\n \nplt.scatter(x1, y1, label= \"Monolithic Analysis\", color= \"blue\", marker= \"x\", s=30)\nplt.scatter(x2, y2, label= \"Compositional Analysis\", color= \"red\", marker= \"x\", s=30) \n \n# naming the x axis \nplt.xlabel('Probability Threshold') \n# naming the y axis \nplt.ylabel('Time in Seconds')\nplt.xscale(\"log\")\n#plt.ticklabel_format(axis=\"x\", style=\"sci\", scilimits=(-12,-1))\nplt.xlim([-0.01, 0.0000000001])\n# show a legend on the plot \nplt.legend(loc=\"upper left\") \nplt.show() \n","sub_path":"Experiments/scripts/graphProbWBS_4wheel.py","file_name":"graphProbWBS_4wheel.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"76148058","text":"COPYRIGHT = \"\"\"\\\n/*\n * Copyright 2017 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sub license, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice (including the\n * next paragraph) shall be included in all copies or substantial portions\n * of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.\n * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR\n * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\"\"\"\n\nimport argparse\nimport copy\nimport re\nimport xml.etree.cElementTree as et\n\nMAX_API_VERSION = '1.0.57'\n\nclass Extension:\n def __init__(self, name, ext_version, enable):\n self.name = name\n self.ext_version = int(ext_version)\n if enable is True:\n self.enable = 'true';\n elif enable is False:\n self.enable = 'false';\n else:\n self.enable = enable;\n\n# On Android, we disable all surface and swapchain extensions. Android's Vulkan\n# loader implements VK_KHR_surface and VK_KHR_swapchain, and applications\n# cannot access the driver's implementation. Moreoever, if the driver exposes\n# the those extension strings, then tests dEQP-VK.api.info.instance.extensions\n# and dEQP-VK.api.info.device fail due to the duplicated strings.\nEXTENSIONS = [\n Extension('VK_ANDROID_native_buffer', 5, 'ANDROID'),\n Extension('VK_KHR_bind_memory2', 1, True),\n Extension('VK_KHR_dedicated_allocation', 1, True),\n Extension('VK_KHR_descriptor_update_template', 1, True),\n Extension('VK_KHR_external_fence', 1,\n 'device->has_syncobj_wait'),\n Extension('VK_KHR_external_fence_capabilities', 1, True),\n Extension('VK_KHR_external_fence_fd', 1,\n 'device->has_syncobj_wait'),\n Extension('VK_KHR_external_memory', 1, True),\n Extension('VK_KHR_external_memory_capabilities', 1, True),\n Extension('VK_KHR_external_memory_fd', 1, True),\n Extension('VK_KHR_external_semaphore', 1, True),\n Extension('VK_KHR_external_semaphore_capabilities', 1, True),\n Extension('VK_KHR_external_semaphore_fd', 1, True),\n Extension('VK_KHR_get_memory_requirements2', 1, True),\n Extension('VK_KHR_get_physical_device_properties2', 1, True),\n Extension('VK_KHR_get_surface_capabilities2', 1, 'ANV_HAS_SURFACE'),\n Extension('VK_KHR_image_format_list', 1, True),\n Extension('VK_KHR_incremental_present', 1, True),\n Extension('VK_KHR_maintenance1', 1, True),\n Extension('VK_KHR_maintenance2', 1, True),\n Extension('VK_KHR_push_descriptor', 1, True),\n Extension('VK_KHR_relaxed_block_layout', 1, True),\n Extension('VK_KHR_sampler_mirror_clamp_to_edge', 1, True),\n Extension('VK_KHR_sampler_ycbcr_conversion', 1, True),\n Extension('VK_KHR_shader_draw_parameters', 1, True),\n Extension('VK_KHR_storage_buffer_storage_class', 1, True),\n Extension('VK_KHR_surface', 25, 'ANV_HAS_SURFACE'),\n Extension('VK_KHR_swapchain', 68, 'ANV_HAS_SURFACE'),\n Extension('VK_KHR_variable_pointers', 1, True),\n Extension('VK_KHR_wayland_surface', 6, 'VK_USE_PLATFORM_WAYLAND_KHR'),\n Extension('VK_KHR_xcb_surface', 6, 'VK_USE_PLATFORM_XCB_KHR'),\n Extension('VK_KHR_xlib_surface', 6, 'VK_USE_PLATFORM_XLIB_KHR'),\n Extension('VK_KHX_multiview', 1, True),\n Extension('VK_EXT_debug_report', 8, True),\n]\n\nclass VkVersion:\n def __init__(self, string):\n split = string.split('.')\n self.major = int(split[0])\n self.minor = int(split[1])\n if len(split) > 2:\n assert len(split) == 3\n self.patch = int(split[2])\n else:\n self.patch = None\n\n # Sanity check. The range bits are required by the definition of the\n # VK_MAKE_VERSION macro\n assert self.major < 1024 and self.minor < 1024\n assert self.patch is None or self.patch < 4096\n assert(str(self) == string)\n\n def __str__(self):\n ver_list = [str(self.major), str(self.minor)]\n if self.patch is not None:\n ver_list.append(str(self.patch))\n return '.'.join(ver_list)\n\n def c_vk_version(self):\n ver_list = [str(self.major), str(self.minor), str(self.patch)]\n return 'VK_MAKE_VERSION(' + ', '.join(ver_list) + ')'\n\n def __int_ver(self):\n # This is just an expansion of VK_VERSION\n patch = self.patch if self.patch is not None else 0\n return (self.major << 22) | (self.minor << 12) | patch\n\n def __cmp__(self, other):\n # If only one of them has a patch version, \"ignore\" it by making\n # other's patch version match self.\n if (self.patch is None) != (other.patch is None):\n other = copy.copy(other)\n other.patch = self.patch\n\n return self.__int_ver().__cmp__(other.__int_ver())\n\nMAX_API_VERSION = VkVersion(MAX_API_VERSION)\n\ndef _init_exts_from_xml(xml):\n \"\"\" Walk the Vulkan XML and fill out extra extension information. \"\"\"\n\n xml = et.parse(xml)\n\n ext_name_map = {}\n for ext in EXTENSIONS:\n ext_name_map[ext.name] = ext\n\n for ext_elem in xml.findall('.extensions/extension'):\n ext_name = ext_elem.attrib['name']\n if ext_name not in ext_name_map:\n continue\n\n # Workaround for VK_ANDROID_native_buffer. Its element in\n # vk.xml lists it as supported=\"disabled\" and provides only a stub\n # definition. Its element in Mesa's custom\n # vk_android_native_buffer.xml, though, lists it as\n # supported='android-vendor' and fully defines the extension. We want\n # to skip the element in vk.xml.\n if ext_elem.attrib['supported'] == 'disabled':\n assert ext_name == 'VK_ANDROID_native_buffer'\n continue\n\n ext = ext_name_map[ext_name]\n ext.type = ext_elem.attrib['type']\n\n_TEMPLATE = COPYRIGHT + \"\"\"\n#include \"anv_private.h\"\n\n#include \"vk_util.h\"\n\n/* Convert the VK_USE_PLATFORM_* defines to booleans */\n%for platform in ['ANDROID', 'WAYLAND', 'XCB', 'XLIB']:\n#ifdef VK_USE_PLATFORM_${platform}_KHR\n# undef VK_USE_PLATFORM_${platform}_KHR\n# define VK_USE_PLATFORM_${platform}_KHR true\n#else\n# define VK_USE_PLATFORM_${platform}_KHR false\n#endif\n%endfor\n\n/* And ANDROID too */\n#ifdef ANDROID\n# undef ANDROID\n# define ANDROID true\n#else\n# define ANDROID false\n#endif\n\n#define ANV_HAS_SURFACE (VK_USE_PLATFORM_WAYLAND_KHR || \\\\\n VK_USE_PLATFORM_XCB_KHR || \\\\\n VK_USE_PLATFORM_XLIB_KHR)\n\nbool\nanv_instance_extension_supported(const char *name)\n{\n%for ext in instance_extensions:\n if (strcmp(name, \"${ext.name}\") == 0)\n return ${ext.enable};\n%endfor\n return false;\n}\n\nVkResult anv_EnumerateInstanceExtensionProperties(\n const char* pLayerName,\n uint32_t* pPropertyCount,\n VkExtensionProperties* pProperties)\n{\n VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);\n\n%for ext in instance_extensions:\n if (${ext.enable}) {\n vk_outarray_append(&out, prop) {\n *prop = (VkExtensionProperties) {\n .extensionName = \"${ext.name}\",\n .specVersion = ${ext.ext_version},\n };\n }\n }\n%endfor\n\n return vk_outarray_status(&out);\n}\n\nuint32_t\nanv_physical_device_api_version(struct anv_physical_device *dev)\n{\n return ${MAX_API_VERSION.c_vk_version()};\n}\n\nbool\nanv_physical_device_extension_supported(struct anv_physical_device *device,\n const char *name)\n{\n%for ext in device_extensions:\n if (strcmp(name, \"${ext.name}\") == 0)\n return ${ext.enable};\n%endfor\n return false;\n}\n\nVkResult anv_EnumerateDeviceExtensionProperties(\n VkPhysicalDevice physicalDevice,\n const char* pLayerName,\n uint32_t* pPropertyCount,\n VkExtensionProperties* pProperties)\n{\n ANV_FROM_HANDLE(anv_physical_device, device, physicalDevice);\n VK_OUTARRAY_MAKE(out, pProperties, pPropertyCount);\n (void)device;\n\n%for ext in device_extensions:\n if (${ext.enable}) {\n vk_outarray_append(&out, prop) {\n *prop = (VkExtensionProperties) {\n .extensionName = \"${ext.name}\",\n .specVersion = ${ext.ext_version},\n };\n }\n }\n%endfor\n\n return vk_outarray_status(&out);\n}\n\"\"\"\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--out', help='Output C file.', required=True)\n parser.add_argument('--xml',\n help='Vulkan API XML file.',\n required=True,\n action='append',\n dest='xml_files')\n args = parser.parse_args()\n\n for filename in args.xml_files:\n _init_exts_from_xml(filename)\n\n for ext in EXTENSIONS:\n assert ext.type == 'instance' or ext.type == 'device'\n\n template_env = {\n 'MAX_API_VERSION': MAX_API_VERSION,\n 'instance_extensions': [e for e in EXTENSIONS if e.type == 'instance'],\n 'device_extensions': [e for e in EXTENSIONS if e.type == 'device'],\n }\n\n from mako.template import Template\n\n with open(args.out, 'w') as f:\n f.write(Template(_TEMPLATE).render(**template_env))\n","sub_path":"src/intel/vulkan/anv_extensions.py","file_name":"anv_extensions.py","file_ext":"py","file_size_in_byte":10533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"135802820","text":"import numpy as np\nimport matplotlib.pyplot as plt\n# 在执行改程序前要依次执行1.Min_dis.py——>2.kNN.py——>3.SVM.py\nacc = np.loadtxt(r'.\\data\\acc.csv')\nx = np.arange(3)\n\nplt.bar(x, acc)\nplt.ylabel('accuracy')\nax = plt.gca()\nax.set_xticks(x)\nax.set_xticklabels(('Min_dist', 'KNN', 'SVM'))\n\nfor i, value in enumerate(acc):\n plt.text(i, value + 4.5, '%.2f%%' % value,ha='center', va='top')\nplt.show()\n","sub_path":"knn 最小距离 SVM 5份/9/4.plot_acc.py","file_name":"4.plot_acc.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"124882611","text":"#This module contains a procedure, which would create a file consisting of the researcher's name and his/her expertise. The file is in the format of RDF. In procedure, name.getName() and expertise.getExpertise() would be used.\n\n\nfrom rdflib import Graph,Namespace,URIRef,Literal,RDF,FOAF,BNode\nfrom bs4 import BeautifulSoup\nfrom requests import get\nimport random, time\nimport json\nfrom name import getName, mapName\nfrom expertise import getExpertiseFromMicrosoft, mapToWikidata\n\n\ncontext = { \"rdf\": \"http://www.w3.org/1999/02/22-rdf-syntax-ns#\",\n\"schema\": \"http://schema.org/\",\n\"name\": \"schema:name\",\n\"jobTitle\": \"schema:jobTitle\",\n\"knowsAbout\": \"schema:knowsAbout\",\n\"frequency\": \"schema:frequency\",\n\"identifier\": \"schema:identifier\",\n\"Person\": \"schema:Person\",\n\"DefinedTerm\": \"schema:DefinedTerm\",\n\"aiiso\": \"https://vocab.org/aiiso/schema#\",\n\"Faculty\": \"aiiso:Faculty\",\n\"Institute\": \"aiiso:Institute\",\n\"ResearchGroup\": \"aiiso:ResearchGroup\",\n\"roles\": \"https://vocab.org/aiiso-roles/schema#\",\n\"Researcher\": \"roles:Researcher\",\n\"Professor\": \"roles:Professor\",\n\"example\": \"https://example.org/people/\"}\n\ndef test():\n\n g = Graph()\n #g.parse(\"database2.rdf\")\n\n s = URIRef('abc')\n o = BNode()\n g.add((o,URIRef('age'),Literal('30')))\n g.add((s,URIRef(RDF.type),o))\n g.add((s,URIRef(FOAF.name),Literal('ruge')))\n\n o2 = BNode()\n g.add((o2,URIRef(FOAF.age),Literal('24')))\n g.add((s,URIRef(RDF.type),o2))\n print(\"RDF graph has been built\")\n\n str = g.serialize(format=\"json-ld\")\n framed = jsonld.frame(str, frame)\n #g.serialize(destination=\"demo_database.rdf\", format=\"xml\")\n\n\n\ndef addName():\n input = open(\"name_list.json\", \"r\", encoding='utf8') \n json_object = input.read()\n name_list = json.loads(json_object)\n\n g = Graph()\n #g.parse(\"database.json\")\n \n roles = Namespace(\"https://vocab.org/aiiso-roles/schema#\")\n aiiso = Namespace(\"https://vocab.org/aiiso/schema#\")\n example = Namespace(\"https://example.org/people/\")\n schema = Namespace(\"http://schema.org/\")\n \n g.bind(\"roles\", roles)\n g.bind(\"aiiso\", aiiso)\n g.bind(\"example\", example)\n g.bind(\"schema\", schema)\n \n count = 0\n for nameAndTitle in name_list:\n\n count += 1\n print(count)\n #time.sleep(0.1)\n \n #print(\"***********************************\")\n #print(\"***********************************\")\n name = nameAndTitle.split('&')[0]\n title = nameAndTitle.split('&')[1]\n faculty_list = nameAndTitle.split('&')[2].split(' | ')\n \n faculty = faculty_list[len(faculty_list)-1]\n institute = ''\n professorship = ''\n \n if len(faculty_list)>1:\n professorship = faculty_list[0]\n if len(faculty_list)>2:\n institute = faculty_list[len(faculty_list)-2]\n\n\n \n # print(faculty)\n # print(institute)\n # print(professorship)\n \n nameID = mapName(name)\n if nameID == '':\n nameID = example + '+'.join(name.split(' '))\n print(nameID)\n \n s = URIRef(nameID)\n g.add((s,schema.name,Literal(name)))\n g.add((s,RDF.type,schema.Person))\n g.add((s,schema.jobTitle,Literal(title)))\n g.add((s,aiiso.ResearchGroup,Literal(professorship)))\n g.add((s,aiiso.Institute,Literal(institute)))\n g.add((s,aiiso.Faculty,Literal(faculty)))\n\n print(\"RDF graph has been built\")\n\n g.serialize(destination=\"database.json\", context = context, format=\"json-ld\")\n #g.serialize(destination=\"demo_database.rdf\", format=\"xml\")\n \n input.close()\n\n\ndef addExpertise():\n g = Graph()\n g.parse(\"database3.json\",format=\"json-ld\")\n\n roles = Namespace(\"https://vocab.org/aiiso-roles/schema#\")\n aiiso = Namespace(\"https://vocab.org/aiiso/schema#\")\n example = Namespace(\"https://example.org/people/\")\n schema = Namespace(\"http://schema.org/\")\n \n g.bind(\"roles\", roles)\n g.bind(\"aiiso\", aiiso)\n g.bind(\"example\", example)\n g.bind(\"schema\", schema)\n \n input = open(\"expertise_dict.json\", \"r\", encoding='utf8') \n json_object = input.read()\n exp_dict = json.loads(json_object)\n \n for key in exp_dict.keys():\n print(key)\n \n exp = json.loads(exp_dict[key])\n if len(exp['histograms'][0]['histogram']) == 0:\n continue\n\n name = key.split('&')[0]\n\n professorship = key.split('&')[2].split('|')[0].strip()\n\n for s, p, o in g.triples((None, schema.name, Literal(name))):\n \n if str(g.value(s,aiiso.ResearchGroup)) != professorship:\n continue\n \n print(\"***********************************\")\n print(\"***********************************\")\n \n exp_list = exp['histograms'][0]['histogram']\n \n \n for expertise in exp_list:\n exp_name = expertise['value']\n exp_count = expertise['count']\n\n time.sleep(1)\n \n exp_id = mapToWikidata(exp_name)\n \n if exp_id == '':\n continue\n \n g.add((URIRef(exp_id),RDF.type,schema.DefinedTerm))\n g.add((URIRef(exp_id),schema.name,Literal(exp_name)))\n \n \n bn = BNode()\n g.add((bn,schema.identifier,URIRef(exp_id)))\n g.add((bn,schema.frequency,Literal(exp_count)))\n \n g.add((s,schema.knowsAbout,bn))\n \n g.serialize(destination=\"database.json\", context = context, format=\"json-ld\")\n\n \n\n\ndef jsonToXML():\n g = Graph()\n g.parse(\"database.json\",format=\"json-ld\")\n\n roles = Namespace(\"https://vocab.org/aiiso-roles/schema#\")\n aiiso = Namespace(\"https://vocab.org/aiiso/schema#\")\n example = Namespace(\"https://example.org/people/\")\n schema = Namespace(\"http://schema.org/\")\n \n g.bind(\"roles\", roles)\n g.bind(\"aiiso\", aiiso)\n g.bind(\"example\", example)\n g.bind(\"schema\", schema)\n \n\n g.serialize(destination=\"database.xml\", format=\"xml\")\n\n\n\n#addName()\n#addExpertise()\njsonToXML()\n\n","sub_path":"researchee/RDF.py","file_name":"RDF.py","file_ext":"py","file_size_in_byte":6221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"18480675","text":"# -*- coding: utf-8 -*-\n##############################################################################\n# \n# OpenERP, Open Source Enterprise Management Solution\n# Copyright (C) 2014 Net Skill Group\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 dateutil.relativedelta import relativedelta\nfrom datetime import datetime, date, timedelta\nfrom odoo.tools import DEFAULT_SERVER_DATE_FORMAT\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import UserError\n#from openerp import exceptions\n\nimport openerp.addons.decimal_precision as dp\n\nclass AccountInvoice(models.Model):\n _inherit = 'account.invoice'\n\n customer_reference = fields.Char(string='Customer reference')\n# def _get_month(self, index):\n# return [\n# _('January'), _('February'), _('March'), _('April'), _('May'), _('June'),\n# _('July'), _('August'), _('September'), _('October'), _('November'), _('December')\n# ][index]\n# \n# @api.model\n# def target_period_groups(self,present_ids,domain,**kwargs): \n# \n# vals=[] \n# folded = {}\n# date_ref = datetime.strptime(fields.Date.today(), DEFAULT_SERVER_DATE_FORMAT) \n# \n# last_period = present_ids[-1]\n# present_ids.append(last_period+1)\n# \n# for period in self.env['date.range'].browse(present_ids):\n# period_date = datetime.strptime(period.date_end, DEFAULT_SERVER_DATE_FORMAT)\n# period_title = self._get_month(period_date.month-1) + period_date.strftime(\" - %Y\")\n# column_title = (period.id,period_title)\n# vals.append(column_title)\n# interval_period = (period_date.year - date_ref.year) * 12 + (period_date.month - date_ref.month)\n# if (interval_period >= 0 and interval_period <= 3) :\n# folded[period.id]=False\n# else:\n# folded[period.id]=True\n# return vals,folded\n\n\n# -------------------------------------------------\n\n @api.multi\n def action_invoice_intercompany(self):\n \"\"\"\n Create a invoice to the other company \n :returns: list of created invoices\n \"\"\"\n \n inv_obj = self.env['account.invoice']\n precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')\n invoices = {}\n\n #take the first company not except actual invoice company\n company = self.env['res.company'].search([('id','!=',self.company_id.id)],limit=1) \n\n #sale journal of the company\n journal_id = self.env['account.journal'].search([('company_id','=',company.id),('type','=','sale')],limit=1) \n\n #receivable account of the company\n receivable_id = self.env['ir.property'].with_context(force_company=company.id).get('property_account_receivable_id', 'res.partner')\n\n #fiscal position\n company_fiscal_position = self.with_context(force_company=company.id).company_id.partner_id.property_account_position_id.id\n partner_fiscal_position = self.env['account.fiscal.position'].browse(company_fiscal_position) \n\n #actual invoice informations\n invoice_vals = {\n 'name': self.name,\n 'origin': self.origin,\n 'type': 'out_invoice',\n 'reference': self.reference or self.name,\n 'customer_reference': self.customer_reference,\n 'partner_id': self.company_id.partner_id.id, \n 'journal_id': journal_id.id,\n 'currency_id': self.currency_id.id,\n 'comment': self.comment,\n 'company_id': company.id,\n 'account_id': receivable_id.id,\n 'payment_term_id': self.payment_term_id.id,\n 'fiscal_position_id': company_fiscal_position,\n 'user_id': self.user_id and self.user_id.id,\n 'team_id': self.team_id.id,\n 'origin_invoice_id':self.id,\n }\n \n invoice = inv_obj.create(invoice_vals)\n\n # default revenue account\n invoice_line_account = self.env['account.account'].search([('company_id','=', company.id),('user_type_id', '=', self.env.ref('account.data_account_type_revenue').id)], limit=1).id\n\n # default tax code\n ir_values = self.env['ir.values']\n list_taxes_id = ir_values.get_default('product.template', 'taxes_id', company_id = company.id)\n list_taxes_obj = self.env['account.tax'].with_context(force_company=company.id).search([('id', 'in',list_taxes_id)])\n \n if partner_fiscal_position:\n invoice_tax = partner_fiscal_position.with_context(force_company=company.id).map_tax(list_taxes_obj).ids\n else:\n invoice_tax = list_taxes_id\n \n for origin_invoice_line in self.invoice_line_ids:\n self.env['account.invoice.line'].create({\n 'quantity': origin_invoice_line.quantity,\n 'price_unit': origin_invoice_line.price_unit,\n #'init_price_unit':post_amount,\n 'invoice_id': invoice.id,\n 'name': origin_invoice_line.name,\n 'origin': origin_invoice_line.origin,\n 'account_id': invoice_line_account, \n 'view_in_pdf':origin_invoice_line.view_in_pdf, \n 'invoice_line_tax_ids': [(6,0, invoice_tax)],\n })\n\n #update tax\n invoice.compute_taxes()\n\n view_id = self.env['ir.ui.view'].search([('name','=','macq.invoice.account.form')], limit=1).id\n return {\n 'name': 'Invoice',\n 'res_id': invoice.id,\n 'res_model': 'account.invoice',\n 'view_id': view_id,\n 'type': 'ir.actions.act_window',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'target': 'new',\n 'flags': {'form': {'action_buttons': True}}, \n 'nodestroy':True,\n #'domain':domain,\n 'context': self.env.context,\n } \n\n\n\n @api.depends('reference')\n def _reference_so_id(self):\n for invoice in self:\n reference_so_id = False\n if invoice.reference:\n so_ids = self.env['sale.order'].search([('name','=',invoice.reference)], limit=1)\n if so_ids:\n reference_so_id = so_ids.id\n invoice.update({'reference_so_id': reference_so_id})\n\n \n @api.onchange('target_period_invoice')\n def on_change_target_period(self):\n self.ensure_one()\n if self.target_period_invoice:\n present_date = datetime.strptime(fields.Date.today(), DEFAULT_SERVER_DATE_FORMAT)\n end_period_date = datetime.strptime(self.target_period_invoice.date_end, DEFAULT_SERVER_DATE_FORMAT)\n month_from_present =(end_period_date.year - present_date.year) * 12 + (end_period_date.month - present_date.month)\n \n if month_from_present < 0:\n self.target_column_invoice = self.env['target.column'].search([('month_interval','=',-1)],limit=1)\n elif month_from_present >3: \n self.target_column_invoice = self.env['target.column'].search([('month_interval','=',3)],limit=1)\n else :\n self.target_column_invoice = self.env['target.column'].search([('month_interval','=',month_from_present)],limit=1)\n \n\n @api.model \n def refresh_target_column(self):\n for invoice in self.env['account.invoice'].search([('state','=','draft')]):\n if invoice.target_period_invoice:\n present_date = datetime.strptime(fields.Date.today(), DEFAULT_SERVER_DATE_FORMAT)\n end_period_date = datetime.strptime(invoice.target_period_invoice.date_end, DEFAULT_SERVER_DATE_FORMAT)\n month_from_present =(end_period_date.year - present_date.year) * 12 + (end_period_date.month - present_date.month)\n \n if month_from_present < 0:\n target_id = self.env['target.column'].search([('month_interval','=',-1)])[0]\n \n invoice.write({'target_column_invoice': target_id.id})\n elif month_from_present >3:\n target_id = self.env['target.column'].search([('month_interval','=',3)])[0]\n invoice.write({'target_column_invoice': target_id.id})\n else :\n target_id = self.env['target.column'].search([('month_interval','=',month_from_present)])[0]\n invoice.write({'target_column_invoice': target_id.id})\n\n\n @api.onchange('date_invoice')\n # to update target invoice\n def on_change_date_invoice(self):\n self.ensure_one()\n \n if self.date_invoice:\n str_date = self.date_invoice\n search_begin=datetime.strptime(str_date[0:8]+'01', DEFAULT_SERVER_DATE_FORMAT)\n search_end= search_begin + relativedelta(months=+1) + relativedelta(days=-1) \n \n find_period = self.env['date.range'].search([('date_start','>=',search_begin),('date_end','<=',search_end)],limit=1)\n #if period doesnt exist create it\n if not find_period:\n periode_id = self.env['date.range'].create({'type_name':'Month',\n 'type_id':1,\n 'company_id':self.company_id.id,\n 'date_start': search_begin,\n 'date_end':search_end,\n 'name':search_end.strftime('%Y-%m')\n })\n else : \n periode_id=find_period.id\n \n self.target_period_invoice = periode_id\n\n \n @api.multi\n def write(self, vals,refresh_only=False):\n \n #Update via form invoice\n update_form_invoice = vals.get('invoice_line_ids', False)\n if update_form_invoice:\n refresh_only = True\n \n if not refresh_only:\n #si update target_period_invoice via kanban only for draft invoice\n #if vals.get('target_period_invoice', False) and not vals.get('date_invoice', False) and self.state=='draft' :\n if vals.get('target_period_invoice', False) and self.state=='draft':\n target_period = self.env['date.range'].browse(vals.get('target_period_invoice', False))\n vals.update ({'date_invoice' : target_period.date_start})\n\n #no update for non draft invoice\n if vals.get('target_period_invoice', False) and self.state!='draft':\n raise UserError(_(\"You can only move draft invoices\"))\n# if (vals.get('target_column_invoice', False) and not vals.get('target_period_invoice', False)): \n# #si update target_column_invoice via kanban\n# present_date = datetime.strptime(fields.Date.today(), DEFAULT_SERVER_DATE_FORMAT)\n# \n# target_column_id = vals.get('target_column_invoice', False)\n# target_column_obj = self.env['target.column'].browse(target_column_id)\n# \n# present_pivot_date = present_date + relativedelta(months=target_column_obj.month_interval)\n# present_pivot_date = present_pivot_date.replace(day=1)\n# \n# target_period = self.env['date.range'].search([('date_start','=',present_pivot_date)],limit=1)\n# \n# vals.update ({'target_period_invoice' : target_period.id})\n \n return super(AccountInvoice, self).write(vals)\n\n @api.one\n @api.depends('intercompany_ids','intercompany_ids.amount_untaxed_signed','intercompany_ids.invoice_line_ids')\n def _intercompany_invoiced(self):\n \"\"\"\n Compute the intercompany invoiced amount\n \"\"\"\n inter_amount=0\n \n for invoice in self.intercompany_ids:\n inter_amount = inter_amount + invoice.amount_untaxed_signed\n self.update({\n 'intercompany_amount': inter_amount,\n })\n\n\n @api.multi\n # FOR INVOICE COPY THE COLOR IS INITIALIZED AT 0\n def copy(self, default=None):\n if default is None:\n default = {}\n self.ensure_one()\n default['color_type_id'] = 0\n return super(AccountInvoice, self).copy(default=default)\n\n# \n# _group_by_full = {\n# 'target_period_invoice': target_period_groups, \n# }\n# \n target_period_invoice = fields.Many2one('date.range', string='Target Invoice Period') \n target_column_invoice = fields.Many2one('target.column', string='Kanban Column')\n need_invoice_proposal = fields.Boolean(string='Customer need invoice proposal',related=\"partner_id.need_invoice_proposal\")\n IP_send = fields.Date(string='IP Date send') \n IP_receive = fields.Date(string='IP Date receive') \n IP_comment = fields.Char(string='IP comment') \n IP_status = fields.Selection([('none','None'),('send','Send'),('approve','Approve'),('refuse','Refuse')],default='none')\n color_type_id = fields.Char(string=\"color\",help=\"Choose your color\",default=0) \n reference_so_id = fields.Many2one('sale.order', string='Reference SO', compute='_reference_so_id', store=True) \n project_id= fields.Many2one('macq.project', related='reference_so_id.macq_project_id', string='Dossier') \n project_description= fields.Char('Dossier description', related='reference_so_id.macq_project_id.description') \n so_description= fields.Char('SO description', related='reference_so_id.budget_description') \n project_pm_id = fields.Many2one('res.users', related='reference_so_id.macq_project_id.pm_id', string='Project manager') \n project_assistant_id=fields.Many2one('res.users', related='reference_so_id.macq_project_id.assistant_id',string='Assistant')\n origin_invoice_id= fields.Many2one('account.invoice', string='Origin Invoice') \n intercompany_ids = fields.One2many(comodel_name='account.invoice', inverse_name='origin_invoice_id') \n intercompany_amount = fields.Float(compute='_intercompany_invoiced',string='intercompany invoiced amount',store=False)\n\n # SURCHARGE TO PASS THE ACCOUNT FROM PURCHASE ORDER\n def _prepare_invoice_line_from_po_line(self, line):\n \n odoo_data = super(AccountInvoice, self)._prepare_invoice_line_from_po_line(line)\n \n if line.account_id: \n odoo_data['account_id'] = line.account_id\n \n return odoo_data\n\n\n\nclass AccountInvoiceLine(models.Model):\n _inherit = \"account.invoice.line\"\n \n customer_reference = fields.Char(related='invoice_id.customer_reference', string='Customer reference')\n\n","sub_path":"Macq_Website/macq_account/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":15669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"609882682","text":"# /usr/bin/env python\n# coding=utf-8\n\"\"\"Dataloader\"\"\"\n\nimport os\n\nimport torch\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Dataset\n# from transformers import BertTokenizer\nfrom NEZHA.tokenization import BertTokenizer\n\nfrom dataloader_utils import read_examples, convert_examples_to_features\n\n\nclass FeatureDataset(Dataset):\n \"\"\"Pytorch Dataset for InputFeatures\n \"\"\"\n\n def __init__(self, features):\n self.features = features\n\n def __len__(self) -> int:\n return len(self.features)\n\n def __getitem__(self, index):\n return self.features[index]\n\n\nclass NERDataLoader(object):\n \"\"\"dataloader\n \"\"\"\n\n def __init__(self, params):\n self.params = params\n\n self.train_batch_size = params.train_batch_size\n self.val_batch_size = params.val_batch_size\n self.test_batch_size = params.test_batch_size\n\n self.data_dir = params.data_dir\n self.max_seq_length = params.max_seq_length\n self.tokenizer = BertTokenizer(vocab_file=os.path.join(params.bert_model_dir, 'vocab.txt'),\n do_lower_case=True)\n # 保存数据(Bool)\n self.data_cache = params.data_cache\n\n @staticmethod\n def collate_fn(features):\n \"\"\"将InputFeatures转换为Tensor\n Args:\n features (List[InputFeatures])\n Returns:\n tensors (List[Tensors])\n \"\"\"\n input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)\n input_mask = torch.tensor([f.input_mask for f in features], dtype=torch.long)\n # gold_start = torch.tensor([f.start_position for f in features], dtype=torch.long)\n # gold_end = torch.tensor([f.end_position for f in features], dtype=torch.long)\n\n # cascade\n cls_label = torch.tensor([f.cls_label for f in features], dtype=torch.long)\n random_cls_ids = torch.tensor([f.random_cls_id for f in features], dtype=torch.long)\n random_start_posis = torch.tensor([f.random_start_posi for f in features], dtype=torch.long)\n random_end_posis = torch.tensor([f.random_end_posi for f in features], dtype=torch.long)\n tags = [f.tag for f in features]\n\n # use to split text\n split_to_ori = torch.tensor([f.split_to_original_id for f in features], dtype=torch.long)\n example_ids = torch.tensor([f.example_id for f in features], dtype=torch.long)\n tensors = [input_ids, input_mask, tags, cls_label, random_cls_ids, random_start_posis,\n random_end_posis, split_to_ori, example_ids]\n return tensors\n\n def get_features(self, data_sign):\n \"\"\"convert InputExamples to InputFeatures\n :param data_sign: 'train', 'val' or 'test'\n :return: features (List[InputFeatures]):\n \"\"\"\n print(\"=*=\" * 10)\n print(\"Loading {} data...\".format(data_sign))\n # get examples\n if data_sign in (\"train\", \"val\", \"test\", \"pseudo\"):\n examples = read_examples(os.path.join(self.data_dir, f'{data_sign}.data'))\n else:\n raise ValueError(\"please notice that the data can only be train/val/test !!\")\n\n features = convert_examples_to_features(self.params, examples, self.tokenizer, greed_split=False)\n return features\n\n def get_dataloader(self, data_sign=\"train\"):\n \"\"\"construct dataloader\n :param data_sign: 'train', 'val' or 'test'\n \"\"\"\n # InputExamples to InputFeatures\n features = self.get_features(data_sign=data_sign)\n dataset = FeatureDataset(features)\n print(f\"{len(features)} {data_sign} data loaded!\")\n print(\"=*=\" * 10)\n\n # construct dataloader\n # RandomSampler(dataset) or SequentialSampler(dataset)\n if data_sign == \"train\":\n datasampler = RandomSampler(dataset)\n dataloader = DataLoader(dataset, sampler=datasampler, batch_size=self.train_batch_size,\n collate_fn=self.collate_fn)\n elif data_sign == \"val\":\n datasampler = SequentialSampler(dataset)\n dataloader = DataLoader(dataset, sampler=datasampler, batch_size=self.val_batch_size,\n collate_fn=self.collate_fn)\n elif data_sign in (\"test\", \"pseudo\"):\n datasampler = SequentialSampler(dataset)\n dataloader = DataLoader(dataset, sampler=datasampler, batch_size=self.test_batch_size,\n collate_fn=self.collate_fn)\n else:\n raise ValueError(\"please notice that the data can only be train/val/test !!\")\n return dataloader\n\n\nif __name__ == '__main__':\n from utils import Params\n\n params = Params()\n datalodaer = NERDataLoader(params)\n feats = datalodaer.get_dataloader(data_sign='test')\n print(len(next(iter(feats))))\n","sub_path":"ee_joint_pointer/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":4860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"206696502","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 30 13:03:23 2020\n\n@author: briardoty\n\"\"\"\nimport math\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\ntry:\n from .ActivationFunctions import (Renlu, Swish, SanityCheck, \n Heaviside, Sigfreud, HSwish, Tanhe)\nexcept:\n from ActivationFunctions import (Renlu, Swish, SanityCheck, \n Heaviside, Sigfreud, HSwish, Tanhe)\n\n\n# map act fn names to fns themselves\nact_fn_dict = {\n \"relu\": torch.relu,\n \"tanh\": torch.tanh,\n \"sigmoid\": torch.sigmoid,\n \"sigfreud\": Sigfreud,\n \"tanhe\": Tanhe,\n \"renlu\": Renlu,\n \"swish\": Swish,\n \"sanityCheck\": SanityCheck,\n \"heaviside\": Heaviside\n}\n\ndef generate_masks(n_features, n_fns, n_repeat):\n \"\"\"\n Generates a set of \"masks\" to apply each activation function on.\n\n Args:\n n_features (int): Number of input features.\n n_fns (int): Number of activation fns.\n n_repeat (int): Number of times to repeat each activation fn across layer.\n\n Returns:\n masks (list[list[int]]): List of \"masks\" to be applied for each\n activation function.\n\n \"\"\"\n masks = [[] for _ in range(n_fns)]\n \n for i in range(n_features):\n # determine which mask this feature belongs to\n mask_idx = math.floor(i / n_repeat) % n_fns\n \n # add this feature to that mask\n masks[mask_idx].append(i)\n \n return masks\n\ndef get_activation_fns(act_fn_names, act_fn_params):\n \"\"\"\n Builds list of torch activation functions for use in this layer.\n\n Args:\n act_fn_names (list): List of act fn names.\n act_fn_params (list): List of act fn params.\n\n Returns:\n act_fns (list): List of torch act fns.\n\n \"\"\"\n act_fns = []\n \n for n, p in zip(act_fn_names, act_fn_params):\n if p is None or p == \"None\":\n act_fns.append(act_fn_dict[n])\n else:\n act_fns.append(act_fn_dict[n](p))\n \n return act_fns\n\nclass MixedActivationLayer(nn.Module):\n \n def __init__(self, n_features, n_repeat, act_fn_names, act_fn_params, \n verbose=False):\n \n super(MixedActivationLayer, self).__init__()\n \n self.n_features = n_features\n self.act_fns = get_activation_fns(act_fn_names, act_fn_params)\n print(\"Initialized MixedActivationLayer with the following activation\"\n + f\"functions: {self.act_fns}\")\n self.masks = generate_masks(n_features, len(self.act_fns), n_repeat)\n \n self.verbose = verbose\n \n def __repr__(self):\n return f\"MixedActivationLayer(n_features={self.n_features}, act_fns={self.act_fns})\"\n\n def forward(self, input_tensor):\n \n output = Variable(input_tensor.new(input_tensor.size()))\n \n for act_fn, mask in zip(self.act_fns, self.masks):\n output[:,mask] = act_fn(input_tensor[:,mask])\n \n if self.verbose:\n print(f\"Input: {input_tensor}\")\n print(f\"Output: {output}\")\n \n return output\n \n \n\n\n\n\n\n\n\n","sub_path":"modules/MixedActivationLayer.py","file_name":"MixedActivationLayer.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"560854588","text":"class Solution:\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n dp = [[0]*n for _ in range(m)]\n for i in range(m):\n dp[i][n-1] = 1\n for i in range(n):\n dp[m-1][i] = 1\n for i in reversed(range(m-1)):\n for j in reversed(range(n-1)):\n dp[i][j] = dp[i+1][j]+dp[i][j+1]\n return dp[0][0]","sub_path":"62.py","file_name":"62.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"8136639","text":"\"\"\"Representaton of an extended property of a device.\"\"\"\nfrom .address import Address\nfrom .device_flag import DeviceFlagBase\n\nRAMP_RATE = \"ramp_rate\"\nX10_HOUSE = \"x10_house\"\nX10_UNIT = \"x10_unit\"\nLED_DIMMING = \"led_dimming\"\nON_LEVEL = \"on_level\"\nAWAKE_INTERVAL = \"awake_interval\"\nSLEEP_INTERVAL = \"sleep_interval\"\nBROADCAST_NUMBER = \"broadcast_number\"\nTRIGGER_GROUP_MASK = \"trigger_group_mask\"\nLSB_OF_SLEEP_INTERVAL = \"lsb_of_sleep_interval\"\nAPP_RETRIES = \"app_retries\"\nCONFIG = \"config\"\nBATTERY_LEVEL = \"battery_level\"\nDATABASE_DELTA = \"database_delta\"\nSENSOR_STATUS = \"sensor_status\"\nHEARBEAT_INTERVAL = \"heartbeat_interval\"\nBATTERY_LOW_LEVEL = \"battery_low_level\"\nLED_BRIGHTNESS = \"led_brightness\"\nMOTION_TIMEOUT = \"motion_timeout\"\nLIGHT_SENSITIVITY = \"light_sensitivity\"\nHARDWARE_TIMEOUT = \"hardware_timeout\"\nHARDWARE_LIGHT_SENSITIVITY = \"hardware_light_sensitivity\"\nAMBIENT_LIGHT_INTENSITY = \"ambient_light_intensity\"\nDELAY = \"delay\"\nPRESCALER = \"prescaler\"\nDURATION_HIGH = \"duration_high\"\nDURATION_LOW = \"duration_low\"\nON_MASK = \"on_mask\"\nOFF_MASK = \"off_mask\"\nNON_TOGGLE_MASK = \"non_toggle_mask\"\nNON_TOGGLE_ON_OFF_MASK = \"non_toggle_on_off_mask\"\nBACKLIGHT = \"backlight\"\nCHANGE_DELAY = \"change_delay\"\nMASTER = \"master\"\nHUMIDITY_HIGH = \"humidity_high\"\nHUMIDITY_LOW = \"humidity_low\"\nTEMP_OFFSET = \"temp_offset\"\nTEMP_OFFSET_EXTERNAL = \"temp_offset_external\"\nHUMIDITY_OFFSET = \"humidity_offset\"\n\n\nclass ExtendedProperty(DeviceFlagBase):\n \"\"\"Representation of an extended property of a device.\"\"\"\n\n def __init__(\n self, address, name, flag_type: type, is_reversed=False, is_read_only=False\n ):\n \"\"\"Init the ExtendedProperty class.\"\"\"\n self._address = Address(address)\n topic = \"{}.property.{}\".format(self._address.id, name)\n super().__init__(topic, name, flag_type, is_reversed, is_read_only)\n","sub_path":"pyinsteon/extended_property.py","file_name":"extended_property.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"614378292","text":"# Copyright 2021 DeepMind Technologies Limited\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\"\"\"Utility functions for building Docker images.\"\"\"\nimport os\nimport pathlib\nimport shutil\nimport subprocess\nimport sys\nfrom typing import Optional\n\nfrom absl import logging\nimport docker\nfrom docker.utils import utils as docker_utils\nimport humanize\nimport termcolor\n\n\ndef prepare_directory(destination_directory: str, source_directory: str,\n project_name: str, entrypoint_file: str,\n dockerfile: str) -> None:\n \"\"\"Stage all inputs into the destination directory.\n\n Args:\n destination_directory: The directory to copy files to.\n source_directory: The directory to copy files from.\n project_name: The name of the folder inside destination_directory/ that\n source_directory/ files will be copied to.\n entrypoint_file: The file path of entrypoint.sh.\n dockerfile: The file path of Dockerfile.\n \"\"\"\n source_path = pathlib.Path(source_directory)\n size = sum(f.stat().st_size for f in source_path.glob('**/*') if f.is_file())\n print(f'Size of Docker input: {humanize.naturalsize(size)}')\n if size > 200 * 10**6:\n print(\n termcolor.colored(\n 'You are trying to pack over 200MB into a Docker image. '\n 'Large images negatively impact build times',\n color='magenta'))\n shutil.copytree(source_directory,\n os.path.join(destination_directory, project_name))\n shutil.copyfile(dockerfile, os.path.join(destination_directory, 'Dockerfile'))\n shutil.copyfile(entrypoint_file,\n os.path.join(destination_directory, 'entrypoint.sh'))\n\n\ndef build_docker_image(image: str,\n directory: str,\n dockerfile: Optional[str] = None,\n use_docker_command: bool = True,\n show_docker_command_progress: bool = False) -> str:\n \"\"\"Builds a Docker image locally.\"\"\"\n logging.info('Building Docker image')\n docker_client = docker.from_env()\n if not dockerfile:\n dockerfile = os.path.join(directory, 'Dockerfile')\n if use_docker_command:\n _build_image_with_docker_command(docker_client, directory, image,\n dockerfile, show_docker_command_progress)\n else:\n _build_image_with_python_client(docker_client, directory, image, dockerfile)\n logging.info('Building docker image: Done')\n return image\n\n\ndef push_docker_image(image: str) -> str:\n \"\"\"Pushes a Docker image to the designated repository.\"\"\"\n docker_client = docker.from_env()\n repository, tag = docker_utils.parse_repository_tag(image)\n push = docker_client.images.push(repository=repository, tag=tag)\n logging.info(push)\n if not isinstance(push, str) or '\"Digest\":' not in push:\n raise RuntimeError(\n 'Expected docker push to return a string with `status: Pushed` and a '\n 'Digest. This is probably a temporary issue with --build_locally and '\n 'you should try again')\n print('Your image URI is:', termcolor.colored(image, color='blue'))\n return image\n\n\ndef _build_image_with_docker_command(client: docker.DockerClient,\n path: str,\n image_tag: str,\n dockerfile: str,\n progress: bool = False) -> None:\n \"\"\"Builds a Docker image by calling `docker build` within a subprocess.\"\"\"\n version = client.version()['Version']\n [major, minor] = version.split('.')[:2]\n if float(f'{major}.{minor}') < 20.10:\n # docker buildx requires docker 20.10.\n raise RuntimeError('XCloud requires Docker Engine version 20.10+.')\n command = [\n 'docker', 'buildx', 'build', '-t', image_tag, '-f', dockerfile, path\n ]\n\n # Adding flags to show progress and disabling cache.\n # Caching prevents actual commands in layer from executing.\n # This is turn makes displaying progress redundant.\n if progress:\n command[2:2] = ['--progress', 'plain', '--no-cache']\n\n subprocess.run(command, check=True, env={'DOCKER_BUILDKIT': '1'})\n\n\ndef _build_image_with_python_client(client: docker.DockerClient, path: str,\n image_tag: str, dockerfile: str) -> None:\n \"\"\"Builds a Docker image by calling the Docker Python client.\"\"\"\n try:\n # The `tag=` arg refers to the full repository:tag image name.\n _, logs = client.images.build(\n path=path, tag=image_tag, dockerfile=dockerfile)\n except docker.errors.BuildError as error:\n for log in error.build_log:\n print(log.get('stream', ''), end='', file=sys.stderr)\n raise error\n for log in logs:\n print(log.get('stream', ''), end='')\n","sub_path":"xmanager/cloud/docker_lib.py","file_name":"docker_lib.py","file_ext":"py","file_size_in_byte":5199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"522011235","text":"# Copyright 2018 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport json\nimport logging\nimport urllib\n\nimport httplib2\n\nfrom py_utils import retry_util # pylint: disable=import-error\n\n\nclass RequestError(OSError):\n \"\"\"Exception class for errors while making a request.\"\"\"\n def __init__(self, request, response, content):\n self.request = request\n self.response = response\n self.content = content\n super(RequestError, self).__init__(\n '%s returned HTTP Error %d: %s' % (\n self.request, self.response.status, self.error_message))\n\n def __reduce__(self):\n # Method needed to make the exception pickleable [1], otherwise it causes\n # the mutliprocess pool to hang when raised by a worker [2].\n # [1]: https://stackoverflow.com/a/36342588\n # [2]: https://github.com/uqfoundation/multiprocess/issues/33\n return (type(self), (self.request, self.response, self.content))\n\n @property\n def json(self):\n try:\n return json.loads(self.content)\n except StandardError:\n return None\n\n @property\n def error_message(self):\n try:\n # Try to find error message within json content.\n return self.json['error']\n except StandardError:\n # Otherwise fall back to entire content itself.\n return self.content\n\n\nclass ClientError(RequestError):\n \"\"\"Exception for 4xx HTTP client errors.\"\"\"\n pass\n\n\nclass ServerError(RequestError):\n \"\"\"Exception for 5xx HTTP server errors.\"\"\"\n pass\n\n\ndef BuildRequestError(request, response, content):\n \"\"\"Build the correct RequestError depending on the response status.\"\"\"\n if response['status'].startswith('4'):\n error = ClientError\n elif response['status'].startswith('5'):\n error = ServerError\n else: # Fall back to the base class.\n error = RequestError\n return error(request, response, content)\n\n\n@retry_util.RetryOnException(ServerError, retries=3)\ndef Request(url, params=None, method='GET', credentials=None, retries=None):\n del retries # Handled by the decorator.\n\n if params:\n url = '%s?%s' % (url, urllib.urlencode(params))\n\n http = httplib2.Http()\n if credentials is not None:\n if credentials.access_token_expired:\n credentials.refresh(http)\n http = credentials.authorize(http)\n\n logging.info('Making API request: %s', url)\n response, content = http.request(\n url, method=method, headers={'Content-length': '0'})\n if response.status != 200:\n raise BuildRequestError(url, response, content)\n return content\n","sub_path":"third_party/catapult/experimental/soundwave/services/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"41861409","text":"from safemaps.models import Location\n\n\nclass LocationHelper:\n\n @classmethod\n def get_locations_within_coordinates(cls, latitude_min,\n latitude_max, longitude_min,\n longitude_max):\n \"\"\"\n @summary: Get locations that have Latitude and Longitude co-ordinates\n in between given ranges.\n @param latitude_min: Minimum value of latitude\n @type latitude_min: float\n @param latitude_max: Maximum value of latitude\n @type latitude_max: float\n @param longitude_min: Minimum value of longitude\n @type longitude_min: float\n @param longitude_max: Maximum value of longitude\n @type longitude_max: float\n @return: a list of Location objects\n \"\"\"\n matching_locations = Location.objects.filter(latitude__gte=latitude_min,\n latitude__lte=latitude_max,\n longitude__gte=longitude_min,\n longitude__lte=longitude_max)\n return matching_locations\n\n @classmethod\n def get_locations_within_latitudes(cls, latitude_min,\n latitude_max):\n \"\"\"\n @summary: Get locations that have Latitude co-ordinates\n in between given range.\n @param latitude_min: Minimum value of latitude\n @type latitude_min: float\n @param latitude_max: Maximum value of latitude\n @type latitude_max: float\n \"\"\"\n matching_locations = Location.objects.filter(latitude__gte=latitude_min,\n latitude__lte=latitude_max)\n return matching_locations\n","sub_path":"maps_site/safemaps/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"268758607","text":"import sys\nN = int(input())\nA = sorted(list(map(int,input().split())))\n\nmn = A[0]\nmx = A[-1]\nif N ==2:\n print(A[1] - A[0])\n print(A[1],A[0])\n sys.exit()\nope = []\nfor a in A[1:-1]:\n if a <=0:\n ope.append([mx, a])\n mx -= a\n else:\n ope.append([mn, a])\n mn -= a\nope.append([mx,mn])\nprint(mx-mn)\nfor o in ope:\n print(o[0],o[1])","sub_path":"AtCoder/Other/Diverta2019_2/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"569960219","text":"# 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 \n# \n# 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 \n# \n# 现在考虑网格中有障碍物。那么从左上角到右下角将会有多少条不同的路径? \n# \n# \n# \n# 网格中的障碍物和空位置分别用 1 和 0 来表示。 \n# \n# 说明:m 和 n 的值均不超过 100。 \n# \n# 示例 1: \n# \n# 输入:\n# [\n#   [0,0,0],\n#   [0,1,0],\n#   [0,0,0]\n# ]\n# 输出: 2\n# 解释:\n# 3x3 网格的正中间有一个障碍物。\n# 从左上角到右下角一共有 2 条不同的路径:\n# 1. 向右 -> 向右 -> 向下 -> 向下\n# 2. 向下 -> 向下 -> 向右 -> 向右\n# \n# Related Topics 数组 动态规划\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution(object):\n def uniquePathsWithObstacles(self, obstacleGrid):\n \"\"\"\n :type obstacleGrid: List[List[int]]\n :rtype: int\n \"\"\"\n m = len(obstacleGrid)\n n = len(obstacleGrid[0])\n dp = [[0] * n for i in range(m)]\n for i in range(m):\n for j in range(n):\n if not obstacleGrid[i][j]:\n if i == j == 0:\n dp[i][j] = 1\n elif i != 0 or j != 0:\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n return dp[-1][-1]\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week09/Assignment/[63]不同路径 II.py","file_name":"[63]不同路径 II.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"215626121","text":"# _*_ coding:utf-8 _*_\n\"\"\"\nAPP初始化\n1、启动APP\n2、退出APP\n3、重启APP\n\n封装方法:\n1、滑动查找方法\n2、。。。。\n\"\"\"\nimport yaml\nfrom appium import webdriver\n\nfrom UI_Framework.Base.BaseClass import BaseClass\nfrom UI_Framework.Page.MainPage import MainPage\n\n\nclass BaseApp(BaseClass):\n\n # 初始化启动APP\n def NewApp(self):\n\n if self.driver == None:\n with open(\"../Data/Data.yml\", 'r', encoding=\"utf-8\") as file:\n data = yaml.safe_load(file)\n self.desired_caps = data[\"desired_caps\"]\n self.host = data[\"localhost\"][\"host\"]\n # # 客户端和appium服务器连接代码\n self.driver = webdriver.Remote(f\"{self.host}\", self.desired_caps)\n self.driver.implicitly_wait(5)\n return self\n\n else:\n self.driver.launch_app()\n\n # 初始化一个driver\n\n # 退出APP\n def StopApp(self):\n self.driver.quit()\n\n # 重启APP\n def RestartApp(self):\n self.driver.launch_app()\n\n # 把driver传递给MainPage页\n def goto_MainPage(self):\n return MainPage(self.driver)\n","sub_path":"UI_Framework/Base/BaseApp.py","file_name":"BaseApp.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"595673019","text":"import time\n\ndef bubble(data, drawData, timeTick):\n size = len(data)\n for i in range(size-1):\n for j in range(size-i-1):\n if data[j] > data[j+1]:\n data[j], data[j+1] = data[j+1], data[j]\n drawData(data, ['#F7E806' if x == j or x == j+1 else '#0CA8F6' for x in range(len(data))] )\n time.sleep(timeTick)\n \n drawData(data, ['#0CA8F6' for x in range(len(data))])\n","sub_path":"bubble.py","file_name":"bubble.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"320587740","text":"import mne\nimport pandas as pd\n\ndata_path = 'E:\\Wavelet_analysis\\Analyzer_export'\nraw_fname = data_path + '\\Learning_S6_d5_M_Mult_wMarkers.dat'\nvhdr_fname = data_path + '\\Learning_S6_d5_M_Mult_wMarkers.vhdr'\n#montage_fname = 'D:\\Lisa\\THESIS\\DLproject\\\\127-channels-Tomsk.txt'\n\nraw = mne.io.read_raw_brainvision(vhdr_fname, montage=None, misc = ['FCC4h'])\n#montage_data = read_montage(kind='easycap-M1', path = 'D:\\Lisa\\THESIS\\DLproject')\nprint(raw)\nprint(raw.info)\nchannels = pd.DataFrame(raw.info['chs'])\nprint(channels)\n\n#read_montage(kind='easycap-M1', path = 'D:\\Lisa\\THESIS\\DLproject')\n\"\"\"\nprint(raw.ch_names)\n\nstart, stop = raw.time_as_index([100, 115]) # 100 s to 115 s data segment\ndata, times = raw[:, start:stop]\nprint(data.shape)\nprint(times.shape)\ndata, times = raw[2:20:3, start:stop] # access underlying data\nraw.plot()\n\"\"\"","sub_path":"1_readSegmented.py","file_name":"1_readSegmented.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"252752988","text":"import cv2\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom detect import *\r\nfrom show import *\r\n\r\n\r\n\r\ndef calc_grads_img(img):\r\n y_filter = np.array(([-1, -2, -1],\r\n [0, 0, 0],\r\n [1, 2, 1]))\r\n x_filter = y_filter.T\r\n grad_y = cv2.filter2D(img, ddepth=-1, kernel=y_filter)\r\n grad_x = cv2.filter2D(img, ddepth=-1, kernel=x_filter)\r\n return grad_x, grad_y\r\n\r\n\r\ndef read_image(path, color=False):\r\n if color:\r\n image = np.array(cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2RGB), dtype=np.float64)\r\n else:\r\n image = cv2.imread(path, 0)\r\n return image\r\n\r\n\r\ndef calc_grad(img):\r\n img_smooth = np.float32(cv2.GaussianBlur(img, (3, 3), 25))\r\n grad_x, grad_y = calc_grads_img(img_smooth)\r\n magnitude_img = np.sqrt(grad_x ** 2 + grad_y ** 2)\r\n angles = np.arctan2(grad_y, grad_x)\r\n return angles\r\n\r\n\r\ndef show_image(image, title=None, cmap=None, textbox=None):\r\n if cmap is not None:\r\n plt.imshow(np.uint8(image), cmap=cmap)\r\n else:\r\n plt.imshow(np.uint8(image))\r\n if title is not None:\r\n plt.title(title)\r\n\r\n plt.show()\r\n\r\ndef create_help_matrix(matrix, n):\r\n new_matrix = np.zeros(matrix.shape)\r\n height, width = matrix.shape\r\n for i in range(0, height, n + 1):\r\n for j in range(0, width, n + 1):\r\n end_j2 = min(j + n + 1, width)\r\n for j2 in range(j, end_j2):\r\n upper = i\r\n upper_max = matrix[upper, j2]\r\n new_matrix[upper, j2] = upper_max\r\n upper += 1\r\n lower = min(i + n, height - 1)\r\n lower_max = matrix[lower, j2]\r\n new_matrix[lower, j2] = lower_max\r\n lower -= 1\r\n\r\n while upper != n // 2 + i and upper != height:\r\n if matrix[upper, j2] > upper_max:\r\n upper_max = matrix[upper, j2]\r\n else:\r\n new_matrix[upper, j2] = upper_max\r\n\r\n if matrix[lower, j2] > lower_max:\r\n lower_max = matrix[lower, j2]\r\n else:\r\n new_matrix[lower, j2] = lower_max\r\n upper += 1\r\n if lower == n // 2 + 1:\r\n lower -= 1\r\n if upper == height:\r\n upper -= 1\r\n new_matrix[upper, j2] = max(upper_max, lower_max, matrix[upper, j2])\r\n return new_matrix\r\n\r\n\r\ndef nms_2d(matrix, size_filter=29, tau=80):\r\n new_matrix = np.zeros(matrix.shape)\r\n maxes = []\r\n height, width = matrix.shape\r\n n = (size_filter - 1) // 2\r\n accum_matrix = create_help_matrix(matrix, n)\r\n\r\n for i in range(0, height, n + 1):\r\n for j in range(0, width, n + 1):\r\n is_not_max = False\r\n mi, mj = i, j\r\n\r\n for i2 in range(i, min(i + n + 1, height)):\r\n for j2 in range(j, min(j + n + 1, width)):\r\n if matrix[i2, j2] > matrix[mi, mj]:\r\n mi, mj = i2, j2\r\n i2 = max(mi - n, 0)\r\n max_i2 = min(mi + n, height - 2) + 1\r\n while i2 < max_i2:\r\n j2 = max(mj - n, 0)\r\n max_j2 = min(mj + n, width - 2) + 1\r\n while j2 < max_j2:\r\n if i2 < i:\r\n if i2 < i - n // 2 - 1:\r\n if matrix[i2, j2] > matrix[mi, mj]:\r\n mi, mj = i2, j2\r\n is_not_max = True\r\n break\r\n elif i2 == i - n // 2 - 1:\r\n if matrix[i2, j2] == accum_matrix[i2, j2]:\r\n if matrix[i2, j2] > matrix[mi, mj]:\r\n mi, mj = i2, j2\r\n is_not_max = True\r\n break\r\n else:\r\n if matrix[i2, j2] > matrix[mi, mj]:\r\n mi, mj = i2, j2\r\n is_not_max = True\r\n break\r\n if j2 + 1 == max_j2:\r\n i2 = i - 1\r\n elif i2 > i + n:\r\n if i2 == i + n + n // 2 or i2 + 1 == max_i2:\r\n if matrix[i2, j2] > matrix[mi, mj]:\r\n mi, mj = i2, j2\r\n is_not_max = True\r\n break\r\n if j2 + 1 == max_j2:\r\n i2 += 1\r\n elif i2 == i + n + n // 2 + 1:\r\n if matrix[i2, j2] == accum_matrix[i2, j2]:\r\n if matrix[i2, j2] > matrix[mi, mj]:\r\n mi, mj = i2, j2\r\n is_not_max = True\r\n break\r\n elif i2 > i + n + n // 2 + 1:\r\n if matrix[i2, j2] > matrix[mi, mj]:\r\n mi, mj = i2, j2\r\n is_not_max = True\r\n break\r\n elif j2 < j or j2 > j + n:\r\n if matrix[i2, j2] > matrix[mi, mj]:\r\n mi, mj = i2, j2\r\n is_not_max = True\r\n break\r\n if j2 + 1 == max_j2:\r\n i2 = i + n\r\n j2 += 1\r\n if is_not_max:\r\n break\r\n i2 += 1\r\n if not is_not_max and tau <= matrix[mi, mj]:\r\n maxes.append((mi, mj, matrix[mi, mj]))\r\n for t in maxes:\r\n i, j, m = t\r\n new_matrix[i, j] = m\r\n return new_matrix\r\n\r\n\r\n\r\n\r\ndef nms_3d(matrix, size_filter=29, tau=80):\r\n new_matrix = matrix.copy()\r\n for i in range(new_matrix.shape[0]):\r\n new_matrix[i] = nms_2d(new_matrix[i], size_filter, tau)\r\n\r\n for j in range(new_matrix.shape[1]):\r\n new_matrix[:, j] = nms_2d(new_matrix[:, j], size_filter, tau)\r\n\r\n for k in range(new_matrix.shape[2]):\r\n new_matrix[:, :, k] = nms_2d(new_matrix[:, :, k], size_filter, tau)\r\n return new_matrix\r\n\r\n\r\ndef GaussianBlur_3d(matrix, filter, sigma):\r\n new_matrix = matrix.copy()\r\n for i in range(new_matrix.shape[0]):\r\n new_matrix[i] = cv2.GaussianBlur(new_matrix[i], filter, sigma)\r\n\r\n for j in range(new_matrix.shape[1]):\r\n new_matrix[:, j] = cv2.GaussianBlur(new_matrix[:, j], filter, sigma)\r\n\r\n for k in range(new_matrix.shape[2]):\r\n new_matrix[:, :, k] = cv2.GaussianBlur(new_matrix[:, :, k], filter, sigma)\r\n return new_matrix","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"605490275","text":"# Copyright (c) 2018, DjaoDjin inc.\n# see LICENSE\n\nfrom pages.api.themes import (\n ThemePackageListAPIView as ThemePackageListAPIBaseView)\nfrom rules.api.keys import (\n AppUpdateAPIView as RulesAppUpdateAPIView)\n\nfrom .serializers import AppSerializer\n\n\nclass ThemePackageListAPIView(ThemePackageListAPIBaseView):\n\n @property\n def theme(self):\n if not hasattr(self, '_theme'):\n self._theme = self.app.slug\n return self._theme\n\n\nclass AppUpdateAPIView(RulesAppUpdateAPIView):\n serializer_class = AppSerializer\n","sub_path":"djaoapp/api/custom_themes.py","file_name":"custom_themes.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"350547465","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom testifycompat import assert_equal\nfrom testifycompat import TestCase\nfrom tron.utils import dicts\n\n\nclass TestInvertDictList(TestCase):\n def test_invert_dict_list(self):\n expected = {\n 'a': 1,\n 'b': 1,\n 'c': 1,\n 'd': 2,\n 'e': 3,\n 'f': 3,\n }\n original = {\n 1: ['a', 'b', 'c'],\n 2: ['d'],\n 3: ['e', 'f'],\n }\n assert_equal(dicts.invert_dict_list(original), expected)\n\n\nclass TestGetDeep(TestCase):\n\n data = {'foo': 23, 'bar': {'car': 'hello'}}\n\n def test_get_deep_one_key(self):\n assert_equal(\n dicts.get_deep(self.data, 'foo'),\n 23,\n )\n\n def test_get_deep_two_keys(self):\n assert_equal(\n dicts.get_deep(self.data, 'bar.car'),\n 'hello',\n )\n\n def test_get_deep_missing(self):\n assert_equal(\n dicts.get_deep(self.data, 'bar.baz'),\n None,\n )\n\n def test_get_deep_missing_first_key(self):\n assert_equal(\n dicts.get_deep(self.data, 'other.car'),\n None,\n )\n\n def test_get_deep_default(self):\n assert_equal(\n dicts.get_deep(self.data, 'other', 'custom_default'),\n 'custom_default',\n )\n","sub_path":"tests/utils/dicts_test.py","file_name":"dicts_test.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"422874803","text":"import unittest\nfrom modules.positon_manage.position_device_manage.position_device_transfer import *\nfrom config import readcfg\n\ndid_Gary_hub = readcfg.did_Gary_hub\npositionId_Gary = readcfg.positionId_real1_Gary\n\n\nclass TestPositionDeviceAssign(unittest.TestCase):\n \"\"\"\n 网关设备转移实体顶级位置(跨家分配位置)\n \"\"\"\n\n def test_position_device_transfer_01(self):\n \"\"\"测试网关设备转移实体顶级位置(跨家分配位置)\"\"\"\n result = position_device_transfer(did_Gary_hub, positionId_Gary)\n self.assertIn('\"code\":735', result.text)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"case/position_manage/position_device_manage/test_position_device_transfer.py","file_name":"test_position_device_transfer.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377599344","text":"'''\nCreated on 1 févr. 2014\n\n@author: inso\n'''\n\nimport os\nimport logging\nimport tarfile\nimport shutil\nimport json\nimport datetime\nimport i18n_rc\n\nfrom PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot, \\\nQUrl, QTranslator, QCoreApplication, QLocale\nfrom PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest\n\nfrom . import config\nfrom .account import Account\nfrom . import person\nfrom .watching.monitor import Monitor\nfrom .. import __version__\nfrom ..tools.exceptions import NameAlreadyExists, BadAccountFile\n\n\nclass Application(QObject):\n\n '''\n Managing core application datas :\n Accounts list and general configuration\n Saving and loading the application state\n '''\n\n loading_progressed = pyqtSignal(int, int)\n version_requested = pyqtSignal()\n\n def __init__(self, argv, qapp):\n '''\n Create a new \"cutecoin\" application\n\n :param argv: The argv parameters of the call\n '''\n super().__init__()\n self.qapp = qapp\n self.accounts = {}\n self.current_account = None\n self.monitor = None\n self.available_version = (True,\n __version__,\n \"\")\n config.parse_arguments(argv)\n self._network_manager = QNetworkAccessManager()\n self._network_manager.finished.connect(self.read_available_version)\n self.preferences = {'account': \"\",\n 'lang': 'en_GB',\n 'ref': 0\n }\n\n self.load()\n self.switch_language()\n\n def switch_language(self):\n translator = QTranslator(self.qapp)\n logging.debug(\"Loading translations\")\n locale = self.preferences['lang']\n QLocale.setDefault(QLocale(locale))\n if translator.load(\":/i18n/{0}\".format(locale)):\n if QCoreApplication.installTranslator(translator):\n logging.debug(\"Loaded i18n/{0}\".format(locale))\n else:\n logging.debug(\"Couldn't load translation\")\n\n def get_account(self, name):\n '''\n Load an account then return it\n\n :param str name: The account name\n :return: The loaded account if it's a success, else return None\n '''\n self.load_account(name)\n if name in self.accounts.keys():\n return self.accounts[name]\n else:\n return None\n\n def create_account(self, name):\n '''\n Create a new account from its name\n\n :param str name: The account name\n :return: The new account\n :raise: NameAlreadyExists if the account name is already used locally\n '''\n for a in self.accounts:\n if a == name:\n raise NameAlreadyExists(a)\n\n account = Account.create(name)\n\n return account\n\n def add_account(self, account):\n self.accounts[account.name] = account\n\n def delete_account(self, account):\n '''\n Delete an account.\n Current account changes to None if it is deleted.\n '''\n self.accounts.pop(account.name)\n if self.current_account == account:\n self.current_account = None\n with open(config.parameters['data'], 'w') as outfile:\n json.dump(self.jsonify(), outfile, indent=4, sort_keys=True)\n if self.preferences['account'] == account.name:\n self.preferences['account'] = \"\"\n self.save_preferences(self.preferences)\n\n def change_current_account(self, account):\n '''\n Change current account displayed and refresh its cache.\n\n :param account: The account object to display\n .. note:: Emits the application pyqtSignal loading_progressed\n during cache refresh\n '''\n def progressing(value, maximum):\n self.loading_progressed.emit(value, maximum)\n\n if self.current_account is not None:\n if self.monitor:\n self.monitor.stop_watching()\n self.save_cache(self.current_account)\n account.loading_progressed.connect(progressing)\n account.refresh_cache()\n self.monitor = Monitor(account)\n self.monitor.prepare_watching()\n self.current_account = account\n\n def load(self):\n '''\n Load a saved application state from the data file.\n Loads only jsonified objects but not their cache.\n\n If the standard application state file can't be found,\n no error is raised.\n '''\n self.load_persons()\n self.load_preferences()\n try:\n logging.debug(\"Loading data...\")\n with open(config.parameters['data'], 'r') as json_data:\n data = json.load(json_data)\n for account_name in data['local_accounts']:\n self.accounts[account_name] = None\n except FileNotFoundError:\n pass\n\n def load_persons(self):\n '''\n Load the Person instances of the person module.\n Each instance is unique, and can be find by its public key.\n '''\n try:\n persons_path = os.path.join(config.parameters['home'],\n '__persons__')\n with open(persons_path, 'r') as persons_path:\n data = json.load(persons_path)\n person.load_cache(data)\n except FileNotFoundError:\n pass\n\n def load_account(self, account_name):\n '''\n Load an account from its name\n\n :param str account_name: The account name\n '''\n account_path = os.path.join(config.parameters['home'],\n account_name, 'properties')\n with open(account_path, 'r') as json_data:\n data = json.load(json_data)\n account = Account.load(data)\n self.load_cache(account)\n self.accounts[account_name] = account\n\n def load_cache(self, account):\n '''\n Load an account cache\n\n :param account: The account object to load the cache\n '''\n for community in account.communities:\n community_path = os.path.join(config.parameters['home'],\n account.name, '__cache__',\n community.currency)\n\n network_path = os.path.join(config.parameters['home'],\n account.name, '__cache__',\n community.currency + '_network')\n\n if os.path.exists(network_path):\n with open(network_path, 'r') as json_data:\n data = json.load(json_data)\n if 'version' in data and data['version'] == __version__:\n logging.debug(\"Merging network : {0}\".format(data))\n community.load_merge_network(data['network'])\n else:\n os.remove(network_path)\n\n if os.path.exists(community_path):\n with open(community_path, 'r') as json_data:\n data = json.load(json_data)\n if 'version' in data and data['version'] == __version__:\n community.load_cache(data)\n else:\n os.remove(community_path)\n\n for wallet in account.wallets:\n wallet_path = os.path.join(config.parameters['home'],\n account.name, '__cache__', wallet.pubkey)\n if os.path.exists(wallet_path):\n with open(wallet_path, 'r') as json_data:\n data = json.load(json_data)\n if 'version' in data and data['version'] == __version__:\n wallet.load_caches(data)\n else:\n os.remove(wallet_path)\n\n def load_preferences(self):\n '''\n Load the preferences.\n '''\n\n try:\n preferences_path = os.path.join(config.parameters['home'],\n 'preferences')\n with open(preferences_path, 'r') as json_data:\n data = json.load(json_data)\n self.preferences = data\n except FileNotFoundError:\n pass\n\n def save_preferences(self, preferences):\n '''\n Save the preferences.\n\n :param preferences: A dict containing the keys/values of the preferences\n '''\n assert('lang' in preferences)\n assert('account' in preferences)\n assert('ref' in preferences)\n\n self.preferences = preferences\n preferences_path = os.path.join(config.parameters['home'],\n 'preferences')\n with open(preferences_path, 'w') as outfile:\n json.dump(preferences, outfile, indent=4)\n\n def save(self, account):\n '''\n Save an account\n\n :param account: The account object to save\n '''\n with open(config.parameters['data'], 'w') as outfile:\n json.dump(self.jsonify(), outfile, indent=4, sort_keys=True)\n account_path = os.path.join(config.parameters['home'],\n account.name)\n if account.name in self.accounts:\n properties_path = os.path.join(account_path, 'properties')\n if not os.path.exists(account_path):\n logging.info(\"Creating account directory\")\n os.makedirs(account_path)\n with open(properties_path, 'w') as outfile:\n json.dump(account.jsonify(), outfile, indent=4, sort_keys=True)\n else:\n account_path = os.path.join(config.parameters['home'], account.name)\n shutil.rmtree(account_path)\n\n def save_persons(self):\n '''\n Save the person module cache\n '''\n persons_path = os.path.join(config.parameters['home'],\n '__persons__')\n with open(persons_path, 'w')as outfile:\n data = person.jsonify_cache()\n data['version'] = __version__\n json.dump(data, outfile, indent=4, sort_keys=True)\n\n def save_wallet(self, account, wallet):\n \"\"\"\n Save wallet of account in cache\n\n :param cutecoin.core.account.Account account: Account instance\n :param cutecoin.core.wallet.Wallet wallet: Wallet instance\n \"\"\"\n if not os.path.exists(os.path.join(config.parameters['home'],\n account.name, '__cache__')):\n os.makedirs(os.path.join(config.parameters['home'],\n account.name, '__cache__'))\n wallet_path = os.path.join(config.parameters['home'],\n account.name, '__cache__', wallet.pubkey)\n with open(wallet_path, 'w') as outfile:\n data = wallet.jsonify_caches()\n data['version'] = __version__\n json.dump(data, outfile, indent=4, sort_keys=True)\n\n def save_cache(self, account):\n '''\n Save the cache of an account\n\n :param account: The account object to save the cache\n '''\n if not os.path.exists(os.path.join(config.parameters['home'],\n account.name, '__cache__')):\n os.makedirs(os.path.join(config.parameters['home'],\n account.name, '__cache__'))\n for wallet in account.wallets:\n self.save_wallet(account, wallet)\n\n for community in account.communities:\n community_path = os.path.join(config.parameters['home'],\n account.name, '__cache__',\n community.currency)\n\n network_path = os.path.join(config.parameters['home'],\n account.name, '__cache__',\n community.currency + '_network')\n\n with open(network_path, 'w') as outfile:\n data = dict()\n data['network'] = community.jsonify_network()\n data['version'] = __version__\n json.dump(data, outfile, indent=4, sort_keys=True)\n\n with open(community_path, 'w') as outfile:\n data = community.jsonify_cache()\n data['version'] = __version__\n json.dump(data, outfile, indent=4, sort_keys=True)\n\n def import_account(self, file, name):\n '''\n Import an account from a tar file and open it\n\n :param str file: The file path of the tar file\n :param str name: The account name\n '''\n with tarfile.open(file, \"r\") as tar:\n path = os.path.join(config.parameters['home'],\n name)\n for obj in [\"properties\"]:\n try:\n tar.getmember(obj)\n except KeyError:\n raise BadAccountFile(file)\n tar.extractall(path)\n\n account_path = os.path.join(config.parameters['home'],\n name, 'properties')\n json_data = open(account_path, 'r')\n data = json.load(json_data)\n account = Account.load(data)\n account.name = name\n self.add_account(account)\n self.save(account)\n self.change_current_account(account)\n\n def export_account(self, file, account):\n '''\n Export an account to a tar file\n\n :param str file: The filepath of the tar file\n :param account: The account object to export\n '''\n with tarfile.open(file, \"w\") as tar:\n for file in [\"properties\"]:\n path = os.path.join(config.parameters['home'],\n account.name, file)\n tar.add(path, file)\n\n def jsonify_accounts(self):\n '''\n Jsonify an account\n\n :return: The account as a dict to format as json\n '''\n data = []\n logging.debug(\"{0}\".format(self.accounts))\n for account in self.accounts:\n data.append(account)\n return data\n\n def jsonify(self):\n '''\n Jsonify the app datas\n\n :return: The accounts of the app to format as json\n '''\n data = {'local_accounts': self.jsonify_accounts()}\n return data\n\n def get_last_version(self):\n url = QUrl(\"https://api.github.com/repos/ucoin-io/cutecoin/releases\")\n request = QNetworkRequest(url)\n self._network_manager.get(request)\n\n @pyqtSlot(QNetworkReply)\n def read_available_version(self, reply):\n latest = None\n releases = reply.readAll().data().decode('utf-8')\n logging.debug(releases)\n if reply.error() == QNetworkReply.NoError:\n for r in json.loads(releases):\n if not latest:\n latest = r\n else:\n latest_date = datetime.datetime.strptime(latest['published_at'], \"%Y-%m-%dT%H:%M:%SZ\")\n date = datetime.datetime.strptime(r['published_at'], \"%Y-%m-%dT%H:%M:%SZ\")\n if latest_date < date:\n latest = r\n latest_version = latest[\"tag_name\"]\n version = (__version__ == latest_version,\n latest_version,\n latest[\"html_url\"])\n logging.debug(\"Found version : {0}\".format(latest_version))\n logging.debug(\"Current version : {0}\".format(__version__))\n self.available_version = version\n self.version_requested.emit()\n","sub_path":"src/cutecoin/core/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":15573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"359456510","text":"\"\"\"Base abstract representations of functions.\"\"\"\n\nimport contextlib\nimport inspect\nimport logging\nfrom typing import Type\n\nfrom pytype import utils\nfrom pytype.abstract import _base\nfrom pytype.abstract import _classes\nfrom pytype.abstract import _instance_base\nfrom pytype.abstract import _instances\nfrom pytype.abstract import _singletons\nfrom pytype.abstract import _typing\nfrom pytype.abstract import abstract_utils\nfrom pytype.abstract import class_mixin\nfrom pytype.abstract import function\n\nlog = logging.getLogger(__name__)\n_isinstance = abstract_utils._isinstance # pylint: disable=protected-access\n\n\nclass Function(_instance_base.SimpleValue):\n \"\"\"Base class for function objects (NativeFunction, InterpreterFunction).\n\n Attributes:\n name: Function name. Might just be something like \"\".\n ctx: context.Context instance.\n \"\"\"\n\n bound_class: Type[\"BoundFunction\"]\n\n def __init__(self, name, ctx):\n super().__init__(name, ctx)\n self.cls = _classes.FunctionPyTDClass(self, ctx)\n self.is_attribute_of_class = False\n self.is_classmethod = False\n self.is_abstract = False\n self.is_method = \".\" in name\n self.members[\"func_name\"] = self.ctx.convert.build_string(\n self.ctx.root_node, name)\n\n def property_get(self, callself, is_class=False):\n if self.name == \"__new__\" or not callself or is_class:\n return self\n self.is_attribute_of_class = True\n # We'd like to cache this, but we can't. \"callself\" contains Variables\n # that would be tied into a BoundFunction instance. However, those\n # Variables aren't necessarily visible from other parts of the CFG binding\n # this function. See test_duplicate_getproperty() in tests/test_flow.py.\n return self.bound_class(callself, self)\n\n def _get_cell_variable_name(self, var):\n \"\"\"Get the python variable name of a pytype Variable.\"\"\"\n f = self.ctx.vm.frame\n if not f:\n # Should not happen but does in some contrived test cases.\n return None\n for name, v in zip(f.f_code.co_freevars, f.cells):\n if v == var:\n return name\n return None\n\n def match_args(self, node, args, alias_map=None, match_all_views=False):\n \"\"\"Check whether the given arguments can match the function signature.\"\"\"\n for a in args.posargs:\n if not a.bindings:\n # The only way to get an unbound variable here is to reference a closure\n # cellvar before it is assigned to in the outer scope.\n name = self._get_cell_variable_name(a)\n assert name is not None, \"Closure variable lookup failed.\"\n raise function.UndefinedParameterError(name)\n # The implementation of match_args is currently rather convoluted because we\n # have two different implementations:\n # * Old implementation: `_match_views` matches 'args' against 'self' one\n # view at a time, where a view is a mapping of every variable in args to a\n # particular binding. This handles generics but scales poorly with the\n # number of bindings per variable.\n # * New implementation: `_match_args_sequentially` matches 'args' one at a\n # time. This scales better but cannot yet handle generics.\n # Subclasses should implement the following:\n # * _match_view(node, args, view, alias_map): this will be called repeatedly\n # by _match_views.\n # * _match_args_sequentially(node, args, alias_map, match_all_views): A\n # sequential matching implementation.\n # TODO(b/228241343): Get rid of _match_views and simplify match_args once\n # _match_args_sequentially can handle generics.\n if self._is_generic_call(args):\n return self._match_views(node, args, alias_map, match_all_views)\n return self._match_args_sequentially(node, args, alias_map, match_all_views)\n\n def _is_generic_call(self, args):\n for sig in function.get_signatures(self):\n for t in sig.annotations.values():\n stack = [t]\n seen = set()\n while stack:\n cur = stack.pop()\n if cur in seen:\n continue\n seen.add(cur)\n if cur.formal or cur.template:\n return True\n if _isinstance(cur, \"Union\"):\n stack.extend(cur.options)\n if self.is_attribute_of_class and args.posargs:\n for self_val in args.posargs[0].data:\n for cls in self_val.cls.mro:\n if cls.template:\n return True\n return False\n\n def _match_views(self, node, args, alias_map, match_all_views):\n \"\"\"Matches all views of the given args against this function.\"\"\"\n error = None\n matched = []\n arg_variables = args.get_variables()\n views = abstract_utils.get_views(arg_variables, node)\n skip_future = None\n while True:\n try:\n view = views.send(skip_future)\n except StopIteration:\n break\n log.debug(\"args in view: %r\", [(a.bindings and view[a].data)\n for a in args.posargs])\n try:\n match = self._match_view(node, args, view, alias_map)\n except function.FailedFunctionCall as e:\n if not node.HasCombination(list(view.values())) or e <= error:\n # This error was ignored, but future ones with the same accessed\n # subset may need to be recorded, so we can't skip them.\n skip_future = False\n else:\n # Add the name of the caller if possible.\n if hasattr(self, \"parent\"):\n e.name = f\"{self.parent.name}.{e.name}\"\n if match_all_views or self.ctx.options.strict_parameter_checks:\n raise e\n error = e\n skip_future = True\n else:\n matched.append(match)\n skip_future = True\n if not matched and error:\n raise error # pylint: disable=raising-bad-type\n return matched\n\n def _match_view(self, node, args, view, alias_map):\n raise NotImplementedError(self.__class__.__name__)\n\n def _match_args_sequentially(self, node, args, alias_map, match_all_views):\n raise NotImplementedError(self.__class__.__name__)\n\n def __repr__(self):\n return self.full_name + \"(...)\"\n\n def _extract_defaults(self, defaults_var):\n \"\"\"Extracts defaults from a Variable, used by set_function_defaults.\n\n Args:\n defaults_var: Variable containing potential default values.\n\n Returns:\n A tuple of default values, if one could be extracted, or None otherwise.\n \"\"\"\n # Case 1: All given data are tuple constants. Use the longest one.\n if all(isinstance(d, _instances.Tuple) for d in defaults_var.data):\n return max((d.pyval for d in defaults_var.data), key=len)\n else:\n # Case 2: Data are entirely Tuple Instances, Unknown or Unsolvable. Make\n # all parameters except self/cls optional.\n # Case 3: Data is anything else. Same as Case 2, but emit a warning.\n if not (all(isinstance(d, (\n _instance_base.Instance, _singletons.Unknown, _singletons.Unsolvable))\n for d in defaults_var.data) and\n all(d.full_name == \"builtins.tuple\"\n for d in defaults_var.data\n if isinstance(d, _instance_base.Instance))):\n self.ctx.errorlog.bad_function_defaults(self.ctx.vm.frames, self.name)\n # The ambiguous case is handled by the subclass.\n return None\n\n def set_function_defaults(self, node, defaults_var):\n raise NotImplementedError(self.__class__.__name__)\n\n\nclass NativeFunction(Function):\n \"\"\"An abstract value representing a native function.\n\n Attributes:\n name: Function name. Might just be something like \"\".\n func: An object with a __call__ method.\n ctx: context.Context instance.\n \"\"\"\n\n def __init__(self, name, func, ctx):\n super().__init__(name, ctx)\n self.func = func\n self.bound_class = lambda callself, underlying: self\n\n def argcount(self, _):\n return self.func.func_code.co_argcount\n\n def call(self, node, _, args, alias_map=None):\n sig = None\n if isinstance(self.func.__self__, _classes.CallableClass):\n sig = function.Signature.from_callable(self.func.__self__)\n args = args.simplify(node, self.ctx, match_signature=sig)\n posargs = [u.AssignToNewVariable(node) for u in args.posargs]\n namedargs = {k: u.AssignToNewVariable(node)\n for k, u in args.namedargs.items()}\n try:\n inspect.signature(self.func).bind(node, *posargs, **namedargs)\n except ValueError as e:\n # Happens for, e.g.,\n # def f((x, y)): pass\n # f((42,))\n raise NotImplementedError(\"Wrong number of values to unpack\") from e\n except TypeError as e:\n # The possible errors here are:\n # (1) wrong arg count\n # (2) duplicate keyword\n # (3) unexpected keyword\n # The way we constructed namedargs rules out (2).\n if \"keyword\" in utils.message(e):\n # Happens for, e.g.,\n # def f(*args): pass\n # f(x=42)\n raise NotImplementedError(\"Unexpected keyword\") from e\n # The function was passed the wrong number of arguments. The signature is\n # ([self, ]node, ...). The length of \"...\" tells us how many variables\n # are expected.\n expected_argcount = len(inspect.getfullargspec(self.func).args) - 1\n if inspect.ismethod(self.func) and self.func.__self__ is not None:\n expected_argcount -= 1\n actual_argcount = len(posargs) + len(namedargs)\n if (actual_argcount > expected_argcount or\n (not args.starargs and not args.starstarargs)):\n # If we have too many arguments, or starargs and starstarargs are both\n # empty, then we can be certain of a WrongArgCount error.\n argnames = tuple(\"_\" + str(i) for i in range(expected_argcount))\n sig = function.Signature(\n self.name, argnames, 0, None, set(), None, {}, {}, {})\n raise function.WrongArgCount(sig, args, self.ctx)\n assert actual_argcount < expected_argcount\n # Assume that starargs or starstarargs fills in the missing arguments.\n # Instead of guessing where these arguments should go, overwrite all of\n # the arguments with a list of unsolvables of the correct length, which\n # is guaranteed to give us a correct (but imprecise) analysis.\n posargs = [\n self.ctx.new_unsolvable(node) for _ in range(expected_argcount)\n ]\n namedargs = {}\n return self.func(node, *posargs, **namedargs)\n\n def get_positional_names(self):\n code = self.func.func_code\n return list(code.co_varnames[:code.co_argcount])\n\n\nclass BoundFunction(_base.BaseValue):\n \"\"\"An function type which has had an argument bound into it.\"\"\"\n\n def __init__(self, callself, underlying):\n super().__init__(underlying.name, underlying.ctx)\n self.cls = underlying.cls\n self._callself = callself\n self.underlying = underlying\n self.is_attribute_of_class = False\n self.is_class_builder = False\n\n # If the function belongs to `ParameterizedClass`, we will annotate the\n # `self` when do argument matching\n self.replace_self_annot = None\n inst = abstract_utils.get_atomic_value(\n self._callself, default=self.ctx.convert.unsolvable)\n if self._should_replace_self_annot():\n if (isinstance(inst.cls, class_mixin.Class) and\n inst.cls.full_name != \"builtins.type\"):\n for cls in inst.cls.mro:\n if isinstance(cls, _classes.ParameterizedClass):\n base_cls = cls.base_cls\n else:\n base_cls = cls\n if isinstance(base_cls, class_mixin.Class) and base_cls.template:\n self.replace_self_annot = (\n _classes.ParameterizedClass.get_generic_instance_type(base_cls))\n break\n if isinstance(inst, _instance_base.SimpleValue):\n self.alias_map = inst.instance_type_parameters.uf\n elif isinstance(inst, _typing.TypeParameterInstance):\n self.alias_map = inst.instance.instance_type_parameters.uf\n else:\n self.alias_map = None\n\n def _should_replace_self_annot(self):\n # To do argument matching for custom generic classes, the 'self' annotation\n # needs to be replaced with a generic type.\n f = self.underlying\n if not _isinstance(f, \"SignedFunction\") or not f.signature.param_names:\n # no 'self' to replace\n return False\n if _isinstance(f, \"InterpreterFunction\"):\n # always replace for user-defined methods\n return True\n # SimpleFunctions are methods we construct internally for generated classes\n # like namedtuples.\n if not _isinstance(f, \"SimpleFunction\"):\n return False\n # We don't want to clobber our own generic annotations.\n return (f.signature.param_names[0] not in f.signature.annotations or\n not f.signature.annotations[f.signature.param_names[0]].formal)\n\n def argcount(self, node):\n return self.underlying.argcount(node) - 1 # account for self\n\n @property\n def signature(self):\n return self.underlying.signature.drop_first_parameter()\n\n @property\n def callself(self):\n return self._callself\n\n def call(self, node, func, args, alias_map=None):\n if abstract_utils.func_name_is_class_init(self.name):\n self.ctx.callself_stack.append(self._callself)\n # The \"self\" parameter is automatically added to the list of arguments, but\n # only if the function actually takes any arguments.\n if self.argcount(node) >= 0:\n args = args.replace(posargs=(self._callself,) + args.posargs)\n try:\n if self.replace_self_annot:\n with self.underlying.set_self_annot(self.replace_self_annot):\n node, ret = self.underlying.call(node, func, args,\n alias_map=self.alias_map)\n else:\n node, ret = self.underlying.call(node, func, args,\n alias_map=self.alias_map)\n except function.InvalidParameters as e:\n if self._callself and self._callself.bindings:\n if \".\" in e.name:\n # match_args will try to prepend the parent's name to the error name.\n # Overwrite it with _callself instead, which may be more exact.\n _, _, e.name = e.name.rpartition(\".\")\n e.name = f\"{self._callself.data[0].name}.{e.name}\"\n raise\n finally:\n if abstract_utils.func_name_is_class_init(self.name):\n self.ctx.callself_stack.pop()\n return node, ret\n\n def get_positional_names(self):\n return self.underlying.get_positional_names()\n\n def has_varargs(self):\n return self.underlying.has_varargs()\n\n def has_kwargs(self):\n return self.underlying.has_kwargs()\n\n @property\n def is_abstract(self):\n return self.underlying.is_abstract\n\n @is_abstract.setter\n def is_abstract(self, value):\n self.underlying.is_abstract = value\n\n @property\n def is_classmethod(self):\n return self.underlying.is_classmethod\n\n def repr_names(self, callself_repr=None):\n \"\"\"Names to use in the bound function's string representation.\n\n This function can return multiple names because there may be multiple\n bindings in callself.\n\n Args:\n callself_repr: Optionally, a repr function for callself.\n\n Returns:\n A non-empty iterable of string names.\n \"\"\"\n callself_repr = callself_repr or (lambda v: v.name)\n if self._callself and self._callself.bindings:\n callself_names = [callself_repr(v) for v in self._callself.data]\n else:\n callself_names = [\"\"]\n # We don't need to recursively call repr_names() because we replace the\n # parent name with the callself.\n underlying = self.underlying.name\n if underlying.count(\".\") > 0:\n underlying = underlying.split(\".\", 1)[-1]\n return [callself + \".\" + underlying for callself in callself_names]\n\n def __repr__(self):\n return self.repr_names()[0] + \"(...)\"\n\n\nclass BoundInterpreterFunction(BoundFunction):\n \"\"\"The method flavor of InterpreterFunction.\"\"\"\n\n @contextlib.contextmanager\n def record_calls(self):\n with self.underlying.record_calls():\n yield\n\n def get_first_opcode(self):\n return self.underlying.code.first_opcode\n\n @property\n def has_overloads(self):\n return self.underlying.has_overloads\n\n @property\n def is_overload(self):\n return self.underlying.is_overload\n\n @is_overload.setter\n def is_overload(self, value):\n self.underlying.is_overload = value\n\n @property\n def defaults(self):\n return self.underlying.defaults\n\n def iter_signature_functions(self):\n for f in self.underlying.iter_signature_functions():\n yield self.underlying.bound_class(self._callself, f)\n\n\nclass BoundPyTDFunction(BoundFunction):\n pass\n\n\nclass ClassMethod(_base.BaseValue):\n \"\"\"Implements @classmethod methods in pyi.\"\"\"\n\n def __init__(self, name, method, callself, ctx):\n super().__init__(name, ctx)\n self.cls = self.ctx.convert.function_type\n self.method = method\n self.method.is_attribute_of_class = True\n # Rename to callcls to make clear that callself is the cls parameter.\n self._callcls = callself\n self.signatures = self.method.signatures\n\n def call(self, node, func, args, alias_map=None):\n return self.method.call(\n node, func, args.replace(posargs=(self._callcls,) + args.posargs))\n\n def to_bound_function(self):\n return BoundPyTDFunction(self._callcls, self.method)\n\n\nclass StaticMethod(_base.BaseValue):\n \"\"\"Implements @staticmethod methods in pyi.\"\"\"\n\n def __init__(self, name, method, _, ctx):\n super().__init__(name, ctx)\n self.cls = self.ctx.convert.function_type\n self.method = method\n self.signatures = self.method.signatures\n\n def call(self, *args, **kwargs):\n return self.method.call(*args, **kwargs)\n\n\nclass Property(_base.BaseValue):\n \"\"\"Implements @property methods in pyi.\n\n If a getter's return type depends on the type of the class, it needs to be\n resolved as a function, not as a constant.\n \"\"\"\n\n def __init__(self, name, method, callself, ctx):\n super().__init__(name, ctx)\n self.cls = self.ctx.convert.function_type\n self.method = method\n self._callself = callself\n self.signatures = self.method.signatures\n\n def call(self, node, func, args, alias_map=None):\n func = func or self.to_binding(node)\n args = args or function.Args(posargs=(self._callself,))\n return self.method.call(node, func, args.replace(posargs=(self._callself,)))\n\n\nclass Splat(_base.BaseValue):\n \"\"\"Representation of unpacked iterables.\"\"\"\n\n def __init__(self, ctx, iterable):\n super().__init__(\"splat\", ctx)\n # When building a tuple for a function call, we preserve splats as elements\n # in a concrete tuple (e.g. f(x, *ys, z) gets called with the concrete tuple\n # (x, *ys, z) in starargs) and let the arg matcher in function.py unpack\n # them. Constructing the tuple accesses its class as a side effect; ideally\n # we would specialise abstract.Tuple for function calls and not bother\n # constructing an associated TupleClass for a function call tuple, but for\n # now we just set the class to Any here.\n self.cls = ctx.convert.unsolvable\n self.iterable = iterable\n\n def __repr__(self):\n return f\"splat({self.iterable.data!r})\"\n","sub_path":"pytype/abstract/_function_base.py","file_name":"_function_base.py","file_ext":"py","file_size_in_byte":18973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"570878776","text":"# -*- coding: utf-8 -*-\nimport picamera\nimport picamera.array\nimport cv2\nimport numpy as np\nfrom scipy import stats\nfrom sklearn.linear_model import Perceptron\nimport keras\nfrom keras import backend as K\nimport sys\nfrom PIL import Image, ImageTk\nimport threading\nimport time\nimport subprocess\ntry:\n import Tkinter as tk\nexcept ImportError: # for Python 3\n import tkinter as tk\nimport tensorflow as tf\n\nversion = cv2.__version__.split(\".\")\nCVversion = int(version[0])\n\nsession = tf.Session()\ngraph = tf.get_default_graph()\n\n# 手の認識用パラメータ(HチャンネルとSチャンネルとを二値化するための条件)\nhmin = 0\nhmax = 30 # 15-40程度にセット\nsmin = 50\n\n# 手の二値化画像のサイズ 縦(row)と横(col)\nimg_rows, img_cols = 12, 16\n\n# 学習に用いる縮小画像のサイズ\nsw = img_cols\nsh = img_rows\n\n# じゃんけんの手のベクトル形式を格納した配列。入力データとして用いる\n# グー [1, 0, 0], チョキ [0, 1, 0], パー [0, 0, 1]\njanken_array = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n\n# グー, チョキ, パーの名称を格納した配列\njanken_class = ['グー', 'チョキ', 'パー']\n\n# 過去何回分の手を覚えているか\nn = 3\n\n# じゃんけんの過去の手の初期化\n# 人間の手とコンピュータの手をそれぞれn回分。さらに1回分につき3個の数字が必要\nJprev = np.zeros(3*n*2) \n\n# 過去の手(ベクトル形式)をランダムに初期化\nfor i in range(2*n):\n j = np.random.randint(0, 3)\n Jprev[3*i:3*i+3] = janken_array[j]\n\n# 現在の手(0~2の整数)をランダムに初期化\nj = np.random.randint(0, 3)\n\n# 過去の手(入力データ)をscikit_learn用の配列に変換\nJprev_set = np.array([Jprev])\n# 現在の手(ターゲット)をscikit_learn用の配列に変換\njnow_set = np.array([j])\n\n# 三層ニューラルネットワークを定義\n#clf_janken = MLPClassifier(hidden_layer_sizes=(200, ), random_state=None)\n# 単純パーセプトロンを定義\nclf_janken = Perceptron(random_state=None)\n# ランダムな入力でオンライン学習を1回行う。\n# 初回の学習では、あり得るターゲット(0, 1, 2)を分類器に知らせる必要がある\nclf_janken.partial_fit(Jprev_set, jnow_set, classes=[0, 1, 2])\n\n# 勝敗の回数を初期化\nwin = 0\ndraw = 0\nlose = 0\n\n# 状態保存用のフラグ\nappliStop = False\njankenLoop = False\nrecognizedHand = 0\njankenFirst = False\n\n# 学習済ファイルの確認\nif len(sys.argv)==2:\n savefile = sys.argv[1]\n try:\n with session.as_default():\n model = keras.models.load_model(savefile)\n except IOError:\n print('学習済ファイル{0}を開けません'.format(savefile))\n sys.exit()\nelse:\n print('使用法: python ml-10-10-janken-deep-shorten.py 学習済ファイル.h5')\n sys.exit()\n\n# X:画像から計算したベクトル、y:教師データ\nX = np.empty((0,sw*sh), float) \ny = np.array([], int)\n\ndef getImageVector(img):\n # 白い領域(ピクセル値が0でない領域)の座標を集める\n nonzero = cv2.findNonZero(img)\n # その領域を囲う四角形の座標と大きさを取得\n xx, yy, ww, hh = cv2.boundingRect(nonzero)\n # 白い領域を含む最小の矩形領域を取得\n img_nonzero = img[yy:yy+hh, xx:xx+ww]\n # 白い領域を(sw, sh)サイズに縮小するための準備\n img_small = np.zeros((sh, sw), dtype=np.uint8)\n # 画像のアスペクト比を保ったまま、白い領域を縮小してimg_smallにコピーする\n if 4*hh < ww*3 and hh > 0:\n htmp = int(sw*hh/ww)\n if htmp>0:\n img_small_tmp = cv2.resize(img_nonzero, (sw, htmp), interpolation=cv2.INTER_LINEAR)\n img_small[int((sh-htmp)/2):int((sh-htmp)/2)+htmp, 0:sw] = img_small_tmp\n elif 4*hh >= ww*3 and ww > 0:\n wtmp = int(sh*ww/hh)\n if wtmp>0:\n img_small_tmp = cv2.resize(img_nonzero, (wtmp, sh), interpolation=cv2.INTER_LINEAR)\n img_small[0:sh, int((sw-wtmp)/2):int((sw-wtmp)/2)+wtmp] = img_small_tmp\n # 0...1の範囲にスケーリングしてからリターンする\n return np.array([img_small.ravel()/255.])\n\n# 手の認識をし続ける関数\ndef imageProcessing():\n with session.as_default():\n with graph.as_default():\n with picamera.PiCamera() as camera:\n with picamera.array.PiRGBArray(camera) as stream:\n # カメラの解像度を320x240にセット\n camera.resolution = (320, 240)\n # カメラのフレームレートを15fpsにセット\n camera.framerate = 15\n # ホワイトバランスをfluorescent(蛍光灯)モードにセット\n camera.awb_mode = 'fluorescent'\n\n while True:\n # stream.arrayにBGRの順で映像データを格納\n camera.capture(stream, 'bgr', use_video_port=True)\n\n # 映像データをHSV形式に変換\n hsv = cv2.cvtColor(stream.array, cv2.COLOR_BGR2HSV)\n # HSV形式からHチャンネルとSチャンネルの画像を得る\n hsv_channels = cv2.split(hsv)\n h_channel = hsv_channels[0]\n s_channel = hsv_channels[1]\n\n # Hチャンネルを平滑化\n h_binary = cv2.GaussianBlur(h_channel, (5,5), 0)\n\n # Hチャンネルの二値化画像を作成\n # hmin~hmaxの範囲を255(白)に、それ以外を0(黒)に\n ret,h_binary = cv2.threshold(h_binary, hmax, 255, cv2.THRESH_TOZERO_INV)\n ret,h_binary = cv2.threshold(h_binary, hmin, 255, cv2.THRESH_BINARY)\n # smin~255の範囲を255(白)に、それ以外を0に(黒)に\n ret,s_binary = cv2.threshold(s_channel, smin, 255, cv2.THRESH_BINARY)\n\n # HチャンネルとSチャンネルの二値化画像のANDをとる\n # HチャンネルとSチャンネルの両方で255(白)の領域のみ白となる\n hs_and = h_binary & s_binary\n\n # 以下、最も広い白領域のみを残すための計算\n # まず、白領域の塊(クラスター)にラベルを振る\n if CVversion == 2:\n img_dist, img_label = cv2.distanceTransformWithLabels(255-hs_and, cv2.cv.CV_DIST_L2, 5)\n else:\n img_dist, img_label = cv2.distanceTransformWithLabels(255-hs_and, cv2.DIST_L2, 5)\n img_label = np.uint8(img_label) & hs_and\n # ラベル0は黒領域なので除外\n img_label_not_zero = img_label[img_label != 0]\n # 最も多く現れた���ベルが最も広い白領域のラベル\n if len(img_label_not_zero) != 0:\n m = stats.mode(img_label_not_zero)[0]\n else:\n m = 0\n # 最大の白領域のみを残す\n hand = np.uint8(img_label == m)*255\n\n # 最大の白領域からscikit-learnに入力するためのベクトルを取得\n hand_vector = getImageVector(hand)\n\n # 学習済のニューラルネットワークから結果を取得\n X = np.array(hand_vector)\n if K.image_data_format() == 'channels_first':\n X = X.reshape(X.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\n else:\n X = X.reshape(X.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n result = model.predict_classes(X, verbose=0)\n\n # 分類結果をrecognizedHandに格納\n global recognizedHand\n recognizedHand = result[0]\n\n # 手と判定されている領域を表示\n cv2.imshow('hand', hand)\n\n # waitを入れる\n key = cv2.waitKey(1) \n\n if appliStop == True:\n break\n\n # streamをリセット\n stream.seek(0)\n stream.truncate()\n\n cv2.destroyAllWindows()\n app.jankenStop()\n app.quit()\n\nclass Application(tk.Frame):\n # 初期化用関数\n def __init__(self, master=None):\n tk.Frame.__init__(self, master)\n self.w = 200\n self.h = 200\n self.pack()\n self.create_widgets()\n root.protocol('WM_DELETE_WINDOW', self.close_window)\n self.recogthread = threading.Thread(target=imageProcessing)\n self.recogthread.start()\n\n # アプリ終了時に呼ばれる関数\n def close_window(self):\n global jankenLoop\n global appliStop \n jankenLoop = False\n appliStop = True\n\n # GUI部品の初期化\n def create_widgets(self):\n w = self.w\n h = self.h\n\n # コンピュータの手を表示する領域を初期化\n self.comp_canvas = tk.Canvas(self, width=w, height=h, bg='white')\n self.comp_blank_img = tk.PhotoImage(width=w, height=h)\n self.comp_canvas.create_image((w/2,h/2), image=self.comp_blank_img, state='normal')\n self.comp_canvas.image = self.comp_blank_img\n self.comp_canvas.grid(row=0, column=0)\n\n # コンピュータの手の画像の読み込み\n self.comp_gu_img = ImageTk.PhotoImage(image=Image.open('ml-images/comp_gu.png'))\n self.comp_choki_img = ImageTk.PhotoImage(image=Image.open('ml-images/comp_choki.png'))\n self.comp_pa_img = ImageTk.PhotoImage(image=Image.open('ml-images/comp_pa.png'))\n\n # 人間の手を表示する領域を初期化 \n self.human_canvas = tk.Canvas(self, width=w, height=h, bg='white')\n self.human_blank_img = tk.PhotoImage(width=w, height=h)\n self.human_canvas.create_image((w/2,h/2), image=self.human_blank_img, state='normal')\n self.human_canvas.image = self.human_blank_img\n self.human_canvas.grid(row=0, column=1)\n\n # 人間の手の画像の読み込み\n self.human_gu_img = ImageTk.PhotoImage(image=Image.open('ml-images/human_gu.png'))\n self.human_choki_img = ImageTk.PhotoImage(image=Image.open('ml-images/human_choki.png'))\n self.human_pa_img = ImageTk.PhotoImage(image=Image.open('ml-images/human_pa.png'))\n\n # メッセージ表示領域の初期化\n self.message_canvas = tk.Canvas(self, width=2*w, height=30, bg='white')\n self.message_canvas.grid(row=1, column=0, columnspan=2)\n\n # 結果表示領域の初期化\n self.result_canvas = tk.Canvas(self, width=2*w, height=30, bg='white')\n self.result_canvas.grid(row=2, column=0, columnspan=2)\n\n # じゃんけん開始ボタンの初期化\n self.janken_btn = tk.Button(self, text='じゃんけん開始', command=self.janken_start, relief='raised')\n self.janken_btn.grid(row=3, column=0)\n\n # クリアボタンの初期化\n self.reset_btn = tk.Button(self, text='集計のクリア', command=self.clear)\n self.reset_btn.grid(row=3, column=1)\n\n # クリアボタンが押されたときに呼ばれる関数\n def clear(self):\n global draw, lose, win\n draw = 0\n lose = 0\n win = 0\n self.message_canvas.delete('all')\n result_text = 'あなたの勝ち: {0:d}, 負け: {1:d}, あいこ: {2:d} '.format(win, lose, draw)\n self.result_canvas.delete('all')\n self.result_canvas.create_text(200, 15, text=result_text)\n\n # じゃんけんが動作中かチェックするための関数\n def jankenAlive(self):\n try:\n self.jankenthread.is_alive()\n except AttributeError:\n return False\n\n # じゃんけんを停止するための関数\n def jankenStop(self):\n try:\n self.jankenthread.join()\n except AttributeError:\n pass\n\n # じゃんけん開始ボタンが押されたときに呼ばれる関数\n def janken_start(self):\n global jankenLoop\n global jankenFirst\n if jankenLoop == False:\n jankenLoop = True\n jankenFirst = True\n if not self.jankenAlive():\n self.jankenthread = threading.Thread(target=self.janken_loop)\n self.jankenthread.start()\n self.janken_btn.config(relief='sunken')\n self.reset_btn.config(state='disabled')\n else:\n jankenLoop = False\n self.janken_btn.config(relief='raised')\n self.reset_btn.config(state='normal')\n\n # じゃんけんのループ\n def janken_loop(self):\n w = self.w\n h = self.h\n global jankenLoop\n global jankenFirst\n while jankenLoop == True:\n time.sleep(1)\n if jankenFirst == True:\n message_text = 'じゃんけん'\n self.message_canvas.delete('all')\n self.message_canvas.create_text(200, 15, text=message_text)\n args = ['mpg321', '-q', 'ml-sound/jankenpon.mp3']\n process = subprocess.Popen(args).wait()\n jankenFirst = False\n else:\n args = ['mpg321', '-q', 'ml-sound/pon.mp3']\n process = subprocess.Popen(args).wait()\n # メッセージ領域に「ぽん!」と表示\n message_text = 'ぽん!'\n self.message_canvas.delete('all')\n self.message_canvas.create_text(200, 15, text=message_text)\n\n # 人間の手を画像処理の結果から決定\n j = recognizedHand\n global Jprev\n # 過去のじゃんけんの手(ベクトル形式)をscikit_learn形式に\n Jprev_set = np.array([Jprev])\n # 現在のじゃんけんの手(0~2の整数)をscikit_learn形式に\n jnow_set = np.array([j])\n\n # コンピュータが、過去の手から人間の現在の手を予測\n jpredict = clf_janken.predict(Jprev_set)\n\n # 人間の手\n your_choice = j\n # 予測を元にコンピュータが決めた手\n # 予測がグーならパー、予測がチョキならグー、予測がパーならチョキ\n comp_choice = (jpredict[0] + 2)%3\n\n if comp_choice == 0:\n # コンピュータのグー画像表示\n self.comp_canvas.create_image((w/2,h/2), image=self.comp_gu_img, state='normal')\n self.comp_canvas.image = self.comp_gu_img\n elif comp_choice == 1:\n # コンピュータのチョキ画像表示\n self.comp_canvas.create_image((w/2,h/2), image=self.comp_choki_img, state='normal')\n self.comp_canvas.image = self.comp_choki_img\n else:\n # コンピュータのパー画像表示\n self.comp_canvas.create_image((w/2,h/2), image=self.comp_pa_img, state='normal')\n self.comp_canvas.image = self.comp_pa_img\n\n if your_choice == 0:\n # 人間のグー画像表示\n self.human_canvas.create_image((w/2,h/2), image=self.human_gu_img, state='normal')\n self.human_canvas.image = self.human_gu_img\n elif your_choice == 1:\n # 人間のチョキ画像表示\n self.human_canvas.create_image((w/2,h/2), image=self.human_choki_img, state='normal')\n self.human_canvas.image = self.human_choki_img\n else:\n # 人間のパー画像表示\n self.human_canvas.create_image((w/2,h/2), image=self.human_pa_img, state='normal')\n self.human_canvas.image = self.human_pa_img\n\n # 勝敗結果を更新 \n global draw, lose, win\n if your_choice == comp_choice:\n draw += 1\n elif your_choice == (comp_choice+1)%3:\n lose += 1\n else:\n win += 1\n\n # 勝敗結果を表示\n result_text = 'あなたの勝ち: {0}, 負け: {1}, あいこ: {2} '.format(win, lose, draw)\n self.result_canvas.delete('all')\n self.result_canvas.create_text(200, 15, text=result_text)\n \n # 過去の手(入力データ)と現在の手(ターゲット)とでオンライン学習 \n clf_janken.partial_fit(Jprev_set, jnow_set)\n\n # 過去の手の末尾に現在のコンピュータの手を追加\n Jprev = np.append(Jprev[3:], janken_array[comp_choice])\n # 過去の手の末尾に現在の人間の手を追加\n Jprev = np.append(Jprev[3:], janken_array[your_choice])\n\nroot = tk.Tk()\napp = Application(master=root)\napp.master.title('ディープじゃんけん(音声短縮版)')\napp.mainloop()\n","sub_path":"ml-10-10-janken-deep-shorten-tf.py","file_name":"ml-10-10-janken-deep-shorten-tf.py","file_ext":"py","file_size_in_byte":17546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"57821901","text":"import sys\n\nopcodes = {\n\t\"NOP\": \"00\",\n\n\t\"LOAD\": \"01\", # M(X) => AC\n\t\"LOADN\": \"02\", # -1 * M(X) => AC\n\t\"LOADA\": \"03\", # abs(M(X)) => AC\n\t\"LOADMQ\": \"0A\", # [MQ] => AC\n\t\"LOADMQM\": \"09\", # M(X) => MQ\n\t\"STOR\": \"21\", # [AC] => M(X)\n\n\t\"JUMPL\": \"0D\", # JUMP M(X, 0:19)\n\t\"JUMPR\": \"0E\", # JUMP M(X,20:39)\n\t\"JUMP+L\": \"0F\", # JUMP+ M(X, 0:19)\n\t\"JUMP+R\": \"10\", # JUMP+ M(X,20:39)\n\n\t\"ADD\": \"05\", # [AC] + M(X) => AC\n\t\"ADDA\": \"07\", # [AC] + abs(M(X)) => AC\n\t\"SUB\": \"06\", # [AC] - M(X) => AC\n\t\"SUBA\": \"08\", # [AC] - abs(M(X)) => AC\n\t\"MUL\": \"0B\", # [MQ] * M(X) => AC:MQ\n\t\"DIV\": \"0C\", # [MQ] / M(X) => MQ; [MQ] % M(X) => AC\n\n\t\"LSH\": \"14\", # [AC] << 1 => AC\n\t\"RSH\": \"15\", # [AC] >> 1 => AC\n\n\t\"STORL\": \"12\", # [AC, 8:19] => M(X, 8:19)\n\t\"STORR\": \"13\" # [AC, 8:19] => M(X,20:39)\n}\n\nlabels = {}\n\ndef label(label, addr, right):\n\n\tif label in labels:\n\t\tprint(\"A label {} já foi usada.\".format(label), file=sys.stderr)\n\t\traise SystemExit\n\n\tlabels[label] = (addr, right)\n\ndef oper(op, operand):\n\n\tif op not in opcodes:\n\t\tprint(\"Instrução desconhecida: {}.\".format(op), file=sys.stderr)\n\t\traise SystemExit\n\n\treturn \"{} {}\".format(opcodes[op], operand)\n\ndef load(oper):\n\n\topers = list(map(str.strip, oper.split(\",\")))\n\n\tif len(opers) > 1 and opers[0] == \"MQ\":\n\t\treturn \"{} {}\".format(opcodes[\"LOADMQM\"], opers[1])\n\telif len(opers) > 1:\n\t\tprint(\"Instrução não reconhecida: LOAD {}.\".format(oper),\n\t\t\t\tfile=sys.stderr)\n\t\traise SystemExit\n\telif oper == \"MQ\":\n\t\treturn opcodes[\"LOADMQ\"] + \" 000\"\n\telif oper.startswith(\"-\"):\n\t\treturn \"{} {}\".format(opcodes[\"LOADN\"], oper[1:])\n\telif oper.startswith(\"|\"):\n\t\treturn \"{} {}\".format(opcodes[\"LOADA\"], oper.strip(\"|\"))\n\n\treturn \"{} {}\".format(opcodes[\"LOAD\"], oper)\n\ndef jump(op, label):\n\n\tif label not in labels:\n\t\tprint(\"A label {} não existe.\".format(label), file=sys.stderr)\n\t\traise SystemExit\n\n\taddr, right = labels[label]\n\n\top += \"R\" if right else \"L\"\n\n\treturn \"{} {:03x}\".format(opcodes[op], addr).upper()\n\ndef parselabels(asm):\n\n\t_addr = 0x000\n\traddr = False\n\trms = []\n\n\tfor i in asm:\n\t\tl = i.split()[0]\n\n\t\tif l.endswith(\":\"):\n\t\t\tlabel(l.rstrip(\":\"), _addr, raddr)\n\t\t\trms.append(i)\n\t\t\tcontinue\n\n\t\tif raddr:\n\t\t\t_addr += 1\n\n\t\traddr = not raddr\n\n\treturn rms\n","sub_path":"ias-old/iasop.py","file_name":"iasop.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"535953839","text":"## x=linhas e y=colunas\ndef retangulo(x,y):\n if x < 1:\n x = 1\n if x > 20:\n x = 20\n if y < 1:\n y = 1\n if y > 20:\n y = 20\n\n print(\"-\"*(x))\n print(\"|\"*(y))\n print(\"-\"*(x))\n \n \n","sub_path":"Python/funcoes/at13.py","file_name":"at13.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"28715373","text":"#1.手动去重\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n if not nums:\n return []\n nums.sort()\n nLen = len(nums)\n res = []\n def twoSum(startIndex, target):\n leftPtr = startIndex\n rightPtr = nLen - 1\n while leftPtr < rightPtr:\n if nums[leftPtr] + nums[rightPtr] == target:\n res.append([-target, nums[leftPtr], nums[rightPtr]])\n leftPtr += 1\n while leftPtr < nLen and nums[leftPtr] == nums[leftPtr - 1]:\n leftPtr += 1\n rightPtr -= 1\n while rightPtr > startIndex and nums[rightPtr] == nums[rightPtr + 1]:\n rightPtr -= 1\n elif nums[leftPtr] + nums[rightPtr] < target:\n leftPtr += 1\n while leftPtr < nLen and nums[leftPtr] == nums[leftPtr - 1]:\n leftPtr += 1\n else:\n rightPtr -= 1\n while rightPtr > startIndex and nums[rightPtr] == nums[rightPtr + 1]:\n rightPtr -= 1\n\n for i in range(nLen - 2):\n if nums[i] + nums[i + 1] + nums[i + 2] > 0:\n break\n if nums[i] + nums[-1] + nums[-2] < 0:\n continue\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n twoSum(i + 1, -nums[i])\n return res \n \n\n#2.利用set去重","sub_path":"Hot100/15. 三数之和.py","file_name":"15. 三数之和.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"69696820","text":"import numpy as np\n\n\ndef readtext(file):\n x1 = []\n x2 = []\n with open(file,'r') as f:\n for x in next(f).split():\n x1.append(float(x))\n for line in f:\n for x in line.split():\n x2.append(float(x))\n shape = (2,len(x1))\n data = np.zeros(shape)\n data[0,:] = x1\n data[1,:] = x2\n return data","sub_path":"Exercise01/ml/readtext.py","file_name":"readtext.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"512222877","text":"#coding=utf-8\r\nimport datetime\r\nfrom django import template\r\nfrom django.conf import settings\r\nfrom cgi import escape\r\nfrom django.utils.translation import ugettext_lazy as _, ugettext\r\nfrom django.core.cache import cache\r\nfrom dbapp.data_utils import hasPerm\r\nfrom django.db import models\r\nfrom django.utils.encoding import force_unicode, smart_str\r\nfrom dbapp.file_handler import get_model_image\r\n\r\nregister = template.Library()\r\n@register.inclusion_tag('dbapp_filters.html')\r\ndef filters(cl):\r\n return {'cl': cl}\r\n\r\ndef filter(cl, spec):\r\n return {'title': spec.title(), 'choices' : list(spec.choices(cl)), 'field': spec.fieldName()}\r\nfilter = register.inclusion_tag('dbapp_filter.html')(filter)\r\n\r\n\r\n@register.simple_tag\r\ndef current_time(format_string):\r\n return str(datetime.datetime.now())\r\n\r\n@register.simple_tag\r\ndef get_this_year():\r\n\timport datetime\r\n\treturn datetime.datetime.now().strftime(\"%Y\")\r\n\r\n\r\n@register.filter\r\ndef escape_js_html(value):\r\n from django.utils.html import escape\r\n from django.template.defaultfilters import escapejs\r\n return escapejs(escape(value))\r\n\r\n@register.filter\r\ndef format_date(fielddatetime):\r\n return fielddatetime.strftime(\"%Y-%m-%d\")\r\n\r\n@register.filter\r\ndef translate_str(str):\r\n from django.utils.translation import ugettext as _\r\n if str:\r\n return _(str)\r\n else:\r\n return \"\"\r\n\r\n@register.filter\r\ndef format_int(float_value):\r\n return int(float_value)\r\n\r\n@register.filter\r\ndef format_shorttime(fielddatetime): \r\n return fielddatetime.strftime(\"%H:%M\")\r\n\r\n@register.filter\r\ndef HasPerm(user, operation): #判断一个登录用户是否有某个权限\r\n return user.has_perm(operation)\r\n\r\n@register.filter\r\ndef format_whether(value): \r\n if value:\r\n return ugettext(u\"是\")\r\n else:\r\n return ugettext(u\"否\")\r\n\r\n@register.filter\r\ndef format_whether2(value): \r\n if value==\"1\":\r\n return ugettext(u\"是\")\r\n elif value==\"2\":\r\n return ugettext(u\"否\")\r\n else:\r\n return ugettext(u\"处理中\")\r\n\r\n \r\n@register.filter\r\ndef reqHasPerm(request, operation): #判断一个当前请求的数据模型表是否有某个权限\r\n '''\r\n 判断一个当前请求是否有某个操作的权限\r\n '''\r\n return hasPerm(request.user, request.model, operation)\r\n\r\n@register.filter\r\ndef hasApp(app_label):\r\n '''\r\n 判断是否存在某个app\r\n '''\r\n from django.conf import settings\r\n if \"&\" in app_label:\r\n for app in app_label.split(\"&\"):\r\n if app.strip() not in settings.INSTALLED_APPS: return False\r\n return True\r\n elif \"|\" in app_label:\r\n for app in app_label.split(\"|\"):\r\n if app.strip() in settings.INSTALLED_APPS: return True\r\n return False\r\n return (app_label in settings.INSTALLED_APPS)\r\n\r\n#用于返回当前系统(站点)是否为oem\r\n@register.filter\r\ndef is_oem(site):#site变量暂无实际意义。\r\n from django.conf import settings\r\n return settings.OEM \r\n\r\n##用于返回当前系统(站点)是否是将zkeco当做zkaccess\r\n#@register.filter\r\n#def zkeco_as_zkaccess(site):#site变量暂无实际意义。\r\n# from django.conf import settings\r\n# return settings.ZKECO_AS_ZKACCESS\r\n\r\n@register.filter\r\ndef buttonItem(request, operation): #根据一项操作产生操作菜单项!!!\r\n if hasPerm(request.user, request.model, operation):\r\n return u'
  • %s
  • '%(iclock_url_rel, model.__name__, model._meta.verbose_name)\r\n else:\r\n return u'
  • '+model._meta.verbose_name+'
  • '\r\n \r\n\r\n@register.simple_tag\r\ndef version():\r\n return settings.VERSION+' by ZKSoftware Inc.'\r\n\r\n@register.simple_tag\r\ndef capTrans(s):\r\n return ugettext(u\"%s\"%s).capitalize()\r\n\r\n@register.filter\r\ndef cap(s):\r\n return (u\"%s\"%s).capitalize()\r\n\r\n@register.filter\r\ndef enabled_udisk_mod(mod_name):\r\n return (\"udisk\" in settings.ENABLED_MOD)\r\n@register.filter\r\ndef enabled_weather_mod(mod_name):\r\n return (\"weather\" in settings.ENABLED_MOD)\r\n@register.filter\r\ndef enabled_msg_mod(mod_name):\r\n return (\"msg\" in settings.ENABLED_MOD)\r\n@register.filter\r\ndef enabled_att_mod(mod_name):\r\n return (\"att\" in settings.ENABLED_MOD)\r\n@register.filter\r\ndef enabled_mod(mod_name):\r\n return (mod_name in settings.ENABLED_MOD)\r\n\r\n@register.filter\r\ndef lescape(s):\r\n if not s: return \"\"\r\n s=escape(s)\r\n return escape(s).replace(\"\\n\",\"\\\\n\").replace(\"\\r\",\"\\\\r\").replace(\"'\",\"'\").replace('\"','"')\r\n\r\n@register.filter\r\ndef isoTime(value):\r\n if value:\r\n return str(value)[:19]\r\n if value==0:\r\n return \"0\"\r\n return \"\"\r\n\r\n@register.filter\r\ndef stdTime(value):\r\n if value:\r\n return value.strftime(settings.STD_DATETIME_FORMAT)\r\n return \"\"\r\n\r\n\r\n@register.filter\r\ndef shortTime(value):\r\n if value:\r\n return value.strftime(settings.SHORT_DATETIME_FMT)\r\n return \"\"\r\n\r\n@register.filter\r\ndef vshortTime(value):\r\n if value:\r\n return value.strftime(settings.VSHORT_DATETIME_FMT)\r\n return \"\"\r\n\r\n@register.filter\r\ndef shortDTime(value):\r\n if value:\r\n return value.strftime(settings.SHORT_DATETIME_FMT2)\r\n return \"\"\r\n\r\n@register.filter\r\ndef onlyTime(value):\r\n if value:\r\n try:\r\n return value.strftime(settings.TIME_FMT)\r\n except:\r\n return (value+datetime.timedelta(100)).strftime(settings.TIME_FMT)\r\n else:\r\n return \"\"\r\n\r\n@register.filter\r\ndef shortDate(value):\r\n if value:\r\n return value.strftime(settings.DATE_FMT)\r\n return \"\"\r\n\r\n@register.filter\r\ndef shortDate4(value):\r\n if value:\r\n return value.strftime(settings.DATE_FMT4)\r\n return \"\"\r\n\r\n\r\n@register.filter\r\ndef left(value, size):\r\n s=(u\"%s\"%value)\r\n if len(s)>size:\r\n return s[:size]+\" ...\"\r\n return s\r\n\r\n@register.simple_tag#{% user_perms \"personnel.Employee\"%}\r\ndef user_perms(app_label_model_name):\r\n from django.contrib.contenttypes.models import ContentType\r\n from django.contrib.auth.models import Permission\r\n from base.model_utils import GetModel\r\n from base.middleware import threadlocals\r\n user=threadlocals.get_current_user()\r\n split=app_label_model_name.split(\".\")\r\n m=GetModel(split[0],split[1])\r\n ct=ContentType.objects.get_for_model(m)\r\n perms=[p.codename for p in Permission.objects.filter(content_type=ct) if user.has_perm(split[0]+\".\"+p.codename)]\r\n perms=sorted(perms)\r\n return \".\".join(perms)\r\n \r\n@register.filter\r\ndef PackList(values, field):\r\n l=[]\r\n for s in values:\r\n l.append(s[field])\r\n return ','.join(l)\r\n\r\n@register.filter\r\ndef detail_str(master_field):\r\n return u', '.join([u'%s'%obj for obj in master_field.all()])\r\n\r\n#@register.filter\r\n#def add_link(field):\r\n #from dbapp import urls\r\n #return u\"%s\"%(field)\r\n #return u\"%s\"%(field)\r\n\r\n@register.filter\r\ndef detail_list(master_field, split=u\",\", max_count=1000000):\r\n from dbapp import urls\r\n objs=master_field.all()\r\n filter, key=master_field.core_filters.items()[0]\r\n def edit_link(obj):\r\n return u\"%s\"%(\\\r\n urls.get_obj_url(obj), filter, key, obj)\r\n def add_link():\r\n return u\"%s\"%(\\\r\n urls.get_model_new_url(master_field.model), filter, key, ugettext('Add'))\r\n has_add=max_count>len(objs)\r\n if not objs and has_add: return add_link()\r\n return split.join([edit_link(obj) for obj in objs])+(has_add and u\" | \"+add_link() or \"\")\r\n\r\n@register.filter\r\n#通用过滤器-----可供首卡开门、多卡开门使用\r\ndef detail_list_set(master_field, max_count=10000):\r\n from dbapp import urls\r\n model = master_field.__dict__['model']\r\n app_label = model._meta.app_label\r\n objs=master_field.all()\r\n filter, key=master_field.core_filters.items()[0]\r\n def add_link():\r\n return u\"%s\"%(app_label, model.__name__, filter, key, ugettext(u'设置'))\r\n \r\n return ugettext(u'已设置数:%(d)d | %(s)s') % { 'd': objs.__len__(), 's': add_link()} or \"\"\r\n\r\n@register.filter\r\ndef detail_list_emp(master_field, max_count=1000000):\r\n from dbapp import urls\r\n objs=master_field.all()\r\n filter, key=master_field.core_filters.items()[0]\r\n def edit_link(obj):\r\n return u\"%s\"%(\\\r\n urls.get_obj_url(obj), filter, key, obj)\r\n def add_link():\r\n return u\"%s\"%(\\\r\n urls.get_model_new_url(master_field.model), filter, key, ugettext('Add'))\r\n has_add=max_count>len(objs)\r\n if not objs and has_add: return add_link()\r\n return u', '.join([edit_link(obj) for obj in objs])+(has_add and u\" | \"+add_link() or \"\")\r\n\r\n\r\n\r\n@register.filter\r\n#detail_list从表max_count为1的特殊情况\r\ndef detail_list_one(master_field, max_count=1):\r\n from dbapp import urls\r\n objs=master_field.all()#最多一条记录\r\n filter, key=master_field.core_filters.items()[0]\r\n def edit_del_link(obj):\r\n #m_objs = master_field.model.objects.all()\r\n return u\"%s %s\"%(\\\r\n urls.get_obj_url(obj), filter, key, ugettext(u'修改'), urls.get_model_data_url(master_field.model), urls.get_obj_url(obj).split(\"/\")[-2], ugettext(u'删除'))\r\n def add_link():\r\n return u\"%s\"%(\\\r\n urls.get_model_new_url(master_field.model), filter, key, ugettext(u'设置'))\r\n has_add=max_count>len(objs)\r\n if not objs and has_add: return add_link()\r\n return edit_del_link(objs[0])\r\n\r\n\r\ndef _(s): return s\r\n\r\nCmdContentNames={'DATA USER PIN=':_(u'人员信息'),\r\n 'DATA FP PIN=':_(u'指纹'),\r\n 'DATA DEL_USER PIN=':_(u'删除人员'),\r\n 'DATA DEL_FP PIN=':_(u'删除指纹'),\r\n 'CHECK':_(u'检查服务器配置'),\r\n 'INFO':_(u'更新服务器上的设备信息'),\r\n 'CLEAR LOG':_(u'清除考勤记录'),\r\n 'RESTART':_(u'重新启动设备'),\r\n 'REBOOT':_(u'重新启动设备'),\r\n 'LOG':_(u'检查并传送新数据'),\r\n 'PutFile':_(u'发送文件到设备'),\r\n 'GetFile':_(u'从设备传文件'),\r\n 'Shell':_(u'执行内部命令'),\r\n 'SET OPTION':_(u'修改配置'),\r\n 'CLEAR DATA':_(u'清除设备上的所有数据'),\r\n 'AC_UNLOCK':_(u'输出开门信号'),\r\n 'AC_UNALARM':_(u'中断报警信号'),\r\n 'ENROLL_FP':_(u'登记人员指纹'),\r\n}\r\n\r\ndef getContStr(cmdData):\r\n for key in CmdContentNames:\r\n if key in cmdData:\r\n return CmdContentNames[key]\r\n return \"\" #_(\"Unknown command\")\r\n\r\n@register.filter\r\ndef cmdName(value):\r\n return getContStr(value)\r\n\r\nDataContentNames={\r\n 'TRANSACT':_(u'考勤记录'),\r\n 'USERDATA':_(u'人员信息及其指纹')}\r\n\r\n@register.filter\r\ndef dataShowStr(value):\r\n if value in DataContentNames:\r\n return value+\" \"+DataContentNames[value]+\"\"\r\n return value\r\n\r\n@register.filter\r\ndef cmdShowStr(value):\r\n return left(value, 30)+\" \"+getContStr(value)+\"\"\r\n\r\n@register.filter\r\ndef thumbnail_url(obj, field=\"\"):\r\n try:\r\n url=obj.get_thumbnail_url()\r\n if url:\r\n try:\r\n fullUrl=obj.get_img_url()\r\n except: #only have thumbnail, no real picture\r\n return \"\"%url\r\n else:\r\n if not fullUrl:\r\n return \"\"%url\r\n return \"\"%(fullUrl, url)\r\n except:\r\n import os\r\n f=getattr(obj, field or 'pk')\r\n if callable(f): f=f()\r\n fn=\"%s.jpg\"%f\r\n fns=get_model_image(obj.__class__, fn, \"photo\", True) #image_file, image_url, thumbnail_file, thumbnail_url\r\n #print fns\r\n if fns[0]:\r\n if fns[2]: #has thumbnail\r\n return \"\"%(fns[1], fns[3])\r\n else:\r\n return \"\"%(fns[1], fns[1])\r\n elif fns[2]:\r\n return \"\"%fns[3]\r\n return \"\"\r\n\r\n#表单里的label_suffix,非filter---add by darcy 20100605\r\ndef label_tag(field): #-------------------------------------------- 没有 @register.filter 无用\r\n label_suffix = ':'\r\n label_tag = field.label_tag()\r\n label = label_tag.split('<')[1].split('>')[1]\r\n if label[-1] not in ':?.!':\r\n label += label_suffix \r\n return field.label_tag(label)\r\n\r\n#表单里的label_suffix(无星号,可用于查询)---add by darcy 20100617\r\n@register.filter \r\ndef field_as_label_tag_no_asterisk(field):\r\n result = label_tag(field)\r\n if result.__contains__(\"required\"):\r\n result = result.replace('required','')\r\n return \"\"\"%s\"\"\"%result\r\n\r\n#表单里的label_suffix(有星号(非必填项),前端判空)---add by darcy 20101225\r\n@register.filter \r\ndef field_as_label_tag_asterisk(field):\r\n result = label_tag(field)\r\n if not result.__contains__(\"required\"):\r\n result = result.replace('label for', 'label class=\"required\" for')\r\n return \"\"\"%s\"\"\" % result\r\n\r\n\r\n#只返回label_tag包含:和for等\r\n@register.filter \r\ndef field_as_label_tag(field):\r\n return \"\"\"%s\"\"\" % label_tag(field)\r\n\r\n#返回help_text 字段中的注释\r\n@register.filter \r\ndef field_as_help_text(field):\r\n return field.help_text and (\"%s\"%unicode(field.help_text)) or \"\"\r\n\r\n@register.filter \r\ndef field_format(field, fmt_str):\r\n return fmt_str%{ \\\r\n 'label_tag':label_tag(field), \r\n 'as_widget':field.as_widget(), \r\n 'errors':field.errors and \"
      %s
    \"%(\"\".join([\"
  • %s
  • \"%e for e in field.errors])) or \"\",\r\n 'help_text':field.help_text and (\"%s\"%unicode(field.help_text)) or \"\"\r\n }\r\n\r\n@register.filter \r\ndef field_as_td_h(field, colspan=1):\r\n return \"\"\"%s%s%s%s\"\"\"%( \\\r\n label_tag(field),\r\n\t\tcolspan>1 and \" colspan=%s\"%colspan or \"\",\r\n field.as_widget(), \r\n field.errors and \"
      %s
    \"%(\"\".join([\"
  • %s
  • \"%e for e in field.errors])) or \"\",\r\n field.help_text and (\"%s\"%unicode(field.help_text)) or \"\"\r\n )\r\n\r\n#将表中无星号的在表单中添加星号(用户设备表等)\r\n@register.filter \r\ndef field_as_td_h_asterisk(field, colspan=1):\r\n return \"\"\"%s%s%s%s\"\"\"%( \\\r\n field_as_label_tag_asterisk(field),\r\n\t\tcolspan>1 and \" colspan=%s\"%colspan or \"\",\r\n field.as_widget(), \r\n field.errors and \"
      %s
    \"%(\"\".join([\"
  • %s
  • \"%e for e in field.errors])) or \"\",\r\n field.help_text and (\"%s\"%unicode(field.help_text)) or \"\"\r\n )\r\n\r\n \r\n@register.filter \r\ndef field_as_ul_li(field):\r\n return \"\"\"
    • %s
    • %s%s%s
    \"\"\"%( \\\r\n label_tag(field), \r\n field.as_widget(), \r\n #\"\"%field.name,\r\n field.errors and \"
      %s
    \"%(\"\".join([\"
  • %s
  • \"%e for e in field.errors])) or \"\",\r\n field.help_text and (\"%s\"%unicode(field.help_text)) or \"\"\r\n )\r\n \r\n\r\n@register.filter \r\n#用于不需要显示label的特殊模板\r\ndef field_as_td_h_special(field):\r\n return \"\"\"%s%s%s\"\"\"%( \\\r\n field.as_widget(), \r\n field.errors and \"
      %s
    \"%(\"\".join([\"
  • %s
  • \"%e for e in field.errors])) or \"\",\r\n field.help_text and (\"%s\"%unicode(field.help_text)) or \"\"\r\n )\r\n\r\n@register.filter \r\n#用于不需要显示label的特殊模板--不显示td\r\ndef field_as_no_td(field):\r\n return \"\"\"%s%s%s\"\"\"%( \\\r\n field.as_widget(), \r\n field.errors and \"
      %s
    \"%(\"\".join([\"
  • %s
  • \"%e for e in field.errors])) or \"\",\r\n field.help_text and (\"%s\"%unicode(field.help_text)) or \"\"\r\n )\r\n\r\n@register.filter \r\n#用于不需要显示label的特殊模板(带自动输入)\r\ndef field_as_td_h_tz(field):\r\n return \"\"\"
    %s%s%s
    \"\"\"%( \\\r\n field.as_widget(), \r\n field.errors and \"
      %s
    \"%(\"\".join([\"
  • %s
  • \"%e for e in field.errors])) or \"\",\r\n field.help_text and (\"%s\"%unicode(field.help_text)) or \"\",\r\n field.name\r\n )\r\n\r\n\r\n@register.filter \r\ndef field_as_td_v(field):\r\n return \"\"\"%s
    %s%s%s\"\"\"%( \\\r\n label_tag(field), \r\n field.as_widget(), \r\n field.errors and \"
      %s
    \"%(\"\".join([\"
  • %s
  • \"%e for e in field.errors])) or \"\",\r\n field.help_text and (\"
    %s\"%unicode(field.help_text)) or \"\"\r\n )\r\n\r\n\r\n@register.filter\r\ndef int_color(color):\r\n if color:\r\n return \" \"%(color>>16&0xff, color>>8&0xff ,color&0xff)\r\n else:\r\n return \" \"\r\n@register.filter\r\ndef boolean_icon(value):\r\n\tif value:\r\n\t\treturn u\"%s\"%(settings.MEDIA_URL, ugettext(u'是'))\r\n\treturn u\"%s\"%(settings.MEDIA_URL, ugettext(u'否'))\r\n\r\n@register.filter\r\ndef treeview(dept, node=\"li\"):\r\n TREE_SPACE=\"<%(n)s class='space'>\"%{\"n\": node}\r\n TREE_PARENT_LINE=\"<%(n)s class='parent_line'>\"%{\"n\": node}\r\n TREE_LEAF=\"<%(n)s class='leaf'>\"%{\"n\": node}\r\n TREE_LAST_LEAF=\"<%(n)s class='last'>\"%{\"n\": node}\r\n TREE_FOLDER=\"<%(n)s class='folder'>\"%{\"n\": node}\r\n TREE_FIRST_FOLDER=\"<%(n)s class='folder first'>\"%{\"n\": node}\r\n TREE_LAST_FOLDER=\"<%(n)s class='folder last'>\"%{\"n\": node}\r\n TREE_CONVERT={'l':TREE_PARENT_LINE, ' ':TREE_SPACE, 'L':TREE_LAST_LEAF}\r\n TREE_FOLDER_CONVERT={'l':TREE_PARENT_LINE, ' ':TREE_SPACE, 'L':TREE_LAST_FOLDER}\r\n if not hasattr(dept, \"tree_prefix\") or not dept.tree_prefix:\r\n if dept.tree_folder:\r\n ret=TREE_FIRST_FOLDER\r\n else:\r\n ret=TREE_LEAF\r\n else:\r\n ret= [TREE_CONVERT[tp] for tp in dept.tree_prefix]\r\n if dept.tree_folder:\r\n ret[-1]=TREE_FOLDER\r\n if dept.tree_prefix[-1]=='L':\r\n ret[-1]=TREE_LAST_FOLDER\r\n elif dept.tree_prefix[-1]=='L':\r\n ret[-1]=TREE_LAST_LEAF\r\n else:\r\n ret[-1]=TREE_LEAF\r\n ret=TREE_SPACE+(''.join(ret))\r\n return u\"%s%s\"%(ret, dept)\r\n\r\n@register.filter\r\ndef mod_by(value, div):\r\n\treturn int(value)%int(div)\r\n\r\n","sub_path":"zkeco-core/python-support/dbapp/templatetags/dbapp_tags.py","file_name":"dbapp_tags.py","file_ext":"py","file_size_in_byte":19374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260653867","text":"import numpy as np \nimport pandas as pd \n\n#SAVE_DIR = '/Users/parkerf/Research/SkyModel/BOSS_Sky/ContFitting/files/'\n#LINE_LIST_DIR = '/Users/parkerf/Research/SkyModel/BOSS_Sky/ContFitting/FitTest/'\ndef main():\n airglow_line_list = pd.read_csv('airglow_lines.txt',delim_whitespace=True,skiprows=1)\n Lines = airglow_line_list[['obs_lam','FWHM','peak_int']]\n Lines.drop_duplicates(inplace=True)\n\n Lines['vacuum'] = air_to_vac(Lines['obs_lam'])\n BlueLines = Lines[(Lines['vacuum']>360)&(Lines['vacuum']<628)&(Lines['peak_int']>150)]['vacuum']\n RedLines = Lines[(Lines['vacuum']>570)&(Lines['vacuum']<1040)&(Lines['peak_int']>150)]['vacuum']\n\n Artificial = pd.read_csv('artificial_lines.csv')\n ArtLines = air_to_vac(np.array(Artificial[' wave'])/10.)\n BlueArt = ArtLines[(ArtLines>360)&(ArtLines<628)]\n RedArt = ArtLines[(ArtLines>570)&(ArtLines<1040)]\n\n BB = np.hstack([BlueLines,BlueArt])\n RR = np.hstack([RedLines,RedArt])\n\n NewBlue = remove_close_lines(BB)\n NewRed = remove_close_lines(RR)\n\n AllLines = np.hstack([NewBlue, NewRed])\n print(\"All Lines: \", len(np.unique(AllLines)))\n print(\"Blue Lines: \", len(np.unique(NewBlue)))\n print(\"Red Lines: \", len(np.unique(NewRed)))\n print(\"Artificial Lines: \", len(remove_close_lines(ArtLines)))\n\n np.save('blue_airglow_lines.npy', NewBlue)\n np.save('red_airglow_lines.npy', NewRed)\n\n\ndef air_to_vac(wave):\n \"\"\"Index of refraction to go from wavelength in air to wavelength in vacuum\n Equation from (Edlen 1966)\n vac_wave = n*air_wave\n \"\"\"\n #Convert to um\n wave_um = wave*.001\n ohm2 = (1./wave_um)**(2)\n\n #Calculate index at every wavelength\n nn = []\n for x in ohm2:\n n = 1+10**(-8)*(8342.13 + (2406030/float(130.-x)) + (15997/float(389-x)))\n nn.append(n)\n \n #Get new wavelength by multiplying by index of refraction\n vac_wave = nn*wave\n return vac_wave\n\ndef remove_close_lines(line_list):\n to_remove = []\n for i,line in enumerate(np.array(line_list)):\n if i == len(line_list)-1:\n pass\n else:\n diff = (line_list[i+1] - line)\n if diff<0.3:\n to_remove.append(i+1)\n \n NewLines = np.delete(line_list,np.array(to_remove))\n return(NewLines)\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"util/make_airglow_line_list.py","file_name":"make_airglow_line_list.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"632037077","text":"import csv\r\nimport numpy as np\r\nfilename = 'E:\\Pythonprojects\\KNN Project\\houses.csv'\r\nsamp_file = open(\"E:\\Pythonprojects\\KNN Project\\Sample.txt\",\"r\")\r\n'''import random#choose random data to usee\r\nstart_pts=[]\r\nfor r in range(0, 269, 10):\r\n start_pts.append(r)\r\nsamp=random.sample(start_pts, 19)\r\n\r\nfor s in samp:\r\n print(str(s))\r\n samp_file.write(str(s)+' ')'''\r\nsamp =[]\r\nfor line in samp_file:#inputs the randomly generated data point indexes so the same\r\n #ones are retrieved each time\r\n samp.append(int(line[:line.find(' ')]))\r\n\r\nwith open(filename) as f:#input data\r\n reader = csv.reader(f)\r\n header_row = next(reader)\r\n\r\n houses=[]\r\n \r\n for row in reader:\r\n houses.append(row[:9])#only want name and numerical rows\r\n f.close()\r\n#Separate Training from Testing Data\r\ntrain=[]\r\nfor pt in samp:\r\n for i in range(0,10):\r\n train.append(houses[pt+i])\r\n #print(houses[pt][0])\r\n\r\ntest=[]\r\nfor h in houses:\r\n if h not in train:\r\n test.append(h)\r\n #print(h[0])\r\n\r\n#create normalization formula for each column based on training data\r\nmins=['',10000000000,1000000,100000,1000,1000,1000,1000,10000000]\r\nmaxes=['',0,0,0,0,0,0,0,0]\r\n\r\nfor h in train:\r\n for i in range(1, len(h)):\r\n h[i]=float(h[i])\r\n if h[i]>float(maxes[i]):\r\n maxes[i]=h[i]\r\n elif h[i] None:\n tf.estimator.train_and_evaluate(\n estimator=estimator,\n train_spec=self.get_train_spec(),\n eval_spec=self.get_eval_spec(),\n )\n\n def create_estimator(\n self,\n model_params: Optional[Dict] = None,\n config: Optional[tf.estimator.RunConfig] = None,\n ) -> tf.estimator.Estimator:\n return tf.estimator.Estimator(\n model_fn=self.model.build_model_fn, params=model_params, config=config\n )\n\n def get_train_spec(self) -> tf.estimator.TrainSpec:\n return tf.estimator.TrainSpec(\n input_fn=self.train_dataset.input_fn,\n max_steps=self.hparams.max_steps,\n hooks=self._maybe_apply_hooks(),\n )\n\n def get_eval_spec(self) -> tf.estimator.EvalSpec:\n return tf.estimator.EvalSpec(\n input_fn=self.eval_dataset.input_fn,\n steps=10,\n hooks=self._maybe_apply_hooks(),\n )\n\n def _maybe_apply_hooks(self):\n hooks = None\n if self.hparams.stateful:\n hooks = [LSTMStateHook(self.hparams)]\n return hooks\n","sub_path":"elmo/trainer/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"584721702","text":"from typing import List\n\n\nclass Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n k %= len(nums)\n nums[:] = nums[-k:] + nums[:-k]\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n nums = [1, 2, 3, 4, 5, 6, 7]\n sol.rotate(nums, 3)\n\n print(nums == [5, 6, 7, 1, 2, 3, 4])\n","sub_path":"LeetCode/Interview questions/Easy/Array/3__646_Rotate_Array/solution2_better.py","file_name":"solution2_better.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"512254836","text":"from pkg_resources import get_distribution, DistributionNotFound\n\nfrom .runtime_001 import ( # noqa\n run_program,\n to_sexp_f,\n KEYWORD_TO_ATOM,\n KEYWORD_FROM_ATOM,\n)\n\ntry:\n __version__ = get_distribution(__name__).version\nexcept DistributionNotFound:\n # package is not installed\n __version__ = \"unknown\"\n","sub_path":"clvm/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"622262567","text":"import logging\nimport json\nimport os\nimport pkgutil\nimport sys\nimport importlib\n\nfrom watchdog.observers import Observer\nfrom logging.handlers import RotatingFileHandler\n\nimport redis\n\nfrom twisted.internet.protocol import Factory\nfrom twisted.internet import reactor, task\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nimport Houdini.Handlers as Handlers\nfrom Houdini.HandlerFileEventHandler import HandlerFileEventHandler\nfrom Houdini.Spheniscidae import Spheniscidae\nfrom Houdini.Penguin import Penguin\nfrom Houdini.Crumbs import retrieveItemCollection, retrieveRoomCollection,\\\n retrieveFurnitureCollection, retrieveFloorCollection, retrieveIglooCollection,\\\n retrievePinCollection, retrieveStampsCollection\nfrom Houdini.Handlers.Play.Pet import decreaseStats\n\n\"\"\"Deep debug\nfrom twisted.python import log\nlog.startLogging(sys.stdout)\n\"\"\"\n\nclass HoudiniFactory(Factory):\n\n def __init__(self, *kw, **kwargs):\n self.logger = logging.getLogger(\"Houdini\")\n\n configFile = kw[0]\n with open(configFile, \"r\") as fileHandle:\n self.config = json.load(fileHandle)\n\n self.serverName = kwargs[\"server\"]\n self.server = self.config[\"Servers\"][self.serverName]\n\n # Set up logging\n generalLogDirectory = os.path.dirname(self.server[\"Logging\"][\"General\"])\n errorsLogDirectory = os.path.dirname(self.server[\"Logging\"][\"Errors\"])\n\n if not os.path.exists(generalLogDirectory):\n os.mkdir(generalLogDirectory)\n\n if not os.path.exists(errorsLogDirectory):\n os.mkdir(errorsLogDirectory)\n\n universalHandler = RotatingFileHandler(self.server[\"Logging\"][\"General\"],\n maxBytes=2097152, backupCount=3, encoding=\"utf-8\")\n self.logger.addHandler(universalHandler)\n\n errorHandler = logging.FileHandler(self.server[\"Logging\"][\"Errors\"])\n errorHandler.setLevel(logging.ERROR)\n self.logger.addHandler(errorHandler)\n\n engineString = \"mysql://{0}:{1}@{2}/{3}\".format(self.config[\"Database\"][\"Username\"],\n self.config[\"Database\"][\"Password\"],\n self.config[\"Database\"][\"Address\"],\n self.config[\"Database\"][\"Name\"])\n\n self.databaseEngine = create_engine(engineString, pool_recycle=3600)\n self.createSession = sessionmaker(bind=self.databaseEngine)\n\n self.redis = redis.StrictRedis()\n\n self.players = {}\n\n self.logger.info(\"Houdini module initialized\")\n\n self.handlers = {}\n\n if self.server[\"World\"]:\n self.protocol = Penguin\n\n self.spawnRooms = (100, 300, 400, 800, 809, 230, 130)\n\n self.rooms = retrieveRoomCollection()\n self.items = retrieveItemCollection()\n self.furniture = retrieveFurnitureCollection()\n self.igloos = retrieveIglooCollection()\n self.floors = retrieveFloorCollection()\n self.pins = retrievePinCollection()\n self.stampGroups, self.stamps = retrieveStampsCollection()\n\n self.openIgloos = {}\n\n self.puffleKiller = task.LoopingCall(decreaseStats, self)\n self.puffleKiller.start(1800)\n\n self.loadHandlerModules()\n self.logger.info(\"Running world server\")\n else:\n self.protocol = Spheniscidae\n self.loadHandlerModules(\"Houdini.Handlers.Login.Login\")\n self.logger.info(\"Running login server\")\n\n def loadHandlerModules(self, strictLoad=()):\n for handlerModule in self.getPackageModules(Handlers):\n if not strictLoad or strictLoad and handlerModule in strictLoad:\n\n if handlerModule not in sys.modules.keys():\n importlib.import_module(handlerModule)\n\n self.logger.info(\"Handler modules loaded\")\n\n def getPackageModules(self, package):\n packageModules = []\n\n for importer, moduleName, isPackage in pkgutil.iter_modules(package.__path__):\n fullModuleName = \"{0}.{1}\".format(package.__name__, moduleName)\n\n if isPackage:\n subpackageObject = importlib.import_module(fullModuleName, package=package.__path__)\n subpackageObjectDirectory = dir(subpackageObject)\n\n if \"Plugin\" in subpackageObjectDirectory:\n packageModules.append((subpackageObject, moduleName))\n\n continue\n\n subPackageModules = self.getPackageModules(subpackageObject)\n\n packageModules = packageModules + subPackageModules\n else:\n packageModules.append(fullModuleName)\n\n return packageModules\n\n def buildProtocol(self, addr):\n session = self.createSession()\n\n player = self.protocol(session, self)\n\n return player\n\n def start(self):\n self.logger.info(\"Starting server..\")\n\n port = self.server[\"Port\"]\n\n handlerEventObserver = Observer()\n handlerEventObserver.schedule(HandlerFileEventHandler(), \"./Houdini/Handlers\", recursive=True)\n handlerEventObserver.start()\n\n self.logger.info(\"Listening on port {0}\".format(port))\n\n reactor.listenTCP(port, self)\n reactor.run()\n","sub_path":"Houdini/HoudiniFactory.py","file_name":"HoudiniFactory.py","file_ext":"py","file_size_in_byte":5372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"256504999","text":"from typing import List\n\nfrom discordmenu.embed.components import EmbedMain\nfrom discordmenu.embed.view import EmbedView\nfrom tsutils.menu.footers import embed_footer_with_state\n\nfrom padinfo.common.config import UserConfig\nfrom padinfo.view.components.view_state_base import ViewStateBase\n\n\nclass SimpleTextViewState(ViewStateBase):\n def __init__(self, original_author_id, menu_type, raw_query,\n color, message,\n reaction_list: List[str] = None,\n extra_state=None):\n super().__init__(original_author_id, menu_type, raw_query,\n reaction_list=reaction_list, extra_state=extra_state)\n self.message = message\n self.color = color\n\n def serialize(self):\n ret = super().serialize()\n ret.update({\n 'message': self.message,\n })\n return ret\n\n @classmethod\n async def deserialize(cls, _dbcog, user_config: UserConfig, ims: dict):\n original_author_id = ims['original_author_id']\n menu_type = ims['menu_type']\n raw_query = ims.get('raw_query')\n return cls(original_author_id, menu_type, raw_query, user_config.color, ims.get('message'),\n reaction_list=ims.get('reaction_list'), extra_state=ims)\n\n\nclass SimpleTextView:\n VIEW_TYPE = 'SimpleText'\n\n @staticmethod\n def embed(state: SimpleTextViewState):\n return EmbedView(\n EmbedMain(\n color=state.color,\n description=state.message\n ),\n embed_footer=embed_footer_with_state(state),\n )\n","sub_path":"padinfo/view/simple_text.py","file_name":"simple_text.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"211196851","text":"\"\"\"\nManage ECM Groups.\n\"\"\"\n\nfrom . import base\n\n\nclass Printer(object):\n \"\"\" Mixin for printing commands. \"\"\"\n\n expands = ','.join([\n 'statistics',\n 'product',\n 'account',\n 'target_firmware',\n 'settings_bindings.setting',\n 'configuration'\n ])\n\n def setup_args(self, parser):\n self.add_argument('-v', '--verbose', action='store_true')\n super().setup_args(parser)\n\n def prerun(self, args):\n self.printed_header = False\n self.printer = self.verbose_printer if args.verbose else \\\n self.terse_printer\n super().prerun(args)\n\n def bundle_group(self, group):\n group['target'] = '%s (%s)' % (group['product']['name'],\n group['target_firmware']['version'])\n if not isinstance(group['settings_bindings'], str):\n group['settings'] = dict((x['setting']['name'] + ':', x['value'])\n for x in group['settings_bindings']\n if not isinstance(x, str) and\n x['value'] is not None)\n else:\n group['settings'] = {}\n stats = group['statistics']\n group['online'] = stats['online_count']\n group['offline'] = stats['offline_count']\n group['total'] = stats['device_count']\n group['account_name'] = group['account']['name']\n return group\n\n def verbose_printer(self, groups):\n for x in groups:\n group = self.bundle_group(x)\n print('ID: ', group['id'])\n print('Name: ', group['name'])\n print('Online: ', group['online'])\n print('Total: ', group['total'])\n print('Target: ', group['target'])\n print('Account: ', group['account']['name'])\n print('Suspended: ', group['statistics']['suspended_count'])\n print('Synchronized: ', group['statistics']['synched_count'])\n if group['settings']:\n print('Settings...')\n for x in sorted(group['settings'].items()):\n print(' %-30s %s' % x)\n print()\n\n def terse_printer(self, groups):\n fields = (\n (\"name\", 'Name'),\n (\"id\", 'ID'),\n (\"account_name\", 'Account'),\n (\"target\", 'Target'),\n (\"online\", 'Online'),\n (\"offline\", 'Offline'),\n (\"total\", 'Total'),\n )\n rows = [[x[1] for x in fields]]\n rows.extend([x[f[0]] for f in fields]\n for x in map(self.bundle_group, groups))\n self.tabulate(rows)\n\n\nclass Show(Printer, base.ECMCommand):\n \"\"\" Show group(s). \"\"\"\n\n name = 'show'\n\n def setup_args(self, parser):\n self.add_argument('ident', metavar='GROUP_ID_OR_NAME', nargs='?',\n complete=self.make_completer('groups', 'name'))\n super().setup_args(parser)\n\n def run(self, args):\n if args.ident:\n groups = [self.api.get_by_id_or_name('groups', args.ident,\n expand=self.expands)]\n else:\n groups = self.api.get_pager('groups', expand=self.expands)\n self.printer(groups)\n\n\nclass Create(base.ECMCommand):\n \"\"\" Create a new group.\n A group mostly represents configuration for more than one device, but\n also manages settings such as alerts and log acquisition. \"\"\"\n\n name = 'create'\n\n def setup_args(self, parser):\n self.add_argument('--name')\n self.add_argument('--product')\n self.add_argument('--firmware')\n\n def run(self, args):\n name = args.name or input('Name: ')\n if not name:\n raise SystemExit(\"Name required\")\n\n product = args.product or input('Product: ')\n products = dict((x['name'], x)\n for x in self.api.get_pager('products'))\n if product not in products:\n if not product:\n print(\"Product required\")\n else:\n print(\"Invalid product:\", product)\n print(\"\\nValid products...\")\n for x in sorted(products):\n print(\"\\t\", x)\n raise SystemExit(1)\n\n fw = args.firmware or input('Firmware: ')\n firmwares = dict((x['version'], x)\n for x in self.api.get_pager('firmwares',\n product=products[product]['id']))\n if fw not in firmwares:\n if not fw:\n print(\"Firmware required\")\n else:\n print(\"Invalid firmware:\", fw)\n print(\"\\nValid firmares...\")\n for x in sorted(firmwares):\n print(\"\\t\", x)\n raise SystemExit(1)\n\n self.api.post('groups', {\n \"name\": name,\n \"product\": products[product]['resource_uri'],\n \"target_firmware\": firmwares[fw]['resource_uri']\n })\n\n\nclass Edit(base.ECMCommand):\n \"\"\" Edit group attributes. \"\"\"\n\n name = 'edit'\n\n def setup_args(self, parser):\n self.add_argument('ident', metavar='GROUP_ID_OR_NAME',\n complete=self.make_completer('groups', 'name'))\n self.add_argument('--name')\n self.add_argument('--firmware', help='Eg. 5.4.1')\n\n def run(self, args):\n group = self.api.get_by_id_or_name('groups', args.ident)\n updates = {}\n if args.name:\n updates['name'] = args.name\n if args.firmware:\n fw = self.api.get_by(['version'], 'firmwares', args.firmware)\n updates['target_firmware'] = fw['resource_uri']\n self.api.put('groups', group['id'], updates)\n\n\nclass Delete(base.ECMCommand):\n \"\"\" Delete one or more groups. \"\"\"\n\n name = 'delete'\n\n def setup_args(self, parser):\n self.add_argument('ident', metavar='GROUP_ID_OR_NAME', nargs='+',\n complete=self.make_completer('groups', 'name'))\n self.add_argument('-f', '--force', action=\"store_true\")\n\n def run(self, args):\n for ident in args.ident:\n group = self.api.get_by_id_or_name('groups', ident)\n if not args.force and \\\n not base.confirm('Delete group: %s' % group['name'],\n exit=False):\n continue\n self.api.delete('groups', group['id'])\n\n\nclass Move(base.ECMCommand):\n \"\"\" Move group to a different account. \"\"\"\n\n name = 'move'\n\n def setup_args(self, parser):\n self.add_argument('ident', metavar='GROUP_ID_OR_NAME',\n complete=self.make_completer('groups', 'name'))\n self.add_argument('new_account', metavar='NEW_ACCOUNT_ID_OR_NAME')\n self.add_argument('-f', '--force', action=\"store_true\")\n\n def run(self, args):\n group = self.api.get_by_id_or_name('groups', args.ident)\n account = self.api.get_by_id_or_name('accounts', args.new_account)\n self.api.put('groups', group['id'],\n {\"account\": account['resource_uri']})\n\n\nclass Search(Printer, base.ECMCommand):\n \"\"\" Search for groups. \"\"\"\n\n name = 'search'\n fields = ['name', ('firmware', 'target_firmware.version'),\n ('product', 'product.name'), ('account', 'account.name')]\n\n def setup_args(self, parser):\n searcher = self.make_searcher('groups', self.fields)\n self.lookup = searcher.lookup\n self.add_argument('search', metavar='SEARCH_CRITERIA', nargs='+',\n help=searcher.help, complete=searcher.completer)\n super().setup_args(parser)\n\n def run(self, args):\n results = list(self.lookup(args.search, expand=self.expands))\n if not results:\n raise SystemExit(\"No Results For: %s\" % ' '.join(args.search))\n self.printer(results)\n\n\nclass Groups(base.ECMCommand):\n \"\"\" Manage ECM Groups. \"\"\"\n\n name = 'groups'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.add_subcommand(Show, default=True)\n self.add_subcommand(Create)\n self.add_subcommand(Edit)\n self.add_subcommand(Delete)\n self.add_subcommand(Move)\n self.add_subcommand(Search)\n\ncommand_classes = [Groups]\n","sub_path":"ecmcli/commands/groups.py","file_name":"groups.py","file_ext":"py","file_size_in_byte":8313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"192380064","text":"import asyncio\nfrom concurrent.futures import ProcessPoolExecutor\nimport gym\nfrom tkinter import *\nfrom tkinter import messagebox\nimport time\nimport threading\n\nprint('running async test')\n\naction = 0\ntotal_score = 0\n\n# env = gym.make(\"CartPole-v0\")\nenv = gym.make(\"MountainCar-v0\")\n\nenv.mode = 'normal'\n\nenv.reset()\n\n\n\n\ndef Game_loop():\n while True:\n env.render()\n # time.sleep(0.05)\n observation, reward, done, info = env.step(action)\n global total_score\n total_score += reward\n # main.update()\n if done:\n # print(\"***** ***** ***** GAME OVER ***** ***** *****\")\n break\n\n\n\n\ndef leftKey(event):\n global action\n action = 0\n # print (\"Left key pressed\" , action)\n L_left.config(bg=\"red\", fg=\"white\")\n L_right.config(bg=\"white\", fg=\"black\")\n # time.sleep(.2) #configure slow motion\n \n\n\ndef rightKey(event):\n global action\n action = 1\n # print (\"Right key pressed\" , action)\n L_right.config(bg=\"red\", fg=\"white\")\n L_left.config(bg=\"white\", fg=\"black\")\n # time.sleep(.2)\n \n\ndef upKey(event):\n global action\n action = 2\n # print (\"Right key pressed\" , action)\n L_right.config(bg=\"white\", fg=\"black\")\n L_left.config(bg=\"white\", fg=\"black\")\n # time.sleep(.2)\n \n\ndef Space_pressed(event):\n messagebox.showinfo(\"Game Over\", (\"Your score \"+str(total_score)))\n global total_score\n total_score = 0\n env.reset()\n \n\n\n\n\nclass App(threading.Thread):\n\n def __init__(self, tk_root):\n self.root = tk_root\n threading.Thread.__init__(self)\n self.start()\n\n def run(self):\n loop_active = True\n while loop_active:\n Game_loop()\n \n\n\nmain = Tk()\nAPP = App(main)\n\nL_left = Label(text=\"Left\" ,font=(\"Courier\", 44),bg=\"white\", fg=\"black\")\nL_right = Label(text=\"Right\" ,font=(\"Courier\", 44),bg=\"white\", fg=\"black\")\n\nL_left.pack(side = LEFT, padx=20)\nL_right.pack(side = RIGHT, padx=20)\nframe = Frame(main, width=100, height=100)\nframe.bind('', leftKey)\nframe.bind('', rightKey)\nframe.bind('', upKey) #comment here in case of less controls needed\nframe.bind('', Space_pressed)\nframe.focus_set()\nframe.pack()\n\nmain.mainloop()\n","sub_path":"UserPlay.py","file_name":"UserPlay.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"263349704","text":"# 首先获得每篇新闻的标题,summary和链接\r\nimport json\r\nfrom urllib.request import Request, urlopen\r\nfrom tqdm import tqdm\r\nimport time\r\n\r\nurl_1 = 'https://mil.huanqiu.com/api/list2?node=/e3pmh1dm8/e3pmt7hva&offset='\r\nurl_2 = '&limit=20'\r\nchrome_headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36'}\r\nfh = open('D:\\文件夹汇总\\项目\\军事知识图谱\\爬虫\\环球军事网\\\\huanqiu_1\\\\news_scription.txt','a+',encoding='UTF-8')\r\nfor i in tqdm(range(227,500)):\r\n url = url_1 + str(20 * i) + url_2\r\n #print(url)\r\n request = Request(url,headers=chrome_headers)\r\n html = urlopen(request)\r\n # print(html)\r\n data = html.read().decode()\r\n # #print(data)\r\n # #print(strs)\r\n # # strs_for_json = strs[4:]\r\n # # strs_for_json = strs_for_json[:-2]\r\n # # #json_obj = demjson(strs_for_json)\r\n # # # print(strs_for_json)\r\n # # data = strs_for_json\r\n # json_data = json.dumps(data,ensure_ascii=False)\r\n # # data_json = json.loads(strs)\r\n # # print(data_json['datas'][0]['aid'])\r\n # #print(datas)\r\n # #print(type(datas))\r\n python_data = json.loads(data)\r\n for j in range(20):\r\n fh.write(python_data['list'][j]['title'])\r\n fh.write('\\n')\r\n fh.write('https://mil.huanqiu.com/article/' + python_data['list'][j]['aid'])\r\n fh.write('\\n')\r\n fh.write(python_data['list'][j]['summary'])\r\n fh.write('\\n')\r\n fh.write('\\n')\r\n print(i,j)\r\n time.sleep(1)\r\n time.sleep(5)\r\n\r\nfh.close()\r\n\r\n\r\n\r\n\r\n","sub_path":"Military_KG/get_LinkAdress.py","file_name":"get_LinkAdress.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"527672781","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os, sys, datetime\nimport pymysql\nfrom pymysqlreplication import BinLogStreamReader\nfrom pymysqlreplication.row_event import (\n WriteRowsEvent,\n UpdateRowsEvent,\n DeleteRowsEvent,\n)\nfrom pymysqlreplication.event import QueryEvent, RotateEvent, FormatDescriptionEvent\nfrom binlog2sql_util import command_line_args, concat_sql_from_binlogevent, create_unique_file, reversed_lines\n\nclass Binlog2sql(object):\n\n def __init__(self, connectionSettings, startFile=None, startPos=None, endFile=None, endPos=None, startTime=None,\n stopTime=None, only_schemas=None, only_tables=None, nopk=False, flashback=False, stopnever=False):\n '''\n connectionSettings: {'host': 127.0.0.1, 'port': 3306, 'user': slave, 'passwd': slave}\n '''\n if not startFile:\n raise ValueError('lack of parameter,startFile.')\n\n self.connectionSettings = connectionSettings\n self.startFile = startFile\n self.startPos = startPos if startPos else 4 # use binlog v4\n self.endFile = endFile if endFile else startFile\n self.endPos = endPos\n self.startTime = datetime.datetime.strptime(startTime, \"%Y-%m-%d %H:%M:%S\") if startTime else datetime.datetime.strptime('1970-01-01 00:00:00', \"%Y-%m-%d %H:%M:%S\")\n self.stopTime = datetime.datetime.strptime(stopTime, \"%Y-%m-%d %H:%M:%S\") if stopTime else datetime.datetime.strptime('2999-12-31 00:00:00', \"%Y-%m-%d %H:%M:%S\")\n\n self.only_schemas = only_schemas if only_schemas else None\n self.only_tables = only_tables if only_tables else None\n self.nopk, self.flashback, self.stopnever = (nopk, flashback, stopnever)\n\n self.binlogList = []\n self.connection = pymysql.connect(**self.connectionSettings)\n try:\n cur = self.connection.cursor()\n cur.execute(\"SHOW MASTER STATUS\")\n self.eofFile, self.eofPos = cur.fetchone()[:2]\n cur.execute(\"SHOW MASTER LOGS\")\n binIndex = [row[0] for row in cur.fetchall()]\n if self.startFile not in binIndex:\n raise ValueError('parameter error: startFile %s not in mysql server' % self.startFile)\n binlog2i = lambda x: x.split('.')[1]\n for bin in binIndex:\n if binlog2i(bin) >= binlog2i(self.startFile) and binlog2i(bin) <= binlog2i(self.endFile):\n self.binlogList.append(bin)\n\n cur.execute(\"SELECT @@server_id\")\n self.serverId = cur.fetchone()[0]\n if not self.serverId:\n raise ValueError('need set server_id in mysql server %s:%s' % (self.connectionSettings['host'], self.connectionSettings['port']))\n finally:\n\n\n cur.close()\n\n def process_binlog(self):\n stream = BinLogStreamReader(connection_settings=self.connectionSettings, server_id=self.serverId,\n log_file=self.startFile, log_pos=self.startPos, only_schemas=self.only_schemas,\n only_tables=self.only_tables, resume_stream=True)\n\n cur = self.connection.cursor()\n tmpFile = create_unique_file('%s.%s' % (self.connectionSettings['host'],self.connectionSettings['port'])) # to simplify code, we do not use file lock for tmpFile.\n ftmp = open(tmpFile ,\"w\")\n flagLastEvent = False\n eStartPos, lastPos = stream.log_pos, stream.log_pos\n try:\n for binlogevent in stream:\n if not self.stopnever:\n if (stream.log_file == self.endFile and stream.log_pos == self.endPos) or (stream.log_file == self.eofFile and stream.log_pos == self.eofPos):\n flagLastEvent = True\n elif datetime.datetime.fromtimestamp(binlogevent.timestamp) < self.startTime:\n if not (isinstance(binlogevent, RotateEvent) or isinstance(binlogevent, FormatDescriptionEvent)):\n lastPos = binlogevent.packet.log_pos\n continue\n elif (stream.log_file not in self.binlogList) or (self.endPos and stream.log_file == self.endFile and stream.log_pos > self.endPos) or (stream.log_file == self.eofFile and stream.log_pos > self.eofPos) or (datetime.datetime.fromtimestamp(binlogevent.timestamp) >= self.stopTime):\n break\n # else:\n # raise ValueError('unknown binlog file or position')\n\n if isinstance(binlogevent, QueryEvent) and binlogevent.query == 'BEGIN':\n eStartPos = lastPos\n\n if isinstance(binlogevent, QueryEvent):\n sql = concat_sql_from_binlogevent(cursor=cur, binlogevent=binlogevent, flashback=self.flashback, nopk=self.nopk)\n if sql:\n print (sql)\n elif isinstance(binlogevent, WriteRowsEvent) or isinstance(binlogevent, UpdateRowsEvent) or isinstance(binlogevent, DeleteRowsEvent):\n for row in binlogevent.rows:\n sql = concat_sql_from_binlogevent(cursor=cur, binlogevent=binlogevent, row=row , flashback=self.flashback, nopk=self.nopk, eStartPos=eStartPos)\n if self.flashback:\n ftmp.write(sql + '\\n')\n else:\n print (sql)\n\n if not (isinstance(binlogevent, RotateEvent) or isinstance(binlogevent, FormatDescriptionEvent)):\n lastPos = binlogevent.packet.log_pos\n if flagLastEvent:\n break\n ftmp.close()\n\n if self.flashback:\n self.print_rollback_sql(tmpFile)\n finally:\n os.remove(tmpFile)\n cur.close()\n stream.close()\n return True\n\n def print_rollback_sql(self, fin):\n '''print rollback sql from tmpfile'''\n with open(fin) as ftmp:\n sleepInterval = 1000\n i = 0\n for line in reversed_lines(ftmp):\n print (line.rstrip())\n if i >= sleepInterval:\n print ('SELECT SLEEP(1);')\n i = 0\n else:\n i += 1\n\n def __del__(self):\n pass\n\n\nif __name__ == '__main__':\n\n args_t = ['-h192.168.134.130','-uroot','-p123456','-P3307','--start-file=mysql-bin.000128','--stop-file=mysql-bin.000130','-dbinlog2sql','-B']\n args = command_line_args(args_t)\n # args = command_line_args(sys.argv[1:])\n\n connectionSettings = {'host':args.host, 'port':args.port, 'user':args.user, 'passwd':args.password,'charset':'utf8'}\n binlog2sql = Binlog2sql(connectionSettings=connectionSettings, startFile=args.startFile,\n startPos=args.startPos, endFile=args.endFile, endPos=args.endPos,\n startTime=args.startTime, stopTime=args.stopTime, only_schemas=args.databases,\n only_tables=args.tables, nopk=args.nopk, flashback=args.flashback, stopnever=args.stopnever)\n binlog2sql.process_binlog()\n","sub_path":"dbmanage/archer/binlog2sql/binlog2sql.py","file_name":"binlog2sql.py","file_ext":"py","file_size_in_byte":7140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"452091846","text":"# data = ['alex', 49, [1900, 3, 18]]\n# name = data[0]\n# age = data[1]\n# born_year = data[2][0]\n# born_month = data[2][1]\n# born_day = data[2][2]\n# print(name, age, born_year,born_month,born_day)\n\n\n# # 11.\t写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)\n# name = \" aleX\"\n# # 1)\t移除 name 变量对应的值两边的空格,并输出处理结果\n# print(name.strip())\n# # 2)\t判断 name 变量对应的值是否以 \"al\" 开头,并输出结果\n# print(name.startswith('al'))\n# # 3)\t判断 name 变量对应的值是否以 \"X\" 结尾,并输出结果\n# print(name.endswith('X'))\n# # 4)\t将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果\n# print(name.replace('l', 'p'))\n# # 5)\t将 name 变量对应的值根据 “l” 分割,并输出结果。\n# print(name.split('l'))\n# # 6)\t将 name 变量对应的值变大写,并输出结果\n# print(name.upper())\n# # 7)\t将 name 变量对应的值变小写,并输出结果\n# print(name.lower())\n# # 8)\t请输出 name 变量对应的值的第 2 个字符?\n# print(name[1])\n# # 9)\t请输出 name 变量对应的值的前 3 个字符?\n# print(name[:3])\n# # 10)\t请输出 name 变量对应的值的后 2 个字符?\n# print(name[-2:])\n# # 11)\t请输出 name 变量对应的值中 “e” 所在索引位置?\n# print(name.index('e'))\n# # 12)\t获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。\n# name_2 = name[:-1]\n# print(name_2)\n\n# print([i for i in range(100) if i % 2 == 1])\n\n# msg = '/etc/a.txt|365|get'\n# filename, file_size, operate_method = msg.split('/')[2].split('|')\n# print(filename, file_size, operate_method, sep='\\n')\n\n\n# 20.\t有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,\n# 将小于 66 的值保存至第二个key的值中。(2分)\n# 即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}\n\n# l = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]\n# dic = {'k1':[], 'k2':[]}\n# for i in l:\n# if i > 66:\n# dic['k1'].append(i)\n# elif i < 66:\n# dic['k2'].append(i)\n# print(dic)\n\n\n# 21.\t有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合\n# pythons = {'alex', 'egon', 'yuanhao', 'wupeiqi', 'cobila', 'biubiu'}\n# linuxs = {'wupeiqi', 'oldboy', 'cobila'}\n# # 求出即报名python又报名linux课程的学员名字集合(2分)\n# print(pythons.intersection(linuxs))\n# print(linuxs.intersection(pythons))\n#\n# # 求出所有报名的学生名字集合(2分)\n# print(pythons.union(linuxs))\n# print(linuxs.union(pythons))\n#\n# # 求出只报名python课程的学员名字(2分)\n# print(pythons.difference(linuxs))\n#\n# # 求出没有同时这两门课程的学员名字集合(2分)\n# print(pythons.symmetric_difference(linuxs))\n# print(linuxs.symmetric_difference(pythons))\n\n\n# 22.\t统计s = 'hello alex alex say hello sb sb'中每个单词的个数(3分)\n# 结果如下:\n# {'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}\n# s = 'hello alex alex say hello sb sb'\n# dic_22 = {}\n# for i in set(s.split(' ')):\n# dic_22.setdefault(i, s.count(i))\n# print(dic_22)\n# import collections\n\n\n# s = 'hello'\n# l = [1, 2, 3, 4]\n# t = (1, 2, 3)\n# d = {'a': 1}\n# s_set = {1, 2, 3}\n# f = open('a.txt')\n#\n#\n# def judge(obj):\n# if '__iter__' in dir(obj):\n# print(obj, '是可迭代对象')\n# else:\n# print(obj, '不是可迭代对象')\n# if '__next__' in dir(obj):\n# print(obj, '是迭代器')\n# else:\n# print(obj, '不是迭代器')\n#\n# judge(s)\n# judge(l)\n# judge(t)\n# judge(d)\n# judge(s_set)\n# judge(f)\n# s = 'hello'\n# l = [1, 2, 3, 4]\n# t = (1, 2, 3)\n# d = {'a': 1}\n# s_set = {1, 2, 3}\n# f = open('a.txt')\n#\n# s_set = {1, 2, 3}\n# # 集合无索引迭代方法\n# # 不依赖索引:\n# for val in s_set:\n# print(val)\n\n\n# apple 10 3\n# tesla 100000 1\n# mac 3000 2\n# lenovo 30000 3\n# chicken 10 3\n\n# goods = []\n# with open('a.txt', 'r', encoding='utf-8') as rf:\n# for line in rf:\n# temp_d = {}\n# item = (line.split(' '))\n# temp_d.setdefault('name', item[0])\n# temp_d.setdefault('price', int(item[1]))\n# temp_d.setdefault('count', int(item[2]))\n# goods.append(temp_d)\n# print(goods)\n#\n# total = 0\n# for i in goods:\n# total += i['price'] * i['count']\n# print(total)\n\n\n# d = {'num': 3, 'str': 2, 'space': 3, 'others': 3}\n# def count_str(string):\n# _dic = {'num': 0, 'str': 0, 'space': 0, 'others': 0}\n# for i in string:\n# if i.isdigit():\n# _dic['num'] += 1\n# elif i.isalpha():\n# _dic['str'] += 1\n# elif i.isspace():\n# _dic['space'] += 1\n# else:\n# _dic['others'] += 1\n# return _dic\n#\n# s = input('>>>')\n# print(count_str(s))\n\n\n# l = [2, 3, 5, 10, 15, 16, 18, 22, 26, 30, 32, 35, 41, 42, 43, 55, 56, 66, 67, 69, 72, 76, 82, 83, 88]\n#\n#\n# def search(obj, aim, left=0, right=None):\n# right = right if right else len(obj)-1\n# if left > right:\n# return\n# center = (left + right)//2\n# if obj[center] == aim:\n# return center\n# elif obj[center] > aim:\n# return search(obj, aim, left, center - 1)\n# else:\n# return search(obj, aim, center + 1, right)\n# # print(len(l))\n# print(search(l, 88))\n\n\n# 2.编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码(10分)\n# 注意:从文件中读出字符串形式的字典,可以用eval\n#\nFLAG = {\n 'status': False\n}\n\n\ndef auth(func):\n def inner(*args, **kwargs):\n if FLAG['status']:\n ret = func(*args, **kwargs)\n return ret\n else:\n if sign_in():\n FLAG['status'] = True\n ret = func(*args, **kwargs)\n return ret\n return inner\n\n\ndef read_data():\n data = []\n with open('users', 'r', encoding='utf-8') as rf:\n for line in rf:\n if line.startswith('\\n') > 0:\n continue\n else:\n data.append(eval(line))\n return data\n\n\ndef sign_in():\n while True:\n data = read_data()\n username = input('请输入用户名:').strip()\n for i in range(len(data)):\n if username == data[i]['name']:\n password = input('请输入密码:').strip()\n if password == data[i]['pwd']:\n print('登陆成功!')\n return True\n else:\n print('密码错误!')\n break\n else:\n print('用户名不存在!')\n\n\n@auth\ndef f1():\n print(111)\n\n\n@auth\ndef f2():\n print(222)\n\n\n@auth\ndef f3():\n print(333)\n\nf1()\nf2()\nf3()\n\n\n# def init(func):\n# def inner(*args, **kwargs):\n# gen = func(*args, **kwargs)\n# next(gen)\n# return gen\n# return inner\n#\n#\n# @init\n# def search(target):\n# while True:\n# path, word = yield\n# with open(path, 'rb') as rf:\n# for line in rf:\n# if line and word in line.decode('utf-8'):\n# target.send(line.decode('utf-8'))\n#\n#\n# @init\n# def printer():\n# while True:\n# line = yield\n# print(line, end='')\n#\n#\n# def index():\n# while True:\n# file_name = input('请输入文件名:').strip()\n# word = input('请输入关键词: ').strip()\n# g = search(printer())\n# g.send((file_name, word))\n#\n# index()\n#\n# t1 = (('a'), ('b'))\n# t2 = (('c'), ('d'))\n#\n# ll1 = list(map(lambda t: {t[0]:t[1]}, zip(t1, t2)))\n# # ll = [{i[0]:i[1]} for i in zip(t1, t2)]\n# print(ll1)\n\n# num = [1, 3, 5, 6, 7, 8]\n# num2 = list(filter(lambda x: x % 2 == 0, num))\n# print(num2)\n\n\n","sub_path":"Basis_of_Python/201704week/0804/Temp.py","file_name":"Temp.py","file_ext":"py","file_size_in_byte":7837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"529890368","text":"from django.urls import path\nfrom users import views\nfrom rest_framework.authtoken.views import obtain_auth_token # rest login\n\nurlpatterns = [\n path('login', obtain_auth_token, name='api_token_auth'),\n path('register', views.RegisterViewSet.register),\n path('confirm', views.RegisterViewSet.confirm),\n path('create', views.RegisterViewSet.createUser),\n path('info', views.UserViewSet.getUserInfo),\n # path('snippets//', views.snippet_detail),\n]","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"463348716","text":"# 原理是先将需要发送的文本放到剪贴板中,然后将剪贴板内容发送到qq窗口\n# 之后模拟按键发送enter键发送消息\n\nimport win32gui\nimport win32con\nimport win32clipboard as w\nimport datetime\nimport time\n\ndef doSth():\n print('test')\n # 假装做这件事情需要一分钟\n time.sleep(5)\ndef main(h=14, m=0):\n '''h表示设定的小时,m为设定的分钟'''\n while True:\n # 判断是否达到设定时间,例如0:00\n while True:\n now = datetime.datetime.now()\n # 到达设定时间,结束内循环\n if now.hour==h and now.minute==m:\n break\n # 不到时间就等20秒之后再次检测\n time.sleep(20)\n # 做正事,一天做一次\n doSth()\n\ndef getText():\n \"\"\"获取剪贴板文本\"\"\"\n w.OpenClipboard()\n d = w.GetClipboardData(win32con.CF_UNICODETEXT)\n w.CloseClipboard()\n return d\n\ndef setText(aString):\n \"\"\"设置剪贴板文本\"\"\"\n w.OpenClipboard()\n w.EmptyClipboard()\n w.SetClipboardData(win32con.CF_UNICODETEXT, aString)\n w.CloseClipboard()\n\ndef send_qq(to_who, msg):\n \"\"\"\n 发送qq消息\n to_who:qq消息接收人\n msg:需要发送的消息\n \"\"\"\n # 将消息写到剪贴板\n setText(msg)\n # 获取qq窗口句柄\n qq = win32gui.FindWindow(None, to_who)\n # 投递剪贴板消息到QQ窗体\n win32gui.SendMessage(qq, 258, 22, 2080193)\n win32gui.SendMessage(qq, 770, 0, 0)\n # 模拟按下回车键\n win32gui.SendMessage(qq, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)\n win32gui.SendMessage(qq, win32con.WM_KEYUP, win32con.VK_RETURN, 0)\n\nmain()\n# 测试\nto_who='吕锋'\nmsg='嘿嘿嘿'\nsend_qq(to_who, msg)\n","sub_path":"py/QQ定时发消息.py","file_name":"QQ定时发消息.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"608726047","text":"class Pagination(object):\n def __init__(self,totalCount,currentPage,perPageItemNum=20,maxPageNum=7):\n # totalCount 传入的数据总数 currentPage 当前页 perPageItemNum 每页显示数 maxPageNum 每页下面显示的最多标签/页码数\n self.total_count = totalCount\n # 数据总个数\n try:\n v = int(currentPage)\n if v <= 0:\n v=1\n # 防止输入的数字小于0 出错\n self.current_page = v\n # 当前页\n except Exception as e:\n self.current_page = 1\n self.per_page_item_num = perPageItemNum\n # 每页显示的行数\n self.max_page_num = maxPageNum\n # 每页下面显示的最多标签\n def start(self):\n # 返回当前页-1 乘以每页显示数的值\n return (self.current_page-1) * self.per_page_item_num\n\n def end(self):\n # 返回当前页 乘以每页显示数的值, start-end这两个函数正好可以切分当前页面显示的范围\n return self.current_page * self.per_page_item_num\n\n\n @property # 加上这个的意思是调用num_pages正常是这样self.num_pages(),加了这个之后self.num_pages可以不用加括号\n def num_pages(self):\n # 计算总页数,用总数量除以每页数\n a,b = divmod(self.total_count,self.per_page_item_num) # 计算两个数的除法返回结果和余数\n if b == 0:\n return a\n return a+1\n\n def pager_num_range(self):\n # 当前页 self.current_page\n # 最多显示页码数11 self.per_pager_num\n # 总页数 self.num_pages\n if self.num_pages < self.max_page_num:\n # 总页数小于最多显示的页码数时,显示1-页码数+1的标签\n return range(1,self.num_pages+1)\n #总页数特别多\n part = int(self.max_page_num/2)\n if self.current_page <= part:\n # 当前页小于显示页码数的一半时,显示1-页码数+1的标签\n return range(1,self.max_page_num+1)\n if (self.current_page + part) > self.num_pages:\n # 如果当前页+页码数一半大于总页数了,就返回总页数-最多页码数到总页数+1的范围了\n return range(self.num_pages-self.max_page_num,self.num_pages+1)\n return range(self.current_page-part,self.current_page+part+1)\n # 否则的话 就显示 当前页-最多显示页码的一半 到 当前页加最多显示页码的一半+1\n def page_str(self):\n # 返回标签的函数\n page_list = []\n type = ''\n page_list.append(type)\n return ''.join(page_list)","sub_path":"pagingAndFrom/pagingDemo/pager.py","file_name":"pager.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270924778","text":"\nimport os\n# accessible as a variable in index.html in template\nfrom sqlalchemy import *\nfrom sqlalchemy.pool import NullPool\nfrom flask import Flask, request, render_template, g, redirect, Response\n\ntmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')\napp = Flask(__name__, template_folder=tmpl_dir)\n\n\nDATABASEURI = \"postgresql://postgres:Cleanslate25@35.243.220.243/proj1part2\"\n\n\nengine = create_engine(DATABASEURI)\n\n\n\n@app.before_request\ndef before_request():\n\n try:\n g.conn = engine.connect()\n except:\n print(\"uh oh, problem connecting to database\")\n import traceback;\n traceback.print_exc()\n g.conn = None\n\n\n@app.teardown_request\ndef teardown_request(exception):\n\n try:\n g.conn.close()\n except Exception as e:\n pass\n\n\n@app.route('/')\ndef index():\n print(request.args)\n\n #\n # example of a database query\n #\n # cursor = g.conn.execute(\"SELECT name FROM test\")\n # names = []\n # for result in cursor:\n # names.append(result['name']) # can also be accessed using result[0]\n # cursor.close()\n #\n # context = dict(data=names)\n\n return render_template(\"index.html\" )#**context)\n\n\n@app.route('/another')\ndef another():\n return render_template(\"another.html\")\n\n\n@app.route('/add', methods=['POST'])\ndef add():\n name = request.form['name']\n g.conn.execute('INSERT INTO test(name) VALUES (%s)', name)\n return redirect('/')\n\n\n@app.route('/login')\ndef login():\n #abort(401)\n #this_is_never_executed()\n return 0\n\nif __name__ == \"__main__\":\n import click\n\n\n @click.command()\n @click.option('--debug', is_flag=True)\n @click.option('--threaded', is_flag=True)\n @click.argument('HOST', default='0.0.0.0')\n @click.argument('PORT', default=8111, type=int)\n def run(debug, threaded, host, port):\n\n\n HOST, PORT = host, port\n print(\"running on %s:%d\" % (HOST, PORT))\n app.run(host=HOST, port=PORT, debug=debug, threaded=threaded)\n\n run()\n\n\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"472833451","text":"import cv2 \r\nimport numpy\r\nimport glob #This module is used to find files matching a certain pattern\r\n\r\n\r\ndef render(imageDir): #Path is an argument given from the function call in app.py. This is the path of folder which contains the detected images.\r\n image_array=[]\r\n\r\n for file in glob.glob(imageDir+'/'+'*.jpg'):\r\n image=cv2.imread(file)\r\n # print(file)\r\n\r\n # image.shape returns the dimesions of the image i.e, its height width as well as how many channels(r,g,b,and more) are in the image\r\n height, width , channels = image.shape\r\n size=(450,450) #This size will be given later as an argument to the VideoWriter class\r\n resizeimage=cv2.resize(image,size,interpolation=cv2.INTER_AREA)\r\n \r\n image_array.append(resizeimage) #Saving the image in an array \r\n\r\n\r\n out = cv2.VideoWriter('video.avi',cv2.VideoWriter_fourcc('M','J','P','G'),0.5,size)\r\n print(\"Rendering \"+str(len(image_array))+\" images\")\r\n # cv2.imshow('',image_array[5])\r\n # cv2.waitKey(0)\r\n for i in range(len(image_array)):\r\n out.write(image_array[i])\r\n\r\n out.release()\r\n print(\"Video rendered successfully\")\r\n \r\n","sub_path":"videorender.py","file_name":"videorender.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"639919617","text":"import torch\nimport parsing\nfrom parsing.config import cfg\nfrom parsing.utils.comm import to_device\nfrom parsing.dataset import build_test_dataset\nfrom parsing.detector import WireframeDetector\nfrom parsing.utils.logger import setup_logger\nfrom parsing.utils.metric_logger import MetricLogger\nfrom parsing.utils.miscellaneous import save_config\nfrom parsing.utils.checkpoint import DetectronCheckpointer\nimport os\nimport os.path as osp\nimport time\nimport datetime\nimport argparse\nimport logging\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport json\nparser = argparse.ArgumentParser(description='HAWP Testing')\n\nparser.add_argument(\"--config-file\",\n metavar=\"FILE\",\n help=\"path to config file\",\n type=str,\n required=True,\n )\n\nparser.add_argument(\"--display\",\n default=False,\n action='store_true')\nparser.add_argument(\"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER\n )\nargs = parser.parse_args()\n\ndef test(cfg):\n logger = logging.getLogger(\"hawp.testing\")\n device = cfg.MODEL.DEVICE\n model = WireframeDetector(cfg)\n model = model.to(device)\n\n test_datasets = build_test_dataset(cfg)\n \n output_dir = cfg.OUTPUT_DIR\n\n checkpointer = DetectronCheckpointer(cfg,\n model,\n save_dir=cfg.OUTPUT_DIR,\n save_to_disk=True,\n logger=logger)\n _ = checkpointer.load()\n model = model.eval()\n for name, dataset in test_datasets:\n results = []\n logger.info('Testing on {} dataset'.format(name))\n\n for i, (images, annotations) in enumerate(tqdm(dataset)):\n with torch.no_grad():\n output, extra_info = model(images.to(device), annotations)\n output = to_device(output,'cpu')\n \n if args.display:\n im = dataset.dataset.image(i)\n plt.imshow(im)\n lines = output['lines_pred'].numpy()\n scores = output['lines_score'].numpy()\n plt.plot([lines[scores>0.97,0],lines[scores>0.97,2]],\n [lines[scores>0.97,1],lines[scores>0.97,3]], 'r-')\n plt.show()\n\n for k in output.keys():\n if isinstance(output[k], torch.Tensor):\n output[k] = output[k].tolist()\n results.append(output)\n outpath_dataset = osp.join(output_dir,'{}.json'.format(name))\n logger.info('Writing the results of the {} dataset into {}'.format(name,\n outpath_dataset))\n with open(outpath_dataset,'w') as _out:\n json.dump(results,_out)\n break\n\nif __name__ == \"__main__\":\n\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n \n output_dir = cfg.OUTPUT_DIR\n logger = setup_logger('hawp', output_dir)\n logger.info(args)\n logger.info(\"Loaded configuration file {}\".format(args.config_file))\n\n\n test(cfg)\n\n ### Training\n\n\n\n # import pdb; pdb.set_trace()\n\n\n","sub_path":"CULane/scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"345321170","text":"import unittest\nfrom selenium import webdriver\nfrom time import sleep\nfrom ddt import ddt, data, file_data, unpack\n@ddt\nclass TestBaidu(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.driver = webdriver.Chrome()\n cls.base_url = \"https://www.baidu.com\"\n\n def baidu_search(self, search_key):\n self.driver.get(self.base_url)\n self.driver.find_element_by_id(\"kw\").send_keys(search_key)\n self.driver.find_element_by_id(\"su\").click()\n sleep(3)\n @file_data(\"aa.json\")\n def test_search4(self, search_key):\n print(\"第四组测试用例:\", search_key)\n self.baidu_search(search_key)\n self.assertEqual(self.driver.title, search_key + \"_百度搜索\")\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\nif __name__ == '__main__':\n unittest.main(verbosity=2)","sub_path":"unittest/test_web/test_baidu_ddt_json.py","file_name":"test_baidu_ddt_json.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"25767892","text":"#Bij Ziggy\n# Countdown functie werkt standalone wel, maar niet in deze voorbeeld\nimport pygame\nimport time\n\npygame.init()\n\n(width, height) = (800, 600)\n\nblack = ( 0, 0, 0)\nwhite = ( 255, 255, 255)\n\nscreen = pygame.display.set_mode((width, height))\n\nfont = pygame.font.Font(\"freesansbold.ttf\", 30)\n\nseconds = 10\n\ndef countdown(second, txt):\n while second != 0:\n print(second)\n second -= 1\n pygame.time.delay(1000)\n\n if(second == 0):\n return True\n\ndef game_intro():\n intro = True\n\n while intro:\n for event in pygame.event.get():\n print(event)\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n screen.fill(white)\n\n txt = font.render(\"Time {}\".format(seconds),\n 1, black)\n screen.blit(txt, (16, 16))\n\n countdown(seconds, txt)\n\n pygame.display.update()\n\ngame_intro()","sub_path":"countdowntest.py","file_name":"countdowntest.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410955609","text":"import os, sys, math, string\nimport json\n\nimport maya.cmds as mc\nimport maya.OpenMaya as mo\n\nimport masset\nreload(masset)\nimport mbridge\nreload(mbridge)\nimport PillarsUtils\n\ndef setBridge():\n '''\n You can edit the userSetup.py the set auto bridge, Add the flow lines to userSetup.py.\n \n import maya.cmds as mc\n mc.commandPort(n = \"localhost:18810\", stp = \"python\")\n \n '''\n mc.commandPort(n = \"localhost:18810\", stp = \"python\")\n\ndef goto():\n work_path = PillarsUtils.getWorkingPath()\n mbridge.setWorkspace(work_path)\n \ndef createCurrentAsset():\n asset = PillarsUtils.loadGotoAsset()\n mbridge.createAsset(asset.name, asset.type)\n \ndef createCameraAsset():\n shot = PillarsUtils.loadGotoAsset()\n if shot.group == \"shot\":\n mbridge.createAsset(\"%s_camera\" % shot.name, \"camera\")\n \ndef publishCurrentAsset():\n asset = PillarsUtils.loadGotoAsset()\n task = PillarsUtils.loadGotoTask()\n mbridge.assetPublish(asset.location, asset.name, task.name, task.version)\n mc.confirmDialog(title='OK', message='Publish %s successful.' % asset.name)\n \n\n","sub_path":"cgPipeline/old/PillarsAssetTool1/Maya/mpipeline.py","file_name":"mpipeline.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"325930033","text":"import numpy as np\r\nimport math\r\nimport sys\r\n\r\n\r\ndef gradient_filter(img):\r\n\r\n # Finding both vertical and horizontal gradients using sobel operator\r\n # Summing them up to achieve energy map (gradient magnitude)\r\n\r\n gradient = np.zeros(img.shape,dtype = np.int32)\r\n max_x, max_y = img.shape\r\n\r\n for y in range(1, max_y - 1):\r\n for x in range(1, max_x - 1):\r\n dx_pos = 4 * img[x, y] - 2 * img[x - 1, y] - img[x - 1, y + 1] - img[x - 1, y - 1]\r\n dx_neg = 4 * img[x, y] - 2 * img[x + 1, y] - img[x + 1, y + 1] - img[x + 1, y - 1]\r\n dx = dx_pos - dx_neg\r\n\r\n dy_pos = 4 * img[x, y] - 2 * img[x, y - 1] - img[x + 1, y - 1] - img[x - 1, y - 1]\r\n dy_neg = 4 * img[x, y] - 2 * img[x, y + 1] - img[x + 1, y + 1] - img[x - 1, y + 1]\r\n dy = dy_pos - dy_neg\r\n\r\n gradient[x, y] = math.fabs(dx) + math.fabs(dy)\r\n\r\n return gradient\r\n\r\n\r\ndef find_vertical_seam(energy_img):\r\n\r\n inv_seam, min_seam_value = find_horizontal_seam(energy_img.T)\r\n seam_pixels = []\r\n for rev_pix in inv_seam:\r\n seam_pixels.append((rev_pix[1],rev_pix[0]))\r\n\r\n # print min_seam_value\r\n return seam_pixels,min_seam_value\r\n\r\n\r\ndef find_horizontal_seam(energy_img):\r\n optimal_cost_dp, path_table = get_DPtable_PathTable(energy_img)\r\n\r\n final_column = list(optimal_cost_dp[:,energy_img.shape[1]-1])\r\n # print optimal_cost_dp\r\n # print path_table\r\n min_seam_value, min_seam_index = get_min_minIndex(final_column)\r\n # print final_column\r\n # print min_seam_index,min_seam_value\r\n seam_pixels = construct_path_horizontal(path_table,min_seam_index)\r\n # print seam_pixels\r\n return seam_pixels, min_seam_value\r\n\r\ndef get_DPtable_PathTable(energy_img):\r\n optimal_cost_dp = np.zeros(energy_img.shape)\r\n path_table = np.zeros(energy_img.shape)\r\n\r\n for i in range(energy_img.shape[1]):\r\n for j in range(energy_img.shape[0]):\r\n if i == 0:\r\n optimal_cost_dp[j][i] = energy_img[j][i]\r\n continue\r\n\r\n if j == 0:\r\n min_value, min_index = get_min_minIndex((optimal_cost_dp[j][i - 1], optimal_cost_dp[j + 1][i - 1]))\r\n optimal_cost_dp[j][i] = energy_img[j][i] + min_value\r\n path_table[j][i] = 1 + min_index\r\n continue\r\n if j == energy_img.shape[0] - 1:\r\n min_value, min_index = get_min_minIndex((optimal_cost_dp[j - 1][i - 1], optimal_cost_dp[j][i - 1]))\r\n optimal_cost_dp[j][i] = energy_img[j][i] + min_value\r\n path_table[j][i] = min_index\r\n continue\r\n\r\n min_value, min_index = \\\r\n get_min_minIndex(\r\n (optimal_cost_dp[j - 1][i - 1], optimal_cost_dp[j][i - 1], optimal_cost_dp[j + 1][i - 1]))\r\n\r\n optimal_cost_dp[j][i] = energy_img[j][i] + min_value\r\n path_table[j][i] = min_index\r\n\r\n return optimal_cost_dp,path_table\r\n\r\n\r\n\r\ndef get_min_minIndex(lis):\r\n\r\n length = len(lis)\r\n if length == 3:\r\n if lis[0]==lis[1] and lis[0] bad_pixel_index:\r\n out_image[j - 1][i] = image[j][i]\r\n\r\n else:\r\n for i in range(height):\r\n bad_pixel_index = seam_pixels[i][1]\r\n for j in range(length):\r\n if j < bad_pixel_index:\r\n out_image[i][j] = image[i][j]\r\n if j > bad_pixel_index:\r\n out_image[i][j-1] = image[i][j]\r\n\r\n return out_image\r\n\r\ndef get_optimal_order_image(energy_img,final_img,req_len,req_height):\r\n img_height, img_length = energy_img.shape\r\n\r\n r = img_height - req_height\r\n c = img_length - req_len\r\n\r\n e_img = np.copy(energy_img)\r\n f_image = np.copy(final_img)\r\n\r\n t_dp = [[0 for x in range(img_length+1)] for y in range(img_height+1)]\r\n\r\n # path_table = np.zeros((r+1,c+1))\r\n # path_table[0][0] = -1\r\n t_dp[0][0] = (0,e_img,f_image)\r\n\r\n for i in range(1,r+1):\r\n seam, min_seam_value = find_horizontal_seam(e_img)\r\n e_img = delete_seam(e_img,seam,isHorizontal=True)\r\n f_image = delete_seam(f_image,seam,isHorizontal=True)\r\n\r\n t_dp[i][0] = (t_dp[i-1][0][0] + min_seam_value,e_img,f_image)\r\n # path_table[i][0] = 1\r\n\r\n e_img = np.copy(energy_img)\r\n f_image = np.copy(final_img)\r\n\r\n for i in range(1,c+1):\r\n seam, min_seam_value = find_vertical_seam(e_img)\r\n e_img = delete_seam(e_img,seam,isHorizontal=False)\r\n f_image = delete_seam(f_image,seam,isHorizontal=False)\r\n t_dp[0][i] = (t_dp[0][i-1][0] + min_seam_value,e_img,f_image)\r\n # path_table[0][i] = 0\r\n count = 0\r\n for i in range(1,r+1):\r\n for j in range(1,c+1):\r\n count = count + 1\r\n print (count),\r\n seamHor, min_seam_valueHor = find_horizontal_seam(t_dp[i-1][j][1])\r\n hor_value = min_seam_valueHor + t_dp[i-1][j][0]\r\n count = count + 1\r\n print (count),\r\n seamVer, min_seam_valueVer = find_vertical_seam(t_dp[i][j-1][1])\r\n ver_value = min_seam_valueVer + t_dp[i][j-1][0]\r\n if hor_value < ver_value:\r\n t_dp[i][j] = (hor_value,delete_seam(t_dp[i-1][j][1],seamHor,isHorizontal=True),delete_seam(t_dp[i-1][j][2],seamHor,isHorizontal=True))\r\n # path_table[i][j] = 1\r\n else:\r\n t_dp[i][j] = (ver_value,delete_seam(t_dp[i][j-1][1],seamVer,isHorizontal=False),delete_seam(t_dp[i][j-1][2],seamVer,isHorizontal=False))\r\n # path_table[i][j] = 0\r\n\r\n return t_dp[r][c][2]\r\n\r\n\r\ndef showMin_X_Seams(f_image,e_image,number_of_seams, isHorizontal = True):\r\n\r\n if not isHorizontal:\r\n e_image = e_image.T\r\n f_image = np.rollaxis(f_image,1,0)\r\n out_image = np.copy(f_image)\r\n out_e_image = np.copy(e_image)\r\n\r\n seam_dp_table, path_table = get_DPtable_PathTable(e_image)\r\n final_column = list(seam_dp_table[:, e_image.shape[1] - 1])\r\n for i in range(len(final_column)):\r\n final_column[i] = (final_column[i], i)\r\n final_column.sort(key=lambda x: x[0])\r\n final_column = final_column[:number_of_seams]\r\n\r\n for k in range(number_of_seams):\r\n seam_path = construct_path_horizontal(path_table, final_column[k][1])\r\n for pixel in seam_path:\r\n out_image[pixel[0]][pixel[1]] = np.array([0,0,255])\r\n out_e_image[pixel[0]][pixel[1]] = 255\r\n\r\n if not isHorizontal:\r\n out_image = np.rollaxis(out_image,1,0)\r\n out_e_image = out_e_image.T\r\n e_image = e_image.T\r\n f_image = np.rollaxis(f_image,1,0)\r\n\r\n return out_image, out_e_image\r\n\r\n\r\n\r\ndef insert_seams_horizontal(f_image,e_image,number_of_seams):\r\n\r\n # print f_image.shape,e_image.shape\r\n\r\n height, length = e_image.shape\r\n out_image_prev = np.zeros((f_image.shape[0]+number_of_seams,f_image.shape[1],3),dtype=np.uint8)\r\n out_energy_image_prev = np.zeros((e_image.shape[0] + number_of_seams, e_image.shape[1]),dtype=np.uint8)\r\n\r\n out_image_prev[:f_image.shape[0],:,:] = np.copy(f_image)\r\n out_energy_image_prev[:e_image.shape[0],:] = np.copy(e_image)\r\n\r\n out_image_next = np.copy(out_image_prev)\r\n out_energy_image_next = np.copy(out_energy_image_prev)\r\n\r\n\r\n seam_dp_table, path_table = get_DPtable_PathTable(e_image)\r\n final_column = list(seam_dp_table[:, e_image.shape[1] - 1])\r\n for i in range(len(final_column)):\r\n final_column[i] = (final_column[i],i)\r\n final_column.sort(key = lambda x : x[0])\r\n final_column = final_column[:number_of_seams]\r\n final_column.sort(key = lambda x : x[1],reverse=True)\r\n # print final_column\r\n count = 0\r\n for k in range(number_of_seams):\r\n count = count + 1\r\n print(count),\r\n seam_path = construct_path_horizontal(path_table,final_column[k][1])\r\n # print seam_path\r\n for i in range(length):\r\n add_index = seam_path[i][0]\r\n # print add_index,\r\n for j in range(height-1+k,-1,-1):\r\n if j > add_index:\r\n out_image_next[j+1][i] = out_image_prev[j][i]\r\n out_energy_image_next[j+1][i] = out_energy_image_prev[j][i]\r\n # print j,i\r\n # print out_energy_image[j][i]\r\n # print out_image[j][i]\r\n\r\n if j == add_index:\r\n\r\n if j==height-1+k:\r\n out_image_next[j+1][i] = out_image_prev[j][i]\r\n out_energy_image_next[j+1][i] = out_energy_image_prev[j][i]\r\n else:\r\n out_image_next[j + 1][i] = (out_image_prev[j][i])/2 + (out_image_prev[j + 1][i]) / 2\r\n out_energy_image_next[j + 1][i] = (out_energy_image_prev[j][i])/2 + (out_energy_image_prev[j + 1][i]) / 2\r\n\r\n\r\n if j <= add_index:\r\n out_image_next[j][i] = out_image_prev[j][i]\r\n out_energy_image_next[j][i] = out_energy_image_prev[j][i]\r\n\r\n # break\r\n\r\n out_image_prev = np.copy(out_image_next)\r\n out_energy_image_prev = np.copy(out_energy_image_next)\r\n # print out_energy_image_next\r\n\r\n return out_image_next,out_energy_image_next\r\n\r\n\r\ndef insert_seams_vertical(f_image,e_image,number_of_seams):\r\n f_image = np.rollaxis(f_image,1,0)\r\n e_image_T = e_image.T\r\n output_f_image_T, output_e_imagee_T = insert_seams_horizontal(f_image, e_image_T, number_of_seams)\r\n output_f_image_T = np.rollaxis(output_f_image_T,1,0)\r\n return output_f_image_T, output_e_imagee_T.T","sub_path":"seamCarve.py","file_name":"seamCarve.py","file_ext":"py","file_size_in_byte":11370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"621776430","text":"# Load the wordnet corpus\nfrom __future__ import division\nfrom nltk.corpus import wordnet as wn\nimport string\nimport array\n\n\n#opens document\nf = open('./textFiles/newTopWords.txt', 'r')\nclusters = 100\n\n#first step creates a list of the top words and prints them to a file\ntopWords = []\ncount = 0\nlistOfNum = []\nfor line in f:\n currentLine = line\n words = string.split(currentLine)\n firstWord = words[0]\n\n topWords.append(firstWord)\n\n if count < 100:\n listOfNum.append(count + 1)\n count = count + 1\n\nf.close\n\nc = open('./textFiles/merge.txt', 'w')\n\nc.write('')\nc.close()\n\nc = open('./textFiles/merge.txt', 'a')\n\nfor index in listOfNum:\n\n number = listOfNum[index-1]\n\n f = open('./textFiles/finalClusters/Cluster' + str(number) + '.txt')\n\n #we don't need first line\n f.readline()\n\n for line in f:\n c.write(line)\n\nc.close()\n\n\n\n \n","sub_path":"ClusterCode/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"62194794","text":"\"\"\"\n-------------------------------------------------------------------------------\nDESCRIPTION\n Purpose : Automatize correction of trades, instruments\n Department and Desk : TCU\n Requester : Martin Herbst, James Stevens, Floyd Malatji, Natasha Williams, Jennitha Jugnath\n Developer : Marian Zdrazil, Tibor Reiss\n\nHISTORY\n===============================================================================\nDate CR / JIRA # Developer Description\n-------------------------------------------------------------------------------\n2019-05-23 CHG1001777219 Marian Zdrazil Initial implementation.\n2019-06-06 FAPE-68 Marian Zdrazil Adding voiding trade, instr. termination + update of leg's end date\n2020-01-09 CHG0073639 Libor Svoboda Update sec loan regenerate logic.\n2020-06-06 CHG0103218 Libor Svoboda Update price/quantity amendment logic.\n\"\"\"\nimport csv\nfrom math import copysign\n\nimport acm\nimport FRunScriptGUI\nfrom at_ael_variables import AelVariableHandler\nfrom at_logging import getLogger\n\n\nLOGGER = getLogger()\nDATE_TODAY = acm.Time().DateToday()\nCALC_SPACE = acm.Calculations().CreateStandardCalculationsSpaceCollection()\n\nFILE_SELECTION = FRunScriptGUI.InputFileSelection(FileFilter=\"CSV Files (*.csv)|*.csv\")\n\n\nael_variables = AelVariableHandler()\nael_variables.add(\n name='amendments_file',\n label='File with amendments to apply',\n cls=FILE_SELECTION,\n default='/services/frontnt/Task',\n mandatory=True,\n multiple=True,\n alt=\"Input CSV file with various amendments on each row\"\n)\n\n\ndef read_corrections_file(csv_file_name):\n \"\"\"\n Input CSV file with amendments has the following format:\n There are 4 columns in the input comma separated/delimited file:\n -------------------------------------------------------------------------------------------------------------------------\n 1st column: trade number (integer)\n 2nd column: amendment value (quantity, price, rate, Open End, Terminate, Void, (end date in MM/DD/YYYY format), etc.)\n 3rd column: field description (Price, Quantity, SL_VAT, Open End, Rate, Terminate, Void)\n 4th column: object (Instrument, Trade, Open End, Instrument AdditionalInfo, Trade AdditionalInfo)\n -------------------------------------------------------------------------------------------------------------------------\n Ex:\n ===\n Price, quantity amendment, VAT field un-ticking, re-opening, rate change\n 108984438,1.58,Price,Instrument\n 95032378,200000,Quantity,Trade\n 108725637,TRUE,SL_VAT,Instrument AdditionalInfo\n 98499295,Open End,Open End,Instrument\n 107767545,0.3,Rate,Trade AdditionalInfo\n 97627257,Terminate,Terminate,Instrument\n 97627257,06/06/2019,Terminate,Instrument\n 110031992,Void,Void,Trade\n\n \"\"\"\n try:\n with open(csv_file_name, 'rb') as corr_file:\n corr_reader = csv.reader(corr_file, delimiter=',')\n corrections = [(int(row[0]), row[1], row[2], row[3])\n for row in corr_reader if len(row) > 1]\n LOGGER.info(\"Corrections from %s file\" % csv_file_name)\n return corrections\n except IOError as io_exception:\n LOGGER.error(\"Missing file with corrections: %s\", csv_file_name)\n raise io_exception\n\n\ndef update_attribute(acm_object, attribute, new_value, obj_desc):\n try:\n if 'AdditionalInfo' in obj_desc:\n old_value = getattr(acm_object.AdditionalInfo(), attribute)()\n object_clone = acm_object.Clone()\n setattr(object_clone.AdditionalInfo(), attribute, new_value)\n else:\n old_value = getattr(acm_object, attribute)()\n object_clone = acm_object.Clone()\n setattr(object_clone, attribute, new_value)\n acm_object.Apply(object_clone)\n acm_object.Commit()\n except Exception as err:\n acm_object.Undo()\n LOGGER.error(\"Changes for object %s of type %s cannot be committed to FA: %s\"\n % (acm_object.Oid(), acm_object.ClassName(), str(err)))\n else:\n LOGGER.info(\"Update successful for object %s on attribute %s: %s --> %s\"\n % (acm_object.Oid(), attribute, old_value, new_value))\n\n\ndef update_loan_value(acm_trade, attribute, new_value):\n ins = acm_trade.Instrument()\n underlying = ins.Underlying()\n quotation_factor = ins.Quotation().QuotationFactor()\n contract_size = ins.ContractSize()\n loan_quantity = acm_trade.FaceValue()\n loan_price = acm_trade.AllInPrice() * quotation_factor\n old_value = ''\n if attribute == 'Price':\n old_value = loan_price\n loan_price = new_value\n elif attribute == 'Quantity':\n old_value = abs(loan_quantity)\n loan_quantity = copysign(new_value, loan_quantity)\n \n trade_image = acm_trade.StorageImage()\n ins_image = ins.StorageImage()\n trade_quantity = loan_price * loan_quantity / contract_size\n ref_val = contract_size / loan_price\n ref_price = loan_price / quotation_factor\n if underlying.InsType() in ('Bond', 'IndexLinkedBond'):\n ref_price = underlying.Calculation().PriceConvert(\n CALC_SPACE, ref_price, 'Pct of Nominal', underlying.Quotation(), \n ins.StartDate())\n trade_image.Quantity(trade_quantity)\n ins_image.RefValue(ref_val)\n ins_image.RefPrice(ref_price)\n acm.BeginTransaction()\n try:\n ins_image.Commit()\n trade_image.Commit()\n acm.CommitTransaction()\n except:\n acm.AbortTransaction()\n LOGGER.exception(\"Failed to update %s for trade %s.\" % (attribute, acm_trade.Oid()))\n else:\n LOGGER.info(\"Update successful for trade %s on attribute %s: %s --> %s\"\n % (acm_trade.Oid(), attribute, old_value, new_value))\n\n\ndef reopen(instr):\n \"\"\" \n FAPE-68: Reopen terminated instruments - reopennning and extending terminated SBL instruments\n when instrument manually reopened by TCU, CFs are not necessarily being regenerated.\n \"\"\"\n if instr.InsType() == 'SecurityLoan':\n leg = instr.Legs()[0]\n old_value_oe = getattr(instr, \"OpenEnd\")()\n new_value_oe = \"Open End\"\n old_value_leg = getattr(leg, \"EndDate\")()\n new_value_leg = acm.Time.DateAddDelta(getattr(leg, \"StartDate\")(), 0, 0, 1)\n old_value_roll_period_base = getattr(leg, \"RollingPeriodBase\")()\n new_value_roll_period_base = getattr(instr, \"StartDate\")()\n\n if old_value_oe != \"Open End\":\n try:\n instr_clone = instr.Clone()\n setattr(instr_clone, \"OpenEnd\", new_value_oe)\n instr.Apply(instr_clone)\n instr.Commit()\n except Exception as err:\n instr.Undo()\n LOGGER.error(\"Reopening failed for instrument %s with the following exception: %s\" % (instr.Name(), err))\n else:\n LOGGER.info(\"Update successful for instrument %s - Open Ending: %s --> %s \" % (\n instr.Name(), old_value_oe, new_value_oe))\n\n if old_value_leg <= DATE_TODAY:\n try:\n leg_clone = leg.Clone()\n setattr(leg_clone, \"EndDate\", new_value_leg)\n setattr(leg_clone, \"RollingPeriodBase\", new_value_roll_period_base)\n leg.Apply(leg_clone)\n leg.Commit()\n except Exception as err:\n leg.Undo()\n LOGGER.error(\"Extending failed for instrument %s with the following exception: %s\" % (instr.Name(), err))\n else:\n LOGGER.info(\"Update successful for leg %s of instrument %s - Extending: Leg start date %s --> %s and \"\n \"Rolling Period Base %s --> %s\" % (leg.Oid(), instr.Name(), old_value_leg, new_value_leg,\n old_value_roll_period_base, new_value_roll_period_base))\n instr.SLExtendOpenEnd()\n instr.SLGenerateCashflows()\n else:\n LOGGER.error(\"Trade on instrument {} is not on a security loan\".format(instr.Name()))\n\n\ndef terminate(instr, end_date):\n \"\"\" \n FAPE-68: Terminate instruments + update leg's end date field\n \"\"\"\n if instr.InsType() == 'SecurityLoan':\n leg = instr.Legs()[0]\n old_value_oe = getattr(instr, \"OpenEnd\")()\n new_value_oe = \"Terminated\"\n old_value_leg = getattr(leg, \"StartDate\")()\n\n if old_value_oe != \"Terminated\":\n try:\n instr_clone = instr.Clone()\n setattr(instr_clone, \"OpenEnd\", new_value_oe)\n instr.Apply(instr_clone)\n instr.Commit()\n except Exception as err:\n instr.Undo()\n LOGGER.error(\"Termination failed for instrument %s with the following exception: %s\" % (instr.Name(), err))\n else:\n LOGGER.info(\"Update successful for instrument %s - Terminating: %s --> %s \" % (\n instr.Name(), old_value_oe, new_value_oe))\n \n if end_date != 'Terminate':\n try:\n leg_clone = leg.Clone()\n setattr(leg_clone, \"EndDate\", end_date)\n leg.Apply(leg_clone)\n leg.Commit()\n except Exception as err:\n leg.Undo()\n LOGGER.error(\"End date update failed for instrument %s with the following exception: %s\" % (instr.Name(), err))\n else:\n LOGGER.info(\"Update successful for leg %s of instrument %s - Leg end date: %s --> %s\" % \n (leg.Oid(), instr.Name(), old_value_leg, end_date))\n\n else:\n LOGGER.error(\"Trade on instrument {} is not on a security loan\".format(instr.Name()))\n\n\ndef implement_updates(corrections):\n for (trdnbr, corr_value, att_desc, obj_desc) in corrections:\n trade = acm.FTrade[trdnbr]\n if trade is not None:\n if trade.ArchiveStatus() == 0:\n if trade.Aggregate() == 0:\n ins = trade.Instrument()\n if att_desc in ('Price', 'Quantity'):\n update_loan_value(trade, att_desc, float(corr_value))\n elif obj_desc == 'Instrument' and att_desc == 'Open End':\n \"\"\" Open Ending & Extending Instrument \"\"\"\n reopen(ins)\n elif obj_desc == 'Instrument' and att_desc == 'Terminate':\n \"\"\" Terminating Instrument \"\"\"\n terminate(ins, corr_value)\n elif obj_desc == 'Trade' and att_desc == 'Void':\n \"\"\" Voiding Instrument \"\"\"\n update_attribute(trade, \"Status\", corr_value, obj_desc) \n elif obj_desc == 'Instrument AdditionalInfo' and att_desc == 'SL_VAT':\n \"\"\" Tick/Untick SL VAT instrument additional info field \"\"\"\n if 'TRUE' in corr_value:\n update_attribute(ins, \"SL_VAT\", True, obj_desc)\n elif 'FALSE' in corr_value:\n update_attribute(ins, \"SL_VAT\", False, obj_desc)\n elif obj_desc == 'Trade AdditionalInfo' and att_desc == 'Rate':\n \"\"\" Amend instrument rates \"\"\"\n update_attribute(trade, \"SL_G1Fee2\", float(corr_value), obj_desc)\n update_attribute(ins.Legs()[0], \"FixedRate\", float(corr_value), \"Leg\")\n else:\n LOGGER.error(\"Attribute flag not recognized - please check the 3rd column in the CSV file\")\n else:\n LOGGER.error(\"Cannot execute request on Aggregate Trade {}\".format(trdnbr))\n else:\n LOGGER.error(\"Cannot execute request on Archived Trade {}\".format(trdnbr))\n else:\n LOGGER.error(\"Trade {} does not exist\".format(trdnbr))\n\n\ndef ael_main(ael_dict):\n LOGGER.msg_tracker.reset()\n corrections = read_corrections_file(str(ael_dict['amendments_file']))\n implement_updates(corrections)\n if LOGGER.msg_tracker.errors_counter:\n raise RuntimeError(\"ERRORS occurred. Please check the log.\")\n LOGGER.info('Completed successfully.')\n","sub_path":"Python modules/TCU_amendment_task.py","file_name":"TCU_amendment_task.py","file_ext":"py","file_size_in_byte":12479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"449149037","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2021.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"Class to test the calibrations setup methods.\"\"\"\n\nimport qiskit.pulse as pulse\nfrom qiskit.test import QiskitTestCase\n\nfrom qiskit_experiments.calibration_management.basis_gate_library import FixedFrequencyTransmon\nfrom qiskit_experiments.exceptions import CalibrationError\n\n\nclass TestFixedFrequencyTransmon(QiskitTestCase):\n \"\"\"Test the various setup methods.\"\"\"\n\n def test_standard_single_qubit_gates(self):\n \"\"\"Test the setup of single-qubit gates.\"\"\"\n\n library = FixedFrequencyTransmon(default_values={\"duration\": 320})\n\n for gate in [\"x\", \"sx\"]:\n sched = library[gate]\n self.assertTrue(isinstance(sched, pulse.ScheduleBlock))\n self.assertEqual(len(sched.parameters), 5)\n\n sched_x = library[\"x\"]\n sched_y = library[\"y\"]\n sched_sx = library[\"sx\"]\n sched_sy = library[\"sy\"]\n\n self.assertEqual(sched_x.blocks[0].pulse.duration, sched_sx.blocks[0].pulse.duration)\n self.assertEqual(sched_x.blocks[0].pulse.sigma, sched_sx.blocks[0].pulse.sigma)\n\n self.assertEqual(len(sched_x.parameters & sched_y.parameters), 4)\n self.assertEqual(len(sched_sx.parameters & sched_sy.parameters), 4)\n\n expected = [\n (0.5, \"amp\", (), \"x\"),\n (0.0, \"β\", (), \"x\"),\n (320, \"duration\", (), \"x\"),\n (80, \"σ\", (), \"x\"),\n (320, \"duration\", (), \"sx\"),\n (0.0, \"β\", (), \"sx\"),\n (0.25, \"amp\", (), \"sx\"),\n (80, \"σ\", (), \"sx\"),\n ]\n\n for param_conf in library.default_values():\n self.assertTrue(param_conf in expected)\n\n # Check that an error gets raise if the gate is not in the library.\n with self.assertRaises(CalibrationError):\n print(library[\"bswap\"])\n\n # Test the basis gates of the library.\n self.assertListEqual(library.basis_gates, [\"x\", \"y\", \"sx\", \"sy\"])\n\n def test_turn_off_drag(self):\n \"\"\"Test the use_drag parameter.\"\"\"\n\n library = FixedFrequencyTransmon(use_drag=False)\n self.assertTrue(isinstance(library[\"x\"].blocks[0].pulse, pulse.Gaussian))\n\n library = FixedFrequencyTransmon()\n self.assertTrue(isinstance(library[\"x\"].blocks[0].pulse, pulse.Drag))\n\n def test_unlinked_parameters(self):\n \"\"\"Test the we get schedules with unlinked parameters.\"\"\"\n\n library = FixedFrequencyTransmon(link_parameters=False)\n\n sched_x = library[\"x\"]\n sched_y = library[\"y\"]\n sched_sx = library[\"sx\"]\n sched_sy = library[\"sy\"]\n\n # Test the number of parameters.\n self.assertEqual(len(sched_x.parameters & sched_y.parameters), 2)\n self.assertEqual(len(sched_sx.parameters & sched_sy.parameters), 2)\n\n expected = [\n (0.5, \"amp\", (), \"x\"),\n (0.0, \"β\", (), \"x\"),\n (160, \"duration\", (), \"x\"),\n (40, \"σ\", (), \"x\"),\n (160, \"duration\", (), \"sx\"),\n (0.0, \"β\", (), \"sx\"),\n (0.25, \"amp\", (), \"sx\"),\n (40, \"σ\", (), \"sx\"),\n (0.5j, \"amp\", (), \"y\"),\n (0.0, \"β\", (), \"y\"),\n (160, \"duration\", (), \"y\"),\n (40, \"σ\", (), \"y\"),\n (160, \"duration\", (), \"sy\"),\n (0.0, \"β\", (), \"sy\"),\n (0.25j, \"amp\", (), \"sy\"),\n (40, \"σ\", (), \"sy\"),\n ]\n\n self.assertSetEqual(set(library.default_values()), set(expected))\n\n def test_setup_partial_gates(self):\n \"\"\"Check that we do not setup all gates if not required.\"\"\"\n\n library = FixedFrequencyTransmon(basis_gates=[\"x\", \"sy\"])\n\n self.assertTrue(\"x\" in library)\n self.assertTrue(\"sy\" in library)\n self.assertTrue(\"y\" not in library)\n self.assertTrue(\"sx\" not in library)\n\n with self.assertRaises(CalibrationError):\n FixedFrequencyTransmon(basis_gates=[\"x\", \"bswap\"])\n","sub_path":"test/calibration/test_setup_library.py","file_name":"test_setup_library.py","file_ext":"py","file_size_in_byte":4372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"333850198","text":"from unittest import TestCase, main\nfrom main import escape, File, Bug, Landscape, BugFinder, DATA_FOLDER_PATH\n\n\nclass Test(TestCase):\n def test_escape(self):\n self.assertEqual(escape('north korea'), r'north\\ korea')\n self.assertEqual(escape('north korea', except_chars=' '), r'north korea')\n\n\nclass TestFile(TestCase):\n def setUp(self):\n self.valid_filename = 'bug.txt'\n self.invalid_filenames = ['wrongFormat.doc', 123, -123, True, None, {}, []]\n self.non_existing_valid_filename = 'doesNotExist.txt'\n\n def test_File(self):\n self.assertEqual(File(self.valid_filename).filename, self.valid_filename)\n\n for filename in self.invalid_filenames:\n self.assertRaises(TypeError, lambda: File(filename))\n\n def test_file_path(self):\n f = File(self.non_existing_valid_filename)\n self.assertRaises(ValueError, lambda: f.file_path)\n\n f = File(self.valid_filename)\n self.assertEqual(f.file_path, '{folder}/{file}'.format(folder=DATA_FOLDER_PATH, file=self.valid_filename))\n\n def test_reader(self):\n f = File(self.valid_filename)\n\n with open(f.file_path, 'r') as file_handler:\n line_count = 0\n for line in File.reader(file_handler):\n self.assertIsInstance(line, File.Line)\n\n line_count += 1\n\n self.assertEqual(line_count, 3)\n\n\nclass TestLine(TestCase):\n def setUp(self):\n self.valid_line_prop = {'id': 1, 'pattern': '---'}\n self.invalid_line_props = [\n {'id': -123, 'pattern': -123},\n {'id': True, 'pattern': True},\n {'id': None, 'pattern': None},\n {'id': {}, 'pattern': {}},\n {'id': [], 'pattern': []},\n ]\n\n def test_Line(self):\n for line_prop in self.invalid_line_props:\n self.assertRaises(TypeError, lambda: File.Line(line_prop['id'], line_prop['pattern']))\n\n def test_id(self):\n line = File.Line(self.valid_line_prop['id'], self.valid_line_prop['pattern'])\n self.assertEqual(line.id, self.valid_line_prop['id'])\n\n def test_pattern(self):\n line = File.Line(self.valid_line_prop['id'], self.valid_line_prop['pattern'])\n self.assertEqual(line.pattern, self.valid_line_prop['pattern'])\n\n\nclass TestBug(TestCase):\n def setUp(self):\n self.valid_filename = 'bug.txt'\n self.invalid_filenames = ['wrongFormat.doc', 123, -123, True, None, {}, []]\n self.non_existing_valid_filename = 'doesNotExist.txt'\n\n def test_Bug(self):\n self.assertEqual(Bug(self.valid_filename).filename, self.valid_filename)\n\n for filename in self.invalid_filenames:\n self.assertRaises(TypeError, lambda: File(filename))\n\n def test__read_bug(self):\n bug = Bug(self.valid_filename)\n\n part_count = 0\n for part in bug.shape:\n self.assertIsInstance(part, Bug.Part)\n\n part_count += 1\n\n self.assertEqual(part_count, 3)\n\n\nclass TestPart(TestCase):\n def setUp(self):\n self.valid_filename = 'bug.txt'\n\n def test__format_bug(self):\n self.assertEqual(Bug.Part._format_pattern('data'), 'd(?=ata)')\n self.assertEqual(Bug.Part._format_pattern('da ta'), 'd(?=a.{1}ta)')\n self.assertEqual(Bug.Part._format_pattern('da ta'), 'd(?=a.{2}ta)')\n self.assertEqual(Bug.Part._format_pattern('da t a'), 'd(?=a.{1}t.{1}a)')\n self.assertEqual(Bug.Part._format_pattern('da.t.a'), 'd(?=a\\.t\\.a)')\n\n self.assertRaises(TypeError, lambda: Bug.Part._format_pattern(123))\n self.assertRaises(TypeError, lambda: Bug.Part._format_pattern(True))\n self.assertRaises(TypeError, lambda: Bug.Part._format_pattern(None))\n self.assertRaises(TypeError, lambda: Bug.Part._format_pattern({}))\n self.assertRaises(TypeError, lambda: Bug.Part._format_pattern([]))\n\n def test__format_bug_replace_match_with_regex(self):\n bug = Bug(self.valid_filename)\n\n self.assertEqual(bug.shape[0].pattern, '\\|(?=.{1}\\|)')\n self.assertEqual(bug.shape[1].pattern, '\\#(?=\\#\\#O)')\n\n\nclass TestLandscape(TestCase):\n def setUp(self):\n self.valid_filename = 'bug.txt'\n self.invalid_filenames = ['wrongFormat.doc', 123, -123, True, None, {}, []]\n\n def test_Landscape(self):\n self.assertEqual(Bug(self.valid_filename).filename, self.valid_filename)\n\n for filename in self.invalid_filenames:\n self.assertRaises(TypeError, lambda: File(filename))\n\n\nclass TestBugFinder(TestCase):\n def setUp(self):\n self.bug = Bug('bug.txt')\n self.landscape = Landscape('landscape.txt')\n\n def test_bug_and_landscape(self):\n bug_finder = BugFinder(self.bug, self.landscape)\n\n self.assertIsInstance(bug_finder.bug, Bug)\n self.assertIsInstance(bug_finder.landscape, Landscape)\n\n self.assertRaises(TypeError, lambda: BugFinder(123, None))\n\n def test_increment_bug_count(self):\n bug_finder = BugFinder(self.bug, self.landscape)\n bug_count = bug_finder.bug_count\n\n bug_finder.increment_bug_count()\n self.assertEqual(bug_finder.bug_count, bug_count + 1)\n\n def test_find_bugs_in_landscape(self):\n bug_finder = BugFinder(self.bug, self.landscape)\n bug_finder.find_bugs_in_landscape()\n\n self.assertEqual(bug_finder.bug_count, 3)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":5396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"328750489","text":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\nimport struct\n\nfrom .common import *\n\n\ndef read_record_head(record_id):\n record_path = os.path.join(cfg.data_path, 'replay', 'ssh', '{:06d}'.format(int(record_id)))\n header_file_path = os.path.join(record_path, 'tp-ssh.tpr')\n file = None\n try:\n file = open(header_file_path, 'rb')\n data = file.read()\n offset = 0\n\n magic, = struct.unpack_from('I', data, offset) # magic must be 1381126228, 'TPRR'\n offset += 4\n time_start, = struct.unpack_from('Q', data, offset)\n offset += 8\n pkg_count, = struct.unpack_from('I', data, offset)\n offset += 4\n time_used, = struct.unpack_from('I', data, offset)\n offset += 4\n width, = struct.unpack_from('H', data, offset)\n offset += 2\n height, = struct.unpack_from('H', data, offset)\n offset += 2\n file_count, = struct.unpack_from('H', data, offset)\n offset += 2\n total_size, = struct.unpack_from('I', data, offset)\n offset += 4\n\n account, = struct.unpack_from('16s', data, offset)\n account = account.decode()\n offset += 16\n user_name, = struct.unpack_from('16s', data, offset)\n user_name = user_name.decode()\n offset += 16\n\n except Exception as e:\n return None\n finally:\n if file is not None:\n file.close()\n\n header = dict()\n header['file_count'] = file_count\n header['time_used'] = time_used\n header['width'] = width\n header['height'] = height\n return header\n\n\n# def read_record_term(record_id):\n# record_path = os.path.join(cfg.data_path, 'replay', 'ssh', '{}'.format(record_id))\n# term_file_path = os.path.join(record_path, 'term.init')\n# # term_file_path = r\"E:\\GitWork\\teleport\\share\\data\\replay\\ssh\\103\\term.init\"\n#\n# file = None\n# try:\n# file = open(term_file_path, 'rb')\n# data = file.read()\n# x = len(data)\n# offset = 0\n# # data = data.decode()\n# ID, = struct.unpack_from('16s', data, offset)\n# ID = ID.decode()\n# offset += 16\n#\n# Version, = struct.unpack_from('16s', data, offset)\n# Version = Version.decode()\n# offset += 16\n#\n# t_count, = struct.unpack_from('I', data, offset)\n# offset += 4\n# term_list = list()\n# for i in range(t_count):\n# # _term, = struct.unpack_from('16s', data, offset)\n# # _term = _term.decode()\n# # offset += 16\n# _time, = struct.unpack_from('I', data, offset)\n# offset += 4\n#\n# x, = struct.unpack_from('I', data, offset)\n# offset += 4\n#\n# y, = struct.unpack_from('I', data, offset)\n# offset += 4\n#\n# # px, = struct.unpack_from('I', data, offset)\n# # offset += 4\n# #\n# # py, = struct.unpack_from('I', data, offset)\n# # offset += 4\n# #\n# # _time, = struct.unpack_from('I', data, offset)\n# # offset += 4\n# temp = dict()\n# # temp['term'] = _term\n# temp['t'] = _time\n# temp['w'] = x\n# temp['h'] = y\n# # temp['px'] = px\n# # temp['py'] = py\n#\n# term_list.append(temp)\n#\n# except Exception as e:\n# return None\n# finally:\n# if file is not None:\n# file.close()\n#\n# header = dict()\n# header['id'] = ID\n# header['ver'] = Version\n# header['count'] = t_count\n# header['term_list'] = term_list\n# return header\n\n\ndef read_record_info(record_id, file_id):\n record_path = os.path.join(cfg.data_path, 'replay', 'ssh', '{:06d}'.format(int(record_id)))\n file_info = os.path.join(record_path, 'tp-ssh.{:03d}'.format(int(file_id)))\n file = None\n try:\n file = open(file_info, 'rb')\n data = file.read()\n total_size = len(data)\n\n offset = 0\n data_size, = struct.unpack_from('I', data, offset)\n offset += 4\n\n data_list = list()\n while True:\n action, = struct.unpack_from('B', data, offset)\n offset += 1\n\n _size, = struct.unpack_from('I', data, offset)\n offset += 4\n\n _time, = struct.unpack_from('I', data, offset)\n offset += 4\n\n # skip reserved 3 bytes.\n offset += 3\n\n _format = '{}s'.format(_size)\n _data, = struct.unpack_from(_format, data, offset)\n offset += _size\n\n temp = dict()\n temp['a'] = action\n temp['t'] = _time\n if action == 1:\n # this is window size changed.\n w, h = struct.unpack_from('HH', _data)\n temp['w'] = w\n temp['h'] = h\n elif action == 2:\n _data = _data.decode()\n # this is ssh data.\n temp['d'] = _data\n else:\n return None\n\n data_list.append(temp)\n if offset == total_size:\n break\n\n except Exception as e:\n return None\n finally:\n if file is not None:\n file.close()\n return data_list\n\n\ndef delete_log(log_list):\n try:\n sql_exec = get_db_con()\n for item in log_list:\n log_id = int(item)\n str_sql = 'DELETE FROM ts_log WHERE id={}'.format(log_id)\n ret = sql_exec.ExecProcNonQuery(str_sql)\n if not ret:\n return False\n # 删除录像文件\n try:\n record_path = os.path.join(cfg.data_path, 'replay', 'ssh', '{:06d}'.format(log_id))\n if os.path.exists(record_path):\n shutil.rmtree(record_path)\n record_path = os.path.join(cfg.data_path, 'replay', 'rdp', '{:06d}'.format(log_id))\n if os.path.exists(record_path):\n shutil.rmtree(record_path)\n except Exception:\n pass\n\n return True\n except:\n return False\n","sub_path":"server/www/teleport/app/eom_app/module/record.py","file_name":"record.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"101544304","text":"from game import Game\nimport threading\nimport os\nimport neat\n\n\n\ndef eval_genomes(genomes, config):\n\n\n for genome_id, genome in genomes:\n winnerSize = 0\n genome.fitness = 0\n #instantiation of the neat neural network\n net = neat.nn.FeedForwardNetwork.create(genome, config)\n #thread creation for the play of the game\n x = threading.Thread(target=game.start(net, genome))\n x.start()\n #if statment to keep track of biggest snake through iterations\n if(game.size>winnerSize):\n winnerSize = game.size\n print(\"Fitness: \", genome.fitness)\n x.join()\n print(\"Longest snake length: \", winnerSize)\n\ndef run(config_file):\n # Load configuration.\n config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,neat.DefaultSpeciesSet, neat.DefaultStagnation,config_file)\n # Create the population, which is the top-level object for a NEAT run.\n p = neat.Population(config)\n\n # Add a stdout reporter to show progress in the terminal.\n p.add_reporter(neat.StdOutReporter(True))\n stats = neat.StatisticsReporter()\n p.add_reporter(stats)\n\n\n # Run for up to 40 generations.\n winner = p.run(eval_genomes, 40)\n\nif __name__ == '__main__':\n #main()\n # Determine path to configuration file. This path manipulation is\n # here so that the script will run successfully regardless of the\n # current working directory.\n local_dir = os.path.dirname(__file__)\n config_path = os.path.join(local_dir, 'neat_config.txt')\n #new game\n game = Game()\n run(config_path)\n","sub_path":"snakeNEAT/neatAgent.py","file_name":"neatAgent.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"296938366","text":"from oslo_config import cfg\nimport oslo_messaging as om\n\nimport config\nfrom common import exceptions\nfrom migrate import app\nimport models\nfrom models import db\n\n\n# Invoke \"get_transport\". This call will set default Configurations required\n# to Create Messaging Transport\ntransport = om.get_transport(cfg.CONF)\n\n# Set/Override Configurations required to Create Messaging Transport\ncfg.CONF.set_override('transport_url', config.transport_url)\n\n# Create Messaging Transport\ntransport = om.get_transport(cfg.CONF)\n\n# Create Target (Exchange, Topic and Server to listen on)\ntarget = om.Target(topic='testme', server=config.rpc_server)\n\n\ndef to_dict(func):\n def decorator(*args, **kwargs):\n res = func(*args, **kwargs)\n if isinstance(res, list):\n return [item.to_dict() for item in res]\n\n if res:\n return res.to_dict()\n else:\n return None\n\n return decorator\n\n\n# Create EndPoint\nclass TestEndpoint(object):\n\n def mldata_create(self, ctxt=None, uuid=None, url=None, ml_lib=None,\n is_form_cluster=None, storage_name=None,\n storage_type=None):\n with app.app_context():\n new_mldata = models.MLData(uuid, url, ml_lib, is_form_cluster,\n storage_name, storage_type)\n\n db.session.add(new_mldata)\n db.session.commit()\n\n def resource_create(self, ctxt=None, uuid=None, resource_type=None,\n provider=None, endpoint=None,\n username=None, password=None, token=None,\n availability_zone=None, region=None):\n with app.app_context():\n new_res = models.Resource(uuid, resource_type, provider, endpoint,\n username, password, token,\n availability_zone, region)\n\n db.session.add(new_res)\n db.session.commit()\n\n def node_create(self, ctxt=None, uuid=None, resource_id=None,\n node_ip=None, username=None, password=None):\n with app.app_context():\n new_node = models.Node(uuid, resource_id, node_ip, username,\n password)\n\n db.session.add(new_node)\n db.session.commit()\n\n @to_dict\n def resource_detail(self, ctxt=None, id=None):\n with app.app_context():\n result = (models.Resource.query.filter(models.Resource.uuid == id)\n .outerjoin(models.Node)\n .one_or_none()\n )\n\n if result is None:\n raise exceptions.ResourceNotFound(uid=id)\n\n return result\n\n @to_dict\n def get_all_resources(self, ctxt=None):\n with app.app_context():\n result = models.Resource.query.all()\n return result\n\n def resource_delete(self, ctxt=None, id=None):\n with app.app_context():\n resource = models.Resource.query.get(id)\n if resource is None:\n return exceptions.ResourceNotFound(uid=id)\n db.session.delete(resource)\n db.session.commit()\n\n @to_dict\n def get_all_mldata(self, ctxt=None):\n with app.app_context():\n result = models.MLData.query.all()\n return result\n\n @to_dict\n def mldata_detail(self, ctxt=None, id=None):\n with app.app_context():\n result = models.MLData.query.get(id)\n\n if result is None:\n raise exceptions.MLDataNotFound(uid=id)\n\n return result\n\n def mldata_delete(self, ctxt=None, id=None):\n with app.app_context():\n data = models.MLData.query.get(id)\n if data is None:\n raise exceptions.MLDataNotFound(uid=id)\n\n db.session.delete(data)\n db.session.commit()\n\n @to_dict\n def get_all_nodes(self, ctxt=None):\n with app.app_context():\n result = models.Node.query.all()\n return result\n\n @to_dict\n def node_detail(self, ctxt=None, id=None):\n with app.app_context():\n result = models.Node.query.get(id)\n\n if result is None:\n raise exceptions.NodeNotFound(uid=id)\n\n return result\n\n def node_delete(self, ctxt=None, id=None):\n with app.app_context():\n node = models.Node.query.get(id)\n\n if node is None:\n raise exceptions.NodeNotFound(uid=id)\n\n db.session.delete(node)\n db.session.commit()\n\n\n# Create EndPoint List\nendpoints = [TestEndpoint(), ]\n\n# Create RPC Server\nserver = om.get_rpc_server(transport, target, endpoints)\n\n# Start RPC Server\nserver.start()\n","sub_path":"db/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"599208086","text":"\"\"\"\nhttps://leetcode.com/problems/move-zeroes/\nGiven an array nums, write a function to move all 0's to the end of it\nwhile maintaining the relative order of the non-zero elements.\n\"\"\"\n\ndef main():\n #nums = [0,1,0,3,12] #[1,3,12,0,0]\n #nums = [0,0,0,0]\n #nums = []\n #nums = [0,0,1]\n #nums = [1,0,0,3]\n nums = [1,0,0,0,3,0,1]\n\n print(move_zeroes_while(nums[:]))\n print(move_zeroes_swap(nums[:]))\n\n\n# Modify nums: when found 0, delete current item and append it to the end of nums\n# Iteration is O(n). Pop is O(n-i), append is O(1). Total is O(n^2)\ndef move_zeroes_while(nums):\n # Check if nums is not empty\n if len(nums) == 0:\n return nums\n\n # Check if nums contains 0 or consists of only zeroes\n if (0 not in nums) or (len(set(nums)) == 1):\n return nums\n\n # Iterate over list, find zeroes, remove them and append to nums.\n index = 0\n max_index= len(nums)\n while index < max_index:\n if nums[index] == 0:\n nums.pop(index)\n nums.append(0)\n max_index -= 1\n else:\n index += 1\n\n return nums\n\n# Modify nums: if found non-zero value, swap it with the item at possible_zero_pos\n# Iteration is O(n), accessing the values is O(1). Total is O(n)\ndef move_zeroes_swap(nums):\n # Check if nums is not empty\n if len(nums) == 0:\n return nums\n\n # Check if nums contains 0 or only consists of zeroes\n if (0 not in nums) or (len(set(nums)) == 1):\n return nums\n\n # If found non-zero, swap items at index and possible_zero_pos and advance the former\n possible_zero_pos = 0\n for index in range(len(nums)):\n if nums[index] != 0:\n nums[possible_zero_pos], nums[index] = nums[index], nums[possible_zero_pos]\n possible_zero_pos += 1\n\n return nums\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"283_move_zeroes.py","file_name":"283_move_zeroes.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"377622916","text":"from flask import Flask,render_template,request\nfrom geopy import Nominatim\nfrom sqlite3 import *\nimport pandas as pd\nfrom geopy.distance import geodesic\nimport reverse_geocoder as rg\nimport pprint\nimport collections\nimport requests, json\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email import encoders\n\napp = Flask(__name__)\napi_key = 'AIzaSyCL0wx3UnODrwb51u4XxQFhmNNd20jhq1o'\nurl = \"https://maps.googleapis.com/maps/api/place/textsearch/json?\"\ndef reverseGeocode(coordinates):\n result = rg.search(coordinates)\n return result\n@app.route('/')\ndef home():\n return render_template('home.html')\n@app.route('/reportFire',methods=['GET','POST'])\ndef report():\n print('Done1')\n if(request.method=='POST'):\n print('Done')\n loc=request.form['location']\n print(loc)\n cause=request.form['cause']\n print(cause)\n intensity=int(request.form['intensity'])\n print(intensity)\n try:\n firest=[]\n phoneno=[]\n geolocator=Nominatim(timeout=5)\n print('Done2')\n location=geolocator.geocode(loc)\n p=location.longitude\n q=location.latitude\n\n coordinates =(q, p)\n z=reverseGeocode(coordinates)\n z=list(z[0].items())\n location=z[2][1]\n query = str(location)+' hospital'\n print(query)\n r = requests.get(url + 'query=' + query +'&key=' + api_key)\n print(\"Amazing\")\n x = r.json()\n y = x['results']\n l2=[]\n for i in range(len(y)):\n print(y[i]['name'])\n l2.append(y[i]['name'])\n print(\"Done3\")\n conn2=connect('firefighters.db')\n print(\"DOne4\")\n conn2.execute(\"INSERT INTO reportfire(latitude,longitude,location,intensity,cause) VALUES(?,?,?,?,?)\",(q,p,loc,intensity,cause) )\n print(\"Done5\")\n conn2.commit()\n print(\"Report Datbase Connected successfully!\")\n conn2.close()\n print(\"Done Inserting!\")\n\n\n conn=connect('firestation.db')\n p1=conn.execute('Select * from Firesta')\n q1=p1.fetchall()\n print(q1)\n for i in q1:\n s=geodesic((i[1],i[2]), (p,q)).km\n if(s<6):\n print(i[0])\n if(str(i[3])!=None):\n print('done')\n firest.append(str(i[0])+' : '+str(i[3]))\n print('done')\n phoneno.append(str(i[3]))\n print('done')\n conn.close()\n\n print('There')\n return render_template('n2.html',l1=firest,l2=l2)\n except:\n return render_template('reportfire.html')\n return render_template('reportfire.html')\n\n@app.route('/safeguard')\ndef safeguard():\n return render_template('safeguard.html')\n@app.route('/checkforfire',methods=['GET','POST'])\ndef firecheck():\n if(request.method=='POST'):\n loc=request.form['location']\n print(loc)\n try:\n fireloc=[]\n geolocator=Nominatim(timeout=15)\n print('Done1')\n location=geolocator.geocode(loc)\n p=location.longitude\n q=location.latitude\n print('Done2')\n conn=connect('firefighters.db')\n p1=conn.execute('Select * from adminfire where current_status=\"Ablaze\"')\n print(\"Done3\")\n q1=p1.fetchall()\n print(\"done4\")\n for i in q1:\n s1=geodesic((p,q),(i[6],i[3])).km\n print(i)\n if(s1<5):\n fireloc.append(str(i[1]))\n print(\"done6\")\n conn.close()\n print(\"done7\")\n print(fireloc)\n return render_template('fireschecked.html',val1=fireloc)\n except:\n return render_template('checkforfire.html')\n return render_template('checkforfire.html')\n@app.route('/dashboardadmin')\ndef dashboardadmin():\n con=connect('firefighters.db')\n con.row_factory = Row\n cur = con.cursor()\n cur.execute(\"select * from adminfire\")\n rows = cur.fetchall();\n\n\n return render_template('dashboardadmin.html',rows = rows)\n@app.route('/ablaze')\ndef ablaze():\n con=connect('firefighters.db')\n con.row_factory = Row\n cur = con.cursor()\n cur.execute(\"select * from adminfire\")\n rows = cur.fetchall();\n return render_template('n3.html',rows=rows)\n@app.route('/dashboard')\ndef dashboard():\n return render_template('dashboard.html')\n@app.route('/login')\ndef login():\n return render_template('login.html')\n@app.route('/notifications',methods=['GET','POST'])\ndef notifications():\n if request.method == \"POST\":\n email=request.form['email']\n phone_number=request.form['phone_number']\n url = \"https://www.fast2sms.com/dev/bulk\"\n msg='Fire has been detected near your vicinity!'\n payload = \"sender_id=FSTSMS&message={}&language=english&route=p&numbers={}\".format(msg,phone_number)\n headers = {\n 'authorization': \"mGtxiRuLCkVlXjW4eJw3KDSrvynh8YFIqZgPa7TQ1UA6Hf92BMYaSJKyh1UbDTOs8C9Azncr5pEL0jXV\",\n 'Content-Type': \"application/x-www-form-urlencoded\",\n 'Cache-Control': \"no-cache\",\n }\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n\n fromaddr = \"nihar.kalsekar@yahoo.com\"\n toaddr = str(email)\n msg = MIMEMultipart()\n msg['From'] = fromaddr\n msg['To'] = toaddr\n msg['Subject'] = \"Fire Notification\"\n\n body = \"A fire has been alarmed at location ABC!Please send relief!\"\n msg.attach(MIMEText(body, 'plain'))\n s = smtplib.SMTP('smtp.mail.yahoo.com', 465)\n s.starttls()\n s.login(fromaddr, \"shubhangi\")\n text = msg.as_string()\n s.sendmail(fromaddr, toaddr, text)\n s.quit()\n return render_template('notifications.html')\n return render_template('notifications.html')\n@app.route('/predictFireFighters',methods=['GET','POST'])\ndef predictff():\n if(request.method=='POST'):\n intensity=int(request.form['intensity'])\n cause=int(request.form['cause'])\n if(cause==1):\n xm=[1,0,0,0,0,0,intensity]\n elif(cause==2):\n xm=[0,1,0,0,0,0,intensity]\n elif(cause==3):\n xm=[0,0,1,0,0,0,intensity]\n elif(cause==4):\n xm=[0,0,0,1,0,0,intensity]\n elif(cause==5):\n xm=[0,0,0,0,1,0,intensity]\n elif(cause==6):\n xm=[0,0,0,0,0,1,intensity]\n df=pd.read_csv('fire.csv')\n x11=df.iloc[1:,3:10].values\n y11=df.iloc[1:,2].values\n z11=df.iloc[1:,10].values\n #np.ravel(y)\n from sklearn.linear_model import LogisticRegression\n #from sklearn.model_selection import train_test_split\n #_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 1/3, random_state = 0)\n lin=LogisticRegression()\n lin.fit(x11,y11)\n ans=lin.predict([xm])\n lin.fit(x11,z11)\n ans2=lin.predict([xm])\n return render_template('predict.html',val2=ans[0],val1=\"The Estimated No. of Fire Fighters Required are: \",val3=ans2[0],val4='The estimated No. of Fire Brigades Required are: ')\n\n return render_template('predict.html')\n@app.route('/updatedb',methods=['GET','POST'])\ndef updatedb():\n if(request.method==\"POST\"):\n #try:\n loc=request.form['location']\n print(loc)\n cas=int(request.form['casualties'])\n print(cas)\n conn=connect('firefighters.db')\n print('done')\n conn.execute('UPDATE adminfire SET casualities=? where current_status=\"Ablaze\" and location=?',(cas,loc,))\n conn.commit()\n conn.execute('UPDATE adminfire SET current_status=\"PutOff\" where current_status=\"Ablaze\" and location=?',(loc,))\n print('done')\n conn.commit()\n p1=conn.execute('Select * from adminfire')\n q1=p1.fetchall()\n print(q1)\n conn.close()\n return (\"Thank You\")\n #except:\n #return render_template('update.html')\n return render_template('update.html')\n@app.route('/notifyme',methods=['POST','GET'])\ndef notifyme():\n if request.method == 'POST':\n try:\n username=request.form['username']\n email=request.form['email']\n phone=request.form['phone_number']\n location=request.form['location']\n print(username)\n print(email)\n print(phone)\n print(location)\n con=connect(\"firefighters.db\")\n\n\n con.execute(\"INSERT INTO users(name,phone_number,email,address) VALUES(?,?,?,?)\",(username,email,phone,location) )\n con.commit()\n msg = \"Record successfully added\"\n print(msg)\n con.close()\n except:\n con.rollback()\n print(\"Error Message\")\n finally:\n con.close()\n\n return render_template('notifyme.html')\n\n@app.route('/safeguard/causesoffire')\ndef causesoffire():\n return render_template('causesoffire.html')\n@app.route('/safeguard/inchargetable')\ndef inchargetable():\n return render_template('inchargetable.html')\n@app.route('/safeguard/safetymeasures')\ndef safetymeasures():\n return render_template('safetymeasures.html')\n@app.route('/safeguard/tutorials')\ndef tutorials():\n return render_template('tutorials.html')\n@app.route('/insert',methods=['GET','POST'])\ndef insert():\n if request.method == 'POST':\n\n try:\n\n lat=request.form['latitude']\n long=request.form['longitude']\n loc=request.form['location']\n cause=request.form['cause']\n intensity=request.form['intensity']\n cas=request.form['casualities']\n status=request.form['current_status']\n firefighter=request.form['firefighter']\n print(lat)\n print(long)\n print(cas)\n con=connect(\"firefighters.db\")\n con.execute(\"INSERT INTO adminfire(cause,location,intensity,latitude,firefighter,casualities,longitude,current_status) VALUES(?,?,?,?,?,?,?,?)\",(cause,loc,intensity,lat,firefighter,cas,long,status) )\n con.commit()\n msg = \"Record successfully added\"\n print(msg)\n con.close()\n except:\n con.rollback()\n print(\"Error Message\")\n finally:\n con.close()\n\n return render_template('insert.html')\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"TSEC/venv/bin/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":10789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"635642361","text":"#!/usr/bin/env python2\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom keras.models import Sequential, load_model\nfrom keras.layers.core import Dense, Dropout, Activation\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten\nfrom keras.optimizers import SGD, Adam\nfrom keras.utils import np_utils\nfrom keras.datasets import mnist\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint, Callback\nfrom keras.regularizers import l2\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers.normalization import BatchNormalization\nfrom PIL import Image\n\nFF = open('dnn_history.csv', 'w')\nclass History(Callback):\n\tdef on_train_begin(self,logs={}):\n\t\tself.tr_los=[]\n\t\tself.vl_los=[]\n\t\tself.tr_acc=[]\n\t\tself.vl_acc=[]\n\n\tdef on_epoch_end(self,epoch,logs={}):\n\t\tself.tr_los.append(logs.get('loss'))\n\t\tself.vl_los.append(logs.get('val_loss'))\n\t\tself.tr_acc.append(logs.get('acc'))\n\t\tself.vl_acc.append(logs.get('val_acc'))\n\t\tFF.write('{},{},{},{}\\n'.format(logs.get('loss'), logs.get('acc'), logs.get('val_loss'), logs.get('val_acc')))\n\t\tFF.flush()\n\nx_test = 0\n\ndef expand(data):\n\ttmp = np.flip(data, 2)\n\ttmp = np.concatenate((data, tmp), axis=0)\n\ttmp2 = [np.reshape(Image.fromarray(d[:,:,0]).rotate(10), (48, 48, 1)) for d in tmp]\n\ttmp3 = [np.reshape(Image.fromarray(d[:,:,0]).rotate(350), (48, 48, 1)) for d in tmp]\n\treturn np.concatenate((tmp, tmp2, tmp3), axis=0)\n\ndef load_data():\n\tdata = pd.read_csv('train.csv')\n\ty_train = np_utils.to_categorical(np.array(data['label']), 7)\n\n\tx_train = data['feature']\n\tx_train = np.array(map(lambda x: map(float, x.split()), x_train))\n\tx_train = np.reshape(x_train, (x_train.shape[0], 48, 48, 1))/255\n\tx_train = x_train\n\n\n\tdata = pd.read_csv('test.csv')\n\tx_test = data['feature']\n\tx_test = np.array(map(lambda x: map(float, x.split()), x_test))\n\tx_test = np.reshape(x_test, (x_test.shape[0], 48, 48, 1))/255\n\tx_test = x_test\n\n\treturn x_train, y_train, x_test\n\ndef load_and_save():\n\tx_train, y_train, x_test = load_data()\n\tfx = open('x_train', 'w')\n\tfy = open('y_train', 'w')\n\tfxx = open('x_test', 'w')\n\tpickle.dump(x_train, fx)\n\tpickle.dump(y_train, fy)\n\tpickle.dump(x_test, fxx)\n\ndef read_data():\n\tfx = open('x_train', 'r')\n\tfy = open('y_train', 'r')\n\tfxx = open('x_test', 'r')\n\tx_train = pickle.load(fx)\n\tx_train = expand(x_train)\n\t\n\ty_train = pickle.load(fy)\n\ty_train = np.concatenate((y_train, y_train, y_train, y_train, y_train, y_train), axis=0)\n\t\n\tx_test = pickle.load(fxx)\n\n\treturn x_train, y_train, x_test\n\ndef train(model, x_train, y_train, batch_size):\n\tcallback = ModelCheckpoint('dnn.h5', monitor='val_accuracy')\n\thistory = History()\n\tmodel.fit(x_train, y_train, batch_size=batch_size, epochs=150, validation_split=0.2, callbacks=[callback, history])\n\t'''\n\tfor i in range(11, 50):\n\t\tmodel.fit(x_train, y_train, batch_size=batch_size, epochs=50, validation_split=0.1, callbacks=[callback, history])\n\t\tmodel.save('model'+str((i+1)*50)+'.h5')\n\t'''\n\ndef test(x_test, batch_size):\n\tmodel = load_model('dnn.h5')\n\tpre = model.predict(x_test, batch_size)\n\tf = open('submit.csv', 'w')\n\tf.write('id,label\\n')\n\tfor i, a in enumerate(pre):\n\t\tans = np.where(a == a.max())[0][0]\n\t\tf.write('{},{}\\n'.format(i, ans))\n\tf.close()\n\ndef main():\n\t#x_train, y_train, x_test = load_data()\n\t#x_train = expand(x_train)\n\t#y_train = np.concatenate((y_train, y_train, y_train, y_train, y_train, y_train), axis=0)\n\tx_train, y_train, x_test = read_data()\n\trate = 0.1\n\tmodel = Sequential()\n\tbase = 32\n\t\t\n\tmodel.add(Flatten(input_shape=(48, 48, 1)))\n\tmodel.add(Dense(units=400, activation='relu'))\n\tmodel.add(Dropout(rate))\n\tmodel.add(Dense(units=400, activation='relu'))\n\tmodel.add(Dropout(rate))\n\tmodel.add(Dense(units=400, activation='relu'))\n\tmodel.add(Dropout(rate))\n\tmodel.add(Dense(units=400, activation='relu'))\n\tmodel.add(Dropout(rate))\n\tmodel.add(Dense(units=400, activation='relu'))\n\tmodel.add(Dropout(rate))\n\tmodel.add(Dense(units=400, activation='relu'))\n\tmodel.add(Dropout(rate))\n\tmodel.add(Dense(units=7, activation='softmax'))\n\tmodel.summary()\n\n\tmodel.compile(loss='categorical_crossentropy', optimizer=\"adam\", metrics=['accuracy'])\n\tmodel.save('dnn.h5')\n\t#model = load_model('model.h5')\n\tbatch_size = 128\n\ttrain(model, x_train, y_train, batch_size)\n\tdel model\n\ttest(x_test, batch_size)\n\nif __name__ == '__main__':\n\t#load_and_save()\n\tmain()\n","sub_path":"hw3/dnn.py","file_name":"dnn.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"395427517","text":"import re\nfrom typing import Optional, List\n\nfrom telegram import Chat, Update\nfrom telegram.ext import MessageHandler, CallbackContext\n\nfrom filters import FilterRegex\nfrom fa_export_api import PageNotFound\nfrom fa_submission import FASubmissionFull, CantSendFileType, FASubmissionShort\nfrom functionalities.functionalities import BotFunctionality, in_progress_msg\n\n\nclass NeatenFunctionality(BotFunctionality):\n FA_SUB_LINK = re.compile(r\"furaffinity\\.net/view/([0-9]+)\", re.I)\n FA_DIRECT_LINK = re.compile(r\"d\\.facdn\\.net/art/([^/]+)/(?:|stories/|poetry/|music/)([0-9]+)/\", re.I)\n FA_THUMB_LINK = re.compile(r\"t\\.facdn\\.net/([0-9]+)@[0-9]+-[0-9]+\\.jpg\")\n FA_LINKS = re.compile(f\"({FA_SUB_LINK.pattern}|{FA_DIRECT_LINK.pattern}|{FA_THUMB_LINK.pattern})\")\n\n def __init__(self, api):\n super().__init__(MessageHandler, filters=FilterRegex(self.FA_LINKS))\n self.api = api\n\n def call(self, update: Update, context: CallbackContext):\n message = update.message.text_markdown_urled or update.message.caption_markdown_urled\n submission_ids = []\n matches = self.FA_LINKS.findall(message)\n if not matches:\n return\n with in_progress_msg(update, context, \"Neatening image link\"):\n for match in matches:\n submission_id = self._get_submission_id_from_link(context.bot, update, match[0])\n if submission_id:\n submission_ids.append(submission_id)\n # Remove duplicates, preserving order\n submission_ids = list(dict.fromkeys(submission_ids))\n # Handle each submission\n for submission_id in submission_ids:\n self._handle_fa_submission_link(context.bot, update, submission_id)\n\n def _get_submission_id_from_link(self, bot, update, link: str) -> Optional[int]:\n # Handle submission page link matches\n sub_match = self.FA_SUB_LINK.match(link)\n if sub_match:\n return int(sub_match.group(1))\n # Handle thumbnail link matches\n thumb_match = self.FA_THUMB_LINK.match(link)\n if thumb_match:\n return int(thumb_match.group(1))\n # Handle direct file link matches\n direct_match = self.FA_DIRECT_LINK.match(link)\n username = direct_match.group(1)\n image_id = int(direct_match.group(2))\n submission_id = self._find_submission(username, image_id)\n if not submission_id:\n self._return_error_in_privmsg(\n bot, update,\n f\"Could not locate the image by {username} with image id {image_id}.\"\n )\n return submission_id\n\n def _handle_fa_submission_link(self, bot, update, submission_id: int):\n print(\"Found a link, ID:{}\".format(submission_id))\n try:\n submission = self.api.get_full_submission(str(submission_id))\n self._send_neat_fa_response(bot, update, submission)\n except PageNotFound:\n self._return_error_in_privmsg(bot, update, \"This doesn't seem to be a valid FA submission: \"\n \"https://www.furaffinity.net/view/{}/\".format(submission_id))\n\n def _send_neat_fa_response(self, bot, update, submission: FASubmissionFull):\n try:\n submission.send_message(bot, update.message.chat_id, update.message.message_id)\n except CantSendFileType as e:\n self._return_error_in_privmsg(bot, update, str(e))\n\n def _return_error_in_privmsg(self, bot, update, error_message: str):\n # Only send an error message in private message\n if update.message.chat.type == Chat.PRIVATE:\n bot.send_message(\n chat_id=update.message.chat_id,\n text=error_message,\n reply_to_message_id=update.message.message_id\n )\n\n def _find_submission(self, username: str, image_id: int) -> Optional[int]:\n folders = [\"gallery\", \"scraps\"]\n for folder in folders:\n submission_id = self._find_submission_in_folder(username, image_id, folder)\n if submission_id:\n return submission_id\n return None\n\n def _find_submission_in_folder(self, username: str, image_id: int, folder: str) -> Optional[int]:\n page_listing = self._find_correct_page(username, image_id, folder)\n if not page_listing:\n # No page is valid.\n return None\n return self._find_submission_on_page(image_id, page_listing)\n\n def _find_submission_on_page(self, image_id: int, page_listing: List[FASubmissionShort]) -> Optional[int]:\n for submission in page_listing:\n test_image_id = self._get_image_id_from_submission(submission)\n if image_id == test_image_id:\n return int(submission.submission_id)\n if test_image_id < image_id:\n return None\n return None\n\n def _find_correct_page(self, username: str, image_id: int, folder: str) -> Optional[List[FASubmissionShort]]:\n page = 1\n while True:\n listing = self.api.get_user_folder(username, folder, page)\n if len(listing) == 0:\n return None\n last_submission = listing[-1]\n if self._get_image_id_from_submission(last_submission) <= image_id:\n return listing\n page += 1\n\n def _get_image_id_from_submission(self, submission: FASubmissionShort) -> int:\n image_id = re.split(r\"[-.]\", submission.thumbnail_url)[-2]\n return int(image_id)","sub_path":"functionalities/neaten.py","file_name":"neaten.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"174284700","text":"import vk_api\nimport config\nimport random\n\nvk_group_session = vk_api.VkApi(token=config.admin_token).get_api()\nall_reposts = []\nvalid_reposts = []\n\ndef isSubscribed(user):\n return vk_group_session.groups.isMember(access_token = config.club_token, group_id = 169971271, user_id = user[\"id\"])\n\ndef getValidReposts(reposts):\n return list(filter(isSubscribed, reposts))\n\ndef getAllReposts():\n return vk_group_session.wall.getReposts(owner_id = -169971271, post_id = 4929, count = 30)\n\ndef main():\n all_reposts = getAllReposts()\n valid_reposts = getValidReposts(all_reposts['profiles'])\n\n print('Random repost script for Beatbox | MemESH is ready to work!')\n \n while 1:\n print('Enter command: ', end='')\n command = input()\n if (command == 'reposted'):\n count = 0\n for user in valid_reposts:\n count += 1\n print(count, user['first_name'], user['last_name'])\n \n\n if (command == 'go'):\n secure_random = random.SystemRandom()\n for x in range(3):\n random_user = secure_random.choice(valid_reposts)\n print(x + 1, 'место -', random_user['first_name'], random_user['last_name'])\n\n if (command == 'all'):\n count = 0\n for user in all_reposts['profiles']:\n count += 1\n print(count, user['first_name'], user['last_name'])\n for group in all_reposts['groups']:\n count += 1\n print(count, group['name'])\n\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"randomRepost.py","file_name":"randomRepost.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"121562697","text":"from DataReader import DataReader\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\ntraining_dataset = DataReader.read_data('data/keystrokesTrainTwoClass.csv', ',')\ntest_dataset = DataReader.read_data('data/keystrokesTestTwoClass.csv', ',')\n\ntraining_numpy_array = np.array(training_dataset.unpack_params()).T\ncovariance = np.cov(training_numpy_array)\n\n# eigenvectors and eigenvalues for the from the covariance matrix\neigenvalues, eigenvectors = np.linalg.eig(covariance)\n\ntransformed_training_dataset = training_dataset.principal_component(2)\n\nclass1_x = map(lambda x: x.params[0], transformed_training_dataset.get_by_class(0.0))\nclass1_y = map(lambda x: x.params[1], transformed_training_dataset.get_by_class(0.0))\nclass2_x = map(lambda x: x.params[0], transformed_training_dataset.get_by_class(1.0))\nclass2_y = map(lambda x: x.params[1], transformed_training_dataset.get_by_class(1.0))\n\nfig = plt.figure('Principal component analysis', dpi=150)\nax = fig.add_subplot(211)\n\nfig.tight_layout()\n\nax.set_title('Eigenspectrum')\nax.set_xlabel('Attribute')\nax.set_ylabel('Eigenvalues')\n\nplt.plot(range(21), sorted(eigenvalues.tolist(), reverse=True), color='b', label=\"Eigenspectrum\")\nplt.legend(loc=\"upper left\")\n\nax1 = fig.add_subplot(212)\nax1.set_title('Scatter plot')\nax1.set_xlabel('Principal component 1')\nax1.set_ylabel('Principal component 2')\n\nplt.plot(class1_x, class1_y, '.', color=[0, 0, 0], label=\"Class 1\")\nplt.plot(class2_x, class2_y, '.', color='red', label=\"Class 2\")\nplt.legend(loc=\"upper left\")\n\nplt.show()","sub_path":"exam/troels.thomsen.qvw203_4.py","file_name":"troels.thomsen.qvw203_4.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"408906047","text":"# -*- coding: utf-8 -*-\nimport os\n# バッチルート\nbatchRoot = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))\n# 正常終了コード\nnormalCode = 0\n# 警告終了コード\nwarningCode = 50\n# 異常終了コード\nerrorCode = 100\n# 致命的異常コード(引数不正)\nargsErrorCode = 101\n# 致命的異常コード(Logger作成エラー)\nloggerErrorCode = 102\n# データベース接続情報キー\nconnectionInfoReg = r'.*_connection_info$'\n# パラメータ不正(設定なし)\ninvalidNotFound = 'Not Found'\n# ログルート\nlogRoot = batchRoot + '/logs'\n# tmpルート\ntmpRoot = batchRoot + '/tmp'\n# みなし日ファイルパス\nsystemDateFile = tmpRoot + '/BATCH_SYSTEM_DATE'\n# タイムアウト時間(秒)\ntimeoutDurationSec = 4*60*60\n\n","sub_path":"lib/CommonConstant.py","file_name":"CommonConstant.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"419020271","text":"#coding: utf-8\nimport csv\nimport re\ndef myreader(csv_reader):\n while True:\n try: yield next(csv_reader)\n except csv.Error:\n pass\n continue\n \n\nwith open ('/Users/LYY/Desktop/friends.csv','wb')as w:\n with open('/Users/LYY/Desktop/yelp_academic_dataset_user.csv','rb')as r:\n reader= myreader(csv.reader(r,delimiter=','))\n writer= csv.writer(w)\n for row in reader:\n if len(row[3])>3:\n check= re.match(r'\\[\\'.+\\'',row[3])\n if check:\n friends= re.compile(r'(\\'[A-Za-z0-9\\-]+\\')')\n item= re.findall(friends,row[3])\n for i in range(len(item)):\n list1= [row[16],item[i]]\n writer.writerow(list1)\n","sub_path":"friends.py","file_name":"friends.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"277009254","text":"from math import pi\nimport random\n# Functions are first-class citizens in Python.\n\n# They can be passed as arguments to other functions,\n# returned as values from other functions, and\n# assigned to variables and stored in data structures.\n\n\ndef myfunc(a, b):\n return a + b\n\n\nfuncs = [myfunc]\nprint(funcs[0])\nprint(funcs[0](2, 3))\nprint(myfunc(2, 3))\n\nlist1 = range(3)\nlist2 = range(5)\nprint(list(list2))\n\nprenom = 0\nif (isinstance(prenom, str)):\n print(\"C'est une chaine de caractere\")\nelse:\n print(\"Ce n'est pas une chaine de caractere\")\n\n\nphrase = \"Bonjour tout le monde.\"\nnouvelle_phrase = phrase.replace(\"Bonjour\", \"Bonsoir\")\nprint(nouvelle_phrase)\n\nchaine = \"Tom, Matteo, Amedeo, Julien, Chloe, Lucie, Eliott\".split(\", \")\nchaine.sort()\nchaine = \", \".join(chaine)\nprint(chaine)\n\nrayon = 10.0\nvolume = (4*pi)/3 * rayon**3\nprint(volume)\n","sub_path":"Tests/test6-func.py","file_name":"test6-func.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"18364201","text":"import cv2 as cv\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom skimage.morphology import disk\nfrom skimage.util import img_as_ubyte\nfrom skimage.filters.rank import entropy\nfrom skimage.io import imread\n\ndef entp(x):\n temp = np.multiply(x, np.log(x))\n temp[np.isnan(temp)] = 0\n return temp\n\n\nsk_image = cv.imread('standard_test_images/jetplane.tif', 0)\nimage = img_as_ubyte(sk_image)\n\nH = cv.calcHist([image], [0], None, [256], [0,256])\ntheta = np.zeros(256)\nHf = np.zeros(256)\nHb = np.zeros(256)\n\nfor T in range(1,255):\n Hf[T] = - np.sum( entp(H[:T-1] / np.sum(H[1:T-1])) )\n Hb[T] = - np.sum( entp(H[T:] / np.sum(H[T:])) )\n theta[T] = Hf[T] + Hb[T]\n\ntheta_max = np.argmax(theta)\n\nret, im_shannon = cv.threshold(image, theta_max, 255, cv.THRESH_BINARY) \n\nfig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 4),\n sharex=True, sharey=True)\n\nimg0 = ax0.imshow(image, cmap=plt.cm.gray)\nax0.set_title(\"Imagem Original\")\nax0.axis(\"off\")\nfig.colorbar(img0, ax=ax0)\n\nimg1 = ax1.imshow(im_shannon, cmap='gray')\nax1.set_title(\"Entropia\")\nax1.axis(\"off\")\nfig.colorbar(img1, ax=ax1)\n\nfig.tight_layout()\n\nplt.show() ","sub_path":"Lista 2/ex6_b.py","file_name":"ex6_b.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"115988895","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, exceptions\nfrom datetime import datetime\n\nPROGRESS_INFO = [(\"draft\", \"Draft\"), (\"confirmed\", \"Confirmed\"), (\"approved\", \"Approved\"), (\"cancel\", \"Cancel\")]\nCURRENT_DATE = datetime.now().strftime(\"%Y-%m-%d\")\nCURRENT_TIME = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\nINDIA_TIME = datetime.now().strftime(\"%d-%m-%Y %H:%M:%S\")\n\n\nclass StoreReturn(models.Model):\n _name = \"store.return\"\n _inherit = \"mail.thread\"\n\n date = fields.Date(string=\"Date\", required=True, default=CURRENT_DATE)\n name = fields.Char(string=\"Name\", readonly=True)\n department_id = fields.Many2one(comodel_name=\"hr.department\", string=\"Department\", required=True)\n returned_by = fields.Many2one(comodel_name=\"arc.person\", string=\"Returned By\", readonly=True)\n approved_by = fields.Many2one(comodel_name=\"arc.person\", string=\"Approved By\", readonly=True)\n progress = fields.Selection(selection=PROGRESS_INFO, string=\"Progress\", default=\"draft\")\n return_detail = fields.One2many(comodel_name=\"store.return.detail\", inverse_name=\"return_id\", string=\"Return Detail\")\n writter = fields.Char(string=\"Writter\", track_visibility=\"always\")\n\n @api.multi\n def trigger_confirm(self):\n returned_by = self.env.user.person_id.id\n writter = \"Store Return Confirmed by {0} on {1}\".format(self.env.user.name, INDIA_TIME)\n self.write({\"progress\": \"confirmed\", \"writter\": writter, \"returned_by\": returned_by})\n\n @api.multi\n def trigger_cancel(self):\n cancel_by = self.env.user.person_id.id\n writter = \"Store Return cancel by {0} on {1}\".format(self.env.user.name, INDIA_TIME)\n self.write({\"progress\": \"cancel\", \"writter\": writter, \"approved_by\": cancel_by})\n\n def generate_accept(self, recs):\n accept_detail = []\n for rec in recs:\n accept_detail.append((0, 0, {\"reference\": rec.name,\n \"product_id\": rec.product_id.id,\n \"description\": rec.description,\n \"returned_quantity\": rec.approved_quantity}))\n\n if accept_detail:\n accept = {\"return_id\": self.id,\n \"department_id\": self.department_id.id,\n \"accept_detail\": accept_detail}\n\n self.env[\"store.accept\"].create(accept)\n\n @api.multi\n def trigger_approve(self):\n approved_by = self.env.user.person_id.id\n recs = self.env[\"store.return.detail\"].search([(\"return_id\", \"=\", self.id), (\"approved_quantity\", \">\", 0)])\n\n if not recs:\n raise exceptions.ValidationError(\"Error! No Products found\")\n\n self.generate_accept(recs)\n\n writter = \"Store Return Approved by {0} on {1}\".format(self.env.user.name, INDIA_TIME)\n self.write({\"progress\": \"approved\", \"writter\": writter, \"approved_by\": approved_by})\n\n @api.model\n def create(self, vals):\n vals[\"name\"] = self.env[\"ir.sequence\"].next_by_code(self._name)\n return super(StoreReturn, self).create(vals)\n\n\nclass StoreReturnDetail(models.Model):\n _name = \"store.return.detail\"\n\n name = fields.Char(string=\"Name\", readonly=True)\n product_id = fields.Many2one(comodel_name=\"arc.product\", string=\"Item\", required=True)\n description = fields.Text(string=\"Item Description\")\n uom_id = fields.Many2one(comodel_name=\"product.uom\", string=\"UOM\", related=\"product_id.uom_id\")\n returned_quantity = fields.Float(string=\"Return Quantity\", default=0, required=True)\n approved_quantity = fields.Float(string=\"Approved Quantity\", default=0, required=True)\n return_id = fields.Many2one(comodel_name=\"store.return\", string=\"Store Return\")\n progress = fields.Selection(selection=PROGRESS_INFO, string=\"Progress\", related=\"return_id.progress\")\n\n @api.constrains(\"returned_quantity\")\n def check_requested_quantity(self):\n if self.approved_quantity > self.returned_quantity:\n raise exceptions.ValidationError(\"Error! Approved quantity more than return quantity\")\n\n @api.model\n def create(self, vals):\n vals[\"name\"] = self.env[\"ir.sequence\"].next_by_code(self._name)\n return super(StoreReturnDetail, self).create(vals)\n","sub_path":"models/store/store_return.py","file_name":"store_return.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"374823184","text":"import sklearn\nimport graphviz\nimport numpy as np\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.tree import export_graphviz\n\n\ndef modelo_teste(x1,y1):\n SEED = 3000\n np.random.seed(SEED)\n treino_x1, teste_x1, treino_y1, teste_y1 = train_test_split(x1, y1, test_size=0.25, stratify=y1)\n\n\n scaler = StandardScaler()\n scaler.fit(treino_x1)\n treino_x1 = scaler.transform(treino_x1)\n teste_x1 = scaler.transform(teste_x1)\n\n modelo = LinearSVC()\n modelo.fit(treino_x1, treino_y1)\n previsoes = modelo.predict(teste_x1)\n\n misterioso1 = [75.0, 0, 0, 1, 0, 1, 100]\n misterioso2 = [55.0, 0, 0, 0, 0, 1, 4]\n testeM = [misterioso1, misterioso2]\n resultado_teste = modelo.predict(testeM)\n print(resultado_teste)\n\n\n acuracia = accuracy_score(teste_y1, previsoes) * 100\n print(\"treino com %d elementos e teste com %d elementos\" % (len(treino_x1), len(teste_x1)))\n print(\"Acuracia de: %.2f%%\" % acuracia)\n\n features1 = x1.columns\n dot_data1 = export_graphviz(modelo, out_file=None,\n filled=True, rounded=True,\n feature_names=features1,\n class_names=[\"sim\", \"não\"])\n grafico1 = graphviz.Source(dot_data1)\n #grafico1","sub_path":"teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"615344865","text":"import os\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport uabRepoPaths\nimport sis_utils\n\nrun_ids = [1, 2, 3, 4, 5]\nrun_types = ['random', 'grid']\nresult_all = np.zeros((len(run_types), len(run_ids)))\ncity_res = np.zeros((len(run_types), 5, len(run_ids)))\ncity_dict = {'austin':0, 'chicago':1, 'kitsap':2, 'tyrol-w':3, 'vienna':4}\n\nfor cnt_1, run_id in enumerate(run_ids):\n for cnt_2, model_type in enumerate(run_types):\n model_name = \\\n 'UnetCrop_inria_aug_{}_{}_PS(572, 572)_BS5_EP100_LR0.0001_DS60_DR0.1_SFN32'.format(model_type, run_id)\n res_path = os.path.join(uabRepoPaths.evalPath, 'grid_vs_random', model_name, 'inria', 'result.txt')\n with open(res_path, 'r') as f:\n results = f.readlines()\n\n mean_iou_A = 0\n mean_iou_B = 0\n for item in results:\n city_name = item.split(' ')[0]\n if len(item.split(' ')) == 1:\n mean_iou = float(item) * 100\n continue\n A, B = item.split('(')[1].strip().strip(')').split(',')\n mean_iou_A += float(A)\n mean_iou_B += float(B)\n iou = float(A)/float(B) * 100\n city_res[cnt_2, city_dict[city_name[:-1]], cnt_1] = iou\n result_all[cnt_2, cnt_1] = mean_iou_A/mean_iou_B * 100\n\nmatplotlib.rcParams.update({'font.size': 18})\nplt.figure(figsize=(11, 6))\n\nplt.subplot(121)\nbp = plt.boxplot(np.transpose(result_all))\nplt.setp(bp['boxes'][0], color='red')\nplt.setp(bp['boxes'][1], color='green')\nplt.xticks(np.arange(len(run_types))+1, run_types)\nfor cnt, b in enumerate(bp['boxes']):\n b.set_label(run_types[cnt])\nplt.legend()\nplt.xlabel('Patch Extraction Type')\nplt.ylabel('IoU')\nplt.title('Overall IoU Comparison')\n\nplt.subplot(122)\npositions = np.arange(5)\nwidth = 0.35\nbp1 = plt.boxplot(np.transpose(city_res[0, :, :]), positions=positions, widths=width)\nbp2 = plt.boxplot(np.transpose(city_res[1, :, :]), positions=positions+width, widths=width)\nplt.setp(bp1['boxes'], color='red')\nplt.setp(bp2['boxes'], color='green')\nplt.title('City-wise IoU Comparison')\nplt.xticks(positions+width/2, ['Austin', 'Chicago', 'Kitsap', 'Tyrol-w', 'Vienna'], rotation=-12)\nplt.xlabel('City Name')\nplt.ylabel('IoU')\nplt.tight_layout()\n\nimg_dir, task_dir = sis_utils.get_task_img_folder()\nplt.savefig(os.path.join(img_dir, 'unet_grid_vs_random_inria_fixed.png'))\n\nplt.show()\n","sub_path":"]tasks/2018.01.23.score_results/plot_inria_unet_grid_vs_random.py","file_name":"plot_inria_unet_grid_vs_random.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"449988777","text":"import os\n\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"3\" # or any {'0', '1', '2'}\n\nimport tensorflow as tf\n\nphysical_devices = tf.config.list_physical_devices(\"GPU\")\nif len(physical_devices) > 0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n\nfrom tensorflow.keras import layers\nfrom luigi import ExternalTask, LocalTarget, Task, Parameter\nimport pb_etl.luigi.dask.target as lt\nfrom pb_etl.luigi.task import Requirement, Requires, TargetOutput, SaltedOutput\n\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom dask import dataframe as dd\n\n# Domain attributes\nattr_type = {\n \"TRANSACTION_ID\": \"int64\",\n \"TLD\": \"object\",\n \"REN\": \"int64\",\n \"REGISTRAR_NAME\": \"object\",\n \"GL_CODE_NAME\": \"object\",\n \"COUNTRY\": \"object\",\n \"DOMAIN_LENGTH\": \"int64\",\n \"HISTORY\": \"object\",\n \"TRANSFERS\": \"int64\",\n \"TERM_LENGTH\": \"object\",\n \"RES30\": \"int64\",\n \"RESTORES\": \"int64\",\n \"REREG\": \"object\",\n \"QTILE\": \"object\",\n \"HD\": \"object\",\n \"NS_V0\": \"float64\",\n \"NS_V1\": \"float64\",\n \"NS_V2\": \"float64\",\n \"TARGET\": \"int64\",\n}\n# Traffic score file format\nts_type = {\"TRANSACTION_ID\": \"int64\", \"TRAFFIC_SCORE\": \"float64\"}\n\n# Fields to be normalized\nattr_norm = [\"REN\", \"DOMAIN_LENGTH\", \"TRANSFERS\", \"RESTORES\", \"TRAFFIC_SCORE\"]\ncat_col = [\n \"TLD\",\n \"REGISTRAR_NAME\",\n \"GL_CODE_NAME\",\n \"COUNTRY\",\n \"HISTORY\",\n \"TERM_LENGTH\",\n \"RES30\",\n \"REREG\",\n \"QTILE\",\n \"HD\",\n]\n# All numeric Attributes\nnum_col = attr_norm.copy()\nnum_col.extend([\"NS_V0\", \"NS_V1\", \"NS_V2\"])\n\n\ndef df_to_dataset(dataframe, shuffle=True, batch_size=32):\n\n \"\"\"\n A utility function to create a tf.data dataset from a Pandas Dataframe\n\n :param dataframe: iput data\n :param shuffle: shuffle flag (True/False)\n :param batch_size: Batch Size\n :return: ts. data.Dataset\n \"\"\"\n\n dataframe = dataframe.copy()\n\n labels = dataframe.pop(\"TARGET\")\n\n ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))\n\n if shuffle:\n ds = ds.shuffle(buffer_size=len(dataframe))\n\n ds = ds.batch(batch_size)\n\n return ds\n\n\nclass ExtData(ExternalTask):\n\n \"\"\"\n base class to work with aws s3\n \"\"\"\n\n __version__ = \"0.0.0\"\n\n # must be assigned in the child class\n data_source = \"\"\n\n def output(self):\n src_data_path_default = \"s3://md-en-csci-e-29-final/\"\n\n # Using .env variable to do tests from local file system\n\n src_data_path = os.getenv(\"FINAL_PROJ_BUCKET\", default=src_data_path_default)\n\n return lt.CSVTarget(\n src_data_path + self.data_source,\n storage_options=dict(requester_pays=True),\n flag=None,\n )\n\n\nclass TrnAttr(ExtData):\n \"\"\"\n Getting domain attributes training data set\n \"\"\"\n\n data_source = \"train/attr/\"\n\n\nclass TrnTscore(ExtData):\n \"\"\"\n Getting domain traffic score for training dataset\n \"\"\"\n\n data_source = \"train/tscore/\"\n\n\nclass TstAttr(ExtData):\n \"\"\"\n Getting data to create dataset to forecast\n \"\"\"\n\n data_source = \"test/attr/\"\n\n\nclass TstTscore(ExtData):\n \"\"\"\n Getting traffic score to add to the forecast dataset\n \"\"\"\n\n data_source = \"test/tscore/\"\n\n\nclass BackTestRslt(ExtData):\n \"\"\"Getting backtest result\"\"\"\n\n data_source = \"results/\"\n\n\nclass LoadData(Task):\n \"\"\"\n Initial stage, loading and transformation of training data\n \"\"\"\n\n __version__ = \"0.0.0\"\n\n S3TrnAttr = Requirement(TrnAttr)\n S3TrnTscore = Requirement(TrnTscore)\n\n requires = Requires()\n\n output = SaltedOutput(target_class=lt.ParquetTarget, target_path=\"./data/traindata\")\n\n def run(self):\n\n trn_atr = (\n self.input()[\"S3TrnAttr\"]\n .read_dask(dtype=attr_type)\n .set_index(\"TRANSACTION_ID\")\n )\n\n trn_ts = (\n self.input()[\"S3TrnTscore\"]\n .read_dask(dtype=ts_type)\n .set_index(\"TRANSACTION_ID\")\n )\n\n # Joining domain attributes and traffic score\n trn = trn_atr.join(trn_ts)\n\n self.output().write_dask(trn, compression=\"gzip\")\n\n\nclass NormalizationDenominators(Task):\n \"\"\"\n Generating Data to Normalize Numeric Attributes. The data will be required for creating model and for the prediction process\n \"\"\"\n\n __version__ = \"0.0.0\"\n\n train_data = Requirement(LoadData)\n requires = Requires()\n\n output = SaltedOutput(target_class=lt.ParquetTarget, target_path=\"./data/trn_max\")\n\n def run(self):\n trn = self.input().read_dask()\n trn_max = pd.DataFrame(trn[attr_norm].max().compute())\n trn_max.columns = [\"max_val\"]\n trn_max_dask = dd.from_pandas(trn_max, npartitions=1)\n self.output().write_dask(trn_max_dask, compression=\"gzip\")\n\n\nclass LoadTest(Task):\n \"\"\"\n Designing a forecast dataset\n \"\"\"\n\n __version__ = \"0.0.0\"\n\n S3TstTscore = Requirement(TstTscore)\n output = SaltedOutput(target_class=lt.ParquetTarget, target_path=\"./data/testdata\")\n S3TstAttr = Requirement(TstAttr)\n requires = Requires()\n\n def run(self):\n tst_ts = (\n self.input()[\"S3TstTscore\"]\n .read_dask(dtype=ts_type)\n .set_index(\"TRANSACTION_ID\")\n )\n tst_atr = (\n self.input()[\"S3TstAttr\"]\n .read_dask(dtype=attr_type)\n .set_index(\"TRANSACTION_ID\")\n )\n\n tst = tst_atr.join(tst_ts)\n\n self.output().write_dask(tst, compression=\"gzip\")\n\n\ndef the_norm(df, max_val_df):\n \"\"\"\n Utility function for normalization\n :param df: input dataset\n :param max_val_df: normalization values\n :return: normalized dataset\n \"\"\"\n for idx in max_val_df.index.values:\n df[idx] = df[idx] / max_val_df.loc[idx][0]\n return df\n\n\nclass FitNNModel(Task):\n\n \"\"\"\n Creating and fitting up a predictive model\n \"\"\"\n\n __version__ = \"0.0.0\"\n TheData = Requirement(LoadData)\n MaxDenoms = Requirement(NormalizationDenominators)\n requires = Requires()\n\n output = SaltedOutput(target_class=LocalTarget, target_path=\"./data/repository/nn\")\n\n def run(self):\n\n trn = self.input()[\"TheData\"].read_dask().compute()\n\n df_max = self.input()[\"MaxDenoms\"].read_dask().compute()\n\n # normalization of the input dataset. NN does not work well with attributes with different scales\n trn = the_norm(trn, df_max)\n\n # creating feature_layer\n # for more information: https://www.tensorflow.org/tutorials/structured_data/feature_columns\n # begin\n\n feature_columns = []\n\n for header in num_col:\n feature_columns.append(tf.feature_column.numeric_column(header))\n\n for header in cat_col:\n categorical_column = (\n tf.feature_column.categorical_column_with_vocabulary_list(\n header, trn[header].unique()\n )\n )\n\n indicator_column = tf.feature_column.indicator_column(categorical_column)\n feature_columns.append(indicator_column)\n\n feature_layer = tf.keras.layers.DenseFeatures(feature_columns)\n\n train, val = train_test_split(trn, test_size=0.2)\n\n train_ds = df_to_dataset(train)\n val_ds = df_to_dataset(val, shuffle=False)\n\n tf.keras.backend.set_floatx(\"float64\")\n\n # feature_layer: end\n\n # creating model\n model = tf.keras.Sequential(\n [\n feature_layer,\n layers.Dense(1024, activation=\"relu\"),\n layers.Dropout(0.2),\n layers.Dense(512, activation=\"relu\"),\n layers.Dropout(0.2),\n layers.Dense(256, activation=\"relu\"),\n layers.Dropout(0.2),\n layers.Dense(128, activation=\"relu\"),\n layers.Dropout(0.2),\n layers.Dense(64, activation=\"relu\"),\n layers.Dropout(0.1),\n layers.Dense(32, activation=\"relu\"),\n layers.Dropout(0.1),\n layers.Dense(\n 1, activation=\"sigmoid\"\n ), # classification task (0,1) - so using sigmoid\n ]\n )\n\n model.compile(\n optimizer=\"adam\",\n loss=tf.keras.losses.BinaryCrossentropy(from_logits=False),\n metrics=[\"accuracy\"],\n )\n\n # fitting the model\n nepochs = 2 # 10\n\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\n history = model.fit(train_ds, validation_data=val_ds, epochs=nepochs, verbose=0)\n\n import json\n\n # Get the dictionary containing each metric and the loss for each epoch\n history_dict = history.history\n\n # Save it under the form of a json file\n os.makedirs(\"./data/repository\")\n with open(\"./data/repository/model_hist_params\", \"w\") as opened_file:\n json.dump(history_dict, opened_file)\n\n # Saving the model in the local repository\n model.save(self.output().path)\n\n\nclass NNPredict(Task):\n\n \"\"\"\n Predicting stage. Getting model, dataset to forecast and predict\n \"\"\"\n\n __version__ = \"0.0.0\"\n Data = Requirement(LoadTest)\n MaxDenoms = Requirement(NormalizationDenominators)\n Model = Requirement(FitNNModel)\n\n requires = Requires()\n\n output = SaltedOutput(target_class=lt.ParquetTarget, target_path=\"./data/result\")\n\n def run(self):\n\n # getting data\n\n tst = self.input()[\"Data\"].read_dask().compute()\n\n df_max = self.input()[\"MaxDenoms\"].read_dask().compute()\n\n # normalization of the input dataset.\n tst = the_norm(tst, df_max)\n\n tst_dd = tf.data.Dataset.from_tensor_slices(dict(tst))\n tst_dd = tst_dd.batch(32)\n\n # getting Model\n model = tf.keras.models.load_model(self.input()[\"Model\"].path)\n tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\n # predict deletion probability\n y_test_hat = model.predict(tst_dd, verbose=0)\n\n # creating resulting dataset\n tst[\"Y_hat\"] = y_test_hat\n rslt = pd.DataFrame(y_test_hat, index=tst.index.values)\n rslt.columns = [\"Y_hat\"]\n rslt.index.name = \"TRANSACTION_ID\"\n\n # saving data into local repository\n dask_rslt = dd.from_pandas(rslt, npartitions=1)\n self.output().write_dask(dask_rslt, compression=\"gzip\")\n\n\nclass BackTest(Task):\n \"\"\"\n Backtesting. Creating backtesting dataset (transaction_id, forecast probability, actual)\n \"\"\"\n\n __version__ = \"0.0.0\"\n actl = Requirement(BackTestRslt)\n frcst = Requirement(NNPredict)\n requires = Requires()\n\n output = SaltedOutput(\n target_class=lt.ParquetTarget, target_path=\"./data/repository/backtest\"\n )\n\n def run(self):\n \"\"\"\n Retrieving a dataset with actual results and joining to a predicted dataset\n :return:\n \"\"\"\n df_actl = (\n self.input()[\"actl\"]\n .read_dask(dtype={\"TRANSACTION_ID\": \"int64\", \"TARGET\": \"int64\"})\n .set_index(\"TRANSACTION_ID\")\n )\n df_frcst = self.input()[\"frcst\"].read_dask(\n dtype={\"TRANSACTION_ID\": \"int64\", \"Y_hat\": \"float64\"}\n )\n\n bcktst = df_actl.join(df_frcst)\n\n self.output().write_dask(bcktst, compression=\"gzip\")\n\n\nclass FinalResults(Task):\n \"\"\"\n Printing the deletion rates (sum(actual)/count() vs. sum(forecast)/count()): actual vs forecast\n \"\"\"\n\n back_tests = Requirement(BackTest)\n requires = Requires()\n\n def run(self):\n bcktst = self.input().read_dask()\n ln = bcktst.count().compute()\n\n print(\"=== FINAL RESULTS ===\")\n print(\"=== Real Deletion Rate (TARGET) ===\")\n print(\"=== Forecasted deletion rate (Y_hat) ===\")\n print(bcktst.sum().compute() / ln)\n print(\"==============================\")\n","sub_path":"pb_etl/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":11810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"476031717","text":"import os\nos.environ['KERAS_BACKEND']='theano'\nimport numpy as np\nfrom keras import backend as K\nfrom keras.engine.topology import Layer, InputSpec\nfrom keras import initializers\nfrom keras.preprocessing.text import Tokenizer, text_to_word_sequence\nfrom keras.utils.np_utils import to_categorical\nfrom nltk import tokenize\nfrom MasterProject.data_Preprocessing.Datasets import get_data\nfrom MasterProject.data_Preprocessing.model import get_model\nfrom sklearn.cross_validation import train_test_split\nfrom keras.layers import Dense,Input,Flatten\nfrom keras.layers import Conv1D,MaxPooling1D,Embedding,Merge,Dropout, LSTM, GRU, Bidirectional, TimeDistributed\nfrom keras.models import Model\nfrom MasterProject.data_Preprocessing.HAN_Classifier.HAN_Helper import Helper\nfrom keras.models import Sequential\nfrom keras.optimizers import rmsprop\nfrom keras.optimizers import Adam\nimport matplotlib.pyplot as plt\nfrom keras import regularizers\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom gensim.models import Word2Vec\n\nimport matplotlib\nimport pickle\n\n#final parmeters\nL2PARAM = 0.01\nWORDS_NUM = 100\nSEN_NUM = 15\nMAX_NB_WORDS = 25000\nDIM = 300\nepochs = 20\nCONTEXT_DIM = 100\n\nL2_REGULAR = regularizers.l2(L2PARAM)\n\n\n\ndef load_word2vec_embedding(modelname,vocabulary):\n #word2vec.txt\n file = open(modelname, 'r')\n lines = file.readlines()[1:]\n file.close()\n\n #create a word2vec vocab\n word2vec_dict = dict()\n for line in lines:\n splits = line.split()\n word = splits[0]\n value = splits[1:]\n\n word2vec_dict[word] = np.asarray(value, dtype='float32')\n\n #create a word embedding layer\n embedding_matrix = np.random.random((len(vocabulary) + 1, DIM))\n count = 0\n for word, index in vocabulary.items():\n vector = word2vec_dict.get(word)\n if (vector is not None):\n count = count + 1\n embedding_matrix[index] = vector\n\n print(count)\n\n return embedding_matrix\n\n#get the data input (matrix form)\ndef get_matrix(reviews, sentences,vocabulary):\n texts_matrix = np.zeros((len(reviews),SEN_NUM,WORDS_NUM),dtype='int32')\n print(texts_matrix.shape)\n\n for index1,review in enumerate(sentences):\n for index2, sentence in enumerate(review):\n if(index2 InfosBD:\n src = path + '.mkv'\n src_clip = lvf.src(src); vdf.set_ffms2_log_level('warning')\n src_cut = src_clip[frame_start:frame_end] if (frame_start or frame_end) else src_clip\n\n name = Path(sys.argv[0]).stem\n output = name + '.mkv'\n return InfosBD(path, src, src_clip, frame_start, frame_end,\n src_cut, None, None, None,\n name, output, None, None)\n\n\nJPBD_NCOP = infos_bd(r'戦姫絶唱シンフォギアG\\[BDMV][131106] 戦姫絶唱シンフォギアG 2\\KIXA_90350\\BDMV\\STREAM\\00006', 24, -24)\nJPBD_10 = infos_bd(r'戦姫絶唱シンフォギアG\\[BDMV][140205] 戦姫絶唱シンフォギアG 5\\KIXA_90354\\BDMV\\STREAM\\00004', 0, -24)\n\n\n\ndef do_filter():\n \"\"\"Vapoursynth filtering\"\"\"\n opstart_ep10 = 768\n ncop = JPBD_NCOP.src_cut\n ep10 = JPBD_10.src_cut\n\n ncop = lvf.rfs(ncop, ep10[opstart_ep10:], [(0, 79), (1035, 1037)])\n\n return ncop\n\n\n\ndef do_encode(clip: vs.VideoNode)-> None:\n \"\"\"Compression with x265\"\"\"\n print('\\n\\n\\nVideo encoding')\n if not os.path.exists(JPBD_NCOP.output):\n ffv1_args = [\n 'ffmpeg', '-i', '-', '-vcodec', 'ffv1', '-coder', '1', '-context', '0',\n '-g', '1', '-level', '3', '-threads', '8',\n '-slices', '24', '-slicecrc', '1', \"_assets/\" + JPBD_NCOP.name + \"_lossless.mkv\"\n ]\n print(\"Encoder command: \", \" \".join(ffv1_args), \"\\n\")\n process = subprocess.Popen(ffv1_args, stdin=subprocess.PIPE)\n clip.output(process.stdin, y4m=True, progress_update=lambda value, endvalue:\n print(f\"\\rVapourSynth: {value}/{endvalue} ~ {100 * value // endvalue}% || Encoder: \", end=\"\"))\n process.communicate()\n\n\n\n\nif __name__ == '__main__':\n FILTERED = do_filter()\n do_encode(FILTERED)\n","sub_path":"Kodoku no Kawarini (KnK)/Senki Zesshou Symphogear G [BD]/symphogearg_ncop01_raw.py","file_name":"symphogearg_ncop01_raw.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"51075941","text":"class Graph:\n def __init__(self, vertex_number):\n self.vertex_number = vertex_number\n self.edges = []\n self.vertexes = []\n for i in range(vertex_number):\n self.vertexes.append([i])\n self.matrix = [[0 for i in range(vertex_number)] for j in range(vertex_number)]\n\n def add_edge(self, u, v, w):\n if v < u:\n u, v = v, u\n self.edges.append((u - 1, v - 1, w))\n self.matrix[u - 1][v - 1] = w\n self.matrix[v - 1][u - 1] = w\n\n def len_of_comp(self, u):\n for i in range(len(self.vertexes)):\n if u in self.vertexes[i]:\n return len(self.vertexes[i]), i\n return 0, -1\n\n def kruskal(self):\n print('\\t\\tKRUSKAL')\n used_vertexes = set()\n used_edges = set()\n ostov_size = 0\n ostov_weight = 0\n components = self.vertexes.copy()\n sorted_edges = sorted(self.edges, key=lambda x: x[2])\n for edge in sorted_edges:\n u, v, w = edge\n u_len, u_i = self.len_of_comp(u)\n v_len, v_i = self.len_of_comp(v)\n if u_i != v_i:\n used_vertexes.add(u), used_vertexes.add(v)\n if u_len > v_len:\n components[u_i] += components[v_i]\n components[v_i].clear()\n else:\n components[v_i] += components[u_i]\n components[u_i].clear()\n used_edges.add(edge)\n ostov_weight += w\n ostov_size += 1\n print(f\"Ostov weight: {ostov_weight}\")\n for edge in sorted_edges:\n out_str = f\"{edge[0] + 1} - {edge[1] + 1} : {edge[2]}\"\n if edge in used_edges:\n print(\"OSTOV {} OSTOV\".format(out_str))\n else:\n print(out_str)\n print(\"Components:\", [comp for comp in components])\n\n def min_dist(self, node, used):\n mini = -1\n for v in range(self.vertex_number):\n if self.matrix[node][v] < mini and v not in used:\n mini = self.matrix[node][v]\n min_index = v\n return mini, min_index\n\n def find_distances(self, new, distances):\n for v in range(self.vertex_number):\n if self.matrix[new][v] < distances[v] and self.matrix[new][v] != 0 and distances[v] != -1:\n distances[v] = self.matrix[new][v]\n return distances\n\n def min_v(self, distances):\n minv = float('inf')\n for x in distances:\n if x != -1 and x < minv:\n minv = x\n return minv\n\n def prim(self):\n print('\\t\\tPRIM')\n ostov_weight = 0\n ostov_size = 1\n used_vertexes = list([0])\n distances = [float('inf') for i in range(self.vertex_number)]\n distances[0] = -1\n used_edges = []\n v = 0\n while ostov_size < self.vertex_number:\n distances = self.find_distances(v, distances)\n min_w = self.min_v(distances)\n if min_w != float('inf'):\n vv = v\n v = distances.index(min_w)\n distances[v] = -1\n used_edges.append([vv, v])\n used_vertexes.append(v)\n ostov_weight += min_w\n ostov_size += 1\n for i in range(len(used_vertexes)):\n used_vertexes[i] += 1\n print('Ostov weight:', ostov_weight)\n print('Used vertexes:', used_vertexes)\n\n\nif __name__ == '__main__':\n graph = Graph(8)\n graph.add_edge(1, 2, 6)\n graph.add_edge(2, 3, 12)\n graph.add_edge(3, 8, 1)\n graph.add_edge(8, 7, 2)\n graph.add_edge(7, 6, 5)\n graph.add_edge(6, 1, 10)\n graph.add_edge(1, 4, 1)\n graph.add_edge(2, 4, 1)\n graph.add_edge(6, 4, 1)\n graph.add_edge(7, 4, 7)\n graph.add_edge(7, 5, 5)\n graph.add_edge(8, 5, 8)\n graph.add_edge(3, 5, 1)\n graph.add_edge(2, 5, 1)\n graph.add_edge(4, 5, 4)\n graph.kruskal()\n graph.prim()\n","sub_path":"LR-2/kruskal_and_prim.py","file_name":"kruskal_and_prim.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"638887163","text":"import re\nimport ssl\nimport urllib\nfrom bs4 import BeautifulSoup\nimport urllib.request, urllib.parse, urllib.error\nfrom Helpers.urlmanager import *\n# Uncomment to test in this file:\n# from urlmanager import *\n\ndef findCarLinks(craigslist_url):\n result = []\n response = urllib.request.urlopen(craigslist_url)\n html = response.read()\n soup = BeautifulSoup(html, 'html.parser')\n\n links = soup.find_all('a', attrs={'class':'result-title hdrlnk'})\n\n result = [link.get('href') for link in links]\n return result\n\ndef parsePages(page_url):\n result = {}\n\n response = urllib.request.urlopen(page_url)\n html = response.read()\n soup = BeautifulSoup(html, 'html.parser')\n result['url'] = page_url\n info = soup.find_all('b')\n pic_link = soup.find_all('img', attrs={'title':'1'})\n try:\n pic_link[0].get('src')\n except:\n result['pic'] = \"\"\n else:\n result['pic'] = pic_link[0].get('src')\n counter = 1\n for piece in info:\n new_piece = piece.parent.getText().encode('ascii', 'ignore').decode('utf-8')\n split_pieces = new_piece.split(':')\n if counter > 1:\n try:\n split_pieces[1] = split_pieces[1].replace(\" \", \"\", 1)\n result[split_pieces[0]] = split_pieces[1]\n except:\n print('badcarvalue')\n else:\n split_pieces[1] = split_pieces[1].replace(\" \", \"\", 1)\n result[split_pieces[0]] = split_pieces[1]\n else:\n result['car'] = split_pieces[0]\n try:\n int(split_pieces[0][0:4])\n except:\n result['model year'] = \"\"\n else:\n result['model year'] = split_pieces[0][0:4]\n price = soup.find_all('span', attrs={'class':'price'})\n try:\n price[0].string.strip('$')\n except:\n result['price'] = '0'\n result['model year'] = \"\"\n else:\n result['price'] = price[0].string.strip('$')\n\n counter += 1\n return result\n\ndef createFile(car, file_path):\n file_name = car + '.csv'\n f = open(file_path + file_name, 'w')\n potential_values = (['url', 'car', 'price', 'model year', 'VIN', 'condition', \n 'cylinders', 'drive', 'fuel', 'odometer', 'paint color', \n 'size', 'title status', 'transmission', 'type', 'pic'])\n for value in potential_values:\n f.write(value + ',')\n f.write('\\n')\n f.close()\n\ndef dictToCSV(car, dictionary, file_path):\n file_name = car + '.csv'\n potential_values = (['url', 'car', 'price', 'model year', 'VIN', 'condition', \n 'cylinders', 'drive', 'fuel', 'odometer', 'paint color', \n 'size', 'title status', 'transmission', 'type', 'pic'])\n f = open(file_path + file_name, 'a')\n for value in potential_values:\n is_valid = dictionary.get(value)\n if is_valid:\n f.write(dictionary[value] + ',')\n else:\n f.write(',')\n f.write('\\n')\n f.close()\n\ndef getBestCars():\n result = []\n scusa_url = 'https://santanderconsumerusa.com/blog/25-vehicles-that-hold-value-best-over-five-years-iseecars-com'\n\n context = ssl._create_unverified_context()\n response = urllib.request.urlopen(scusa_url, context=context)\n html = response.read()\n soup = BeautifulSoup(html, 'html.parser')\n\n cars = soup.find_all('strong')\n counter = 1\n for car in cars:\n if (car.parent.name != 'figcaption'):\n if (counter % 2 == 0):\n result.append(car.string)\n counter += 1\n else:\n counter += 1\n return result\n\nif __name__ == '__main__':\n array = getBestCars()\n master_links = {}\n for car in array:\n url = urlManager('humboldt', 'owner') + addMakeModel(car)\n master_links[car] = findCarLinks(url)\n\n for car in master_links:\n createFile(car, 'data\\\\cardata\\\\')\n for link in master_links[car]:\n dictToCSV(car, parsePages(link), 'data\\\\cardata\\\\')\n\n ","sub_path":"Project Files/Helpers/findcarlinks.py","file_name":"findcarlinks.py","file_ext":"py","file_size_in_byte":4125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"166757051","text":"import argparse\r\nimport json\r\nimport pickle\r\nfrom collections import defaultdict, Counter\r\nfrom os.path import dirname, join\r\nimport os\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nfrom torch.utils.data import DataLoader\r\nimport numpy as np\r\n\r\nfrom dataset import Dictionary, VQAFeatureDataset\r\nimport rubi_base_model\r\nfrom rubi_train import train\r\nimport utils\r\nimport click\r\n\r\nfrom vqa_debias_loss_functions import *\r\n\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser(\"Train the BottomUpTopDown model with a de-biasing method\")\r\n\r\n # Arguments we added\r\n parser.add_argument(\r\n '--cache_features', default=True,\r\n help=\"Cache image features in RAM. Makes things much faster, \"\r\n \"especially if the filesystem is slow, but requires at least 48gb of RAM\")\r\n parser.add_argument(\r\n '--dataset', default='cpv2',\r\n choices=[\"v2\", \"cpv2\", \"cpv1\"],\r\n help=\"Run on VQA-2.0 instead of VQA-CP 2.0\"\r\n )\r\n parser.add_argument(\r\n '--mode', default=\"updn\",\r\n choices=[\"updn\", \"lmh_rubi\"],\r\n help=\"Kind of ensemble loss to use\")\r\n parser.add_argument(\r\n '--topq', type=int,default=1,\r\n choices=[1,2,3],\r\n help=\"num of q to mask\")\r\n parser.add_argument(\r\n '--keep_qtype', default=True,\r\n help=\"keep qtype or not\")\r\n parser.add_argument(\r\n '--topv', type=int,default=1,\r\n choices=[1,3,5,-1],\r\n help=\"num of v to mask\")\r\n parser.add_argument(\r\n '--top_hint',type=int, default=9,\r\n choices=[9,18,27,36], \r\n help=\"num of hint\")\r\n parser.add_argument(\r\n '--qvp', type=int,default=0,\r\n choices=[0,1,2,3,4,5,6,7,8,9,10],\r\n help=\"proportion of q/v\")\r\n parser.add_argument(\r\n '--eval_each_epoch', default=True,\r\n help=\"Evaluate every epoch, instead of at the end\")\r\n\r\n # Arguments from the original model, we leave this default, except we\r\n # set --epochs to 15 since the model maxes out its performance on VQA 2.0 well before then\r\n parser.add_argument('--epochs', type=int, default=30)\r\n parser.add_argument('--num_hid', type=int, default=1024)\r\n parser.add_argument('--model', type=str, default='baseline0_newatt')\r\n parser.add_argument('--output', type=str, default='logs/exp0') \r\n parser.add_argument('--batch_size', type=int, default=512)\r\n parser.add_argument('--seed', type=int, default=1111, help='random seed')\r\n args = parser.parse_args()\r\n return args\r\n\r\ndef get_bias(train_dset,eval_dset):\r\n # Compute the bias:\r\n # The bias here is just the expected score for each answer/question type\r\n answer_voc_size = train_dset.num_ans_candidates\r\n\r\n # question_type -> answer -> total score\r\n question_type_to_probs = defaultdict(Counter)\r\n\r\n # question_type -> num_occurances\r\n question_type_to_count = Counter()\r\n for ex in train_dset.entries:\r\n ans = ex[\"answer\"]\r\n q_type = ans[\"question_type\"]\r\n question_type_to_count[q_type] += 1\r\n if ans[\"labels\"] is not None:\r\n for label, score in zip(ans[\"labels\"], ans[\"scores\"]):\r\n question_type_to_probs[q_type][label] += score\r\n question_type_to_prob_array = {}\r\n\r\n for q_type, count in question_type_to_count.items():\r\n prob_array = np.zeros(answer_voc_size, np.float32)\r\n for label, total_score in question_type_to_probs[q_type].items():\r\n prob_array[label] += total_score\r\n prob_array /= count\r\n question_type_to_prob_array[q_type] = prob_array\r\n\r\n for ds in [train_dset,eval_dset]:\r\n for ex in ds.entries:\r\n q_type = ex[\"answer\"][\"question_type\"]\r\n ex[\"bias\"] = question_type_to_prob_array[q_type]\r\n\r\n\r\ndef main():\r\n args = parse_args()\r\n dataset=args.dataset\r\n args.output=os.path.join('logs',args.output)\r\n if not os.path.isdir(args.output):\r\n utils.create_dir(args.output)\r\n else:\r\n if click.confirm('Exp directory already exists in {}. Erase?'\r\n .format(args.output, default=False)):\r\n os.system('rm -r ' + args.output)\r\n utils.create_dir(args.output)\r\n\r\n else:\r\n os._exit(1)\r\n\r\n\r\n\r\n if dataset=='cpv1':\r\n dictionary = Dictionary.load_from_file('data/dictionary_v1.pkl')\r\n elif dataset=='cpv2' or dataset=='v2':\r\n dictionary = Dictionary.load_from_file('data/dictionary.pkl')\r\n\r\n print(\"Building train dataset...\")\r\n train_dset = VQAFeatureDataset('train', dictionary, dataset=dataset,\r\n cache_image_features=False)\r\n\r\n print(\"Building test dataset...\")\r\n eval_dset = VQAFeatureDataset('val', dictionary, dataset=dataset,\r\n cache_image_features=False)\r\n\r\n get_bias(train_dset,eval_dset)\r\n\r\n\r\n # Build the model using the original constructor\r\n constructor = 'build_%s' % args.model\r\n model = getattr(rubi_base_model, constructor)(train_dset, args.num_hid).cuda()\r\n if dataset=='cpv1':\r\n model.w_emb.init_embedding('data/glove6b_init_300d_v1.npy')\r\n elif dataset=='cpv2' or dataset=='v2':\r\n model.w_emb.init_embedding('data/glove6b_init_300d.npy')\r\n\r\n # Add the loss_fn based our arguments\r\n # model.debias_loss_fn = Focal()\r\n\r\n with open('util/qid2type_%s.json'%args.dataset,'r') as f:\r\n qid2type=json.load(f)\r\n model=model.cuda()\r\n batch_size = args.batch_size\r\n\r\n torch.manual_seed(args.seed)\r\n torch.cuda.manual_seed(args.seed)\r\n torch.backends.cudnn.benchmark = True\r\n\r\n train_loader = DataLoader(train_dset, batch_size, shuffle=True, num_workers=0)\r\n eval_loader = DataLoader(eval_dset, batch_size, shuffle=False, num_workers=0)\r\n\r\n print(\"Starting training...\")\r\n train(model, train_loader, eval_loader, args,qid2type)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"rubi_main.py","file_name":"rubi_main.py","file_ext":"py","file_size_in_byte":5895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"139564530","text":"import taichi as tc\nimport random\n\n\ndef create_taichi_text():\n text = 1 - tc.Texture(\n 'text',\n content='Taichi',\n width=200,\n height=200,\n font_file=tc.get_asset_path('fonts/go/Go-Bold.ttf'),\n size=50,\n dx=0,\n dy=0)\n mesh = tc.Mesh(\n 'plane',\n tc.SurfaceMaterial(\n 'transparent',\n nested=tc.SurfaceMaterial('diffuse', color=(1, 1, 1)),\n mask=text),\n translate=(5.0, 2, 0.05),\n scale=2,\n rotation=(90, 0, 0))\n return mesh\n\n\ndef create_scene():\n downsample = 2\n camera = tc.Camera(\n 'pinhole',\n res=(1500 // downsample, 600 // downsample),\n fov=30,\n origin=(0, 1, 20),\n look_at=(0, 2, 0),\n up=(0, 1, 0))\n\n scene = tc.Scene()\n\n with scene:\n scene.set_camera(camera)\n\n ground_tex = tc.Texture(\n 'image', filename=tc.get_asset_path('textures/paper.jpg'))\n\n mesh = tc.Mesh(\n 'plane',\n tc.SurfaceMaterial('pbr', diffuse_map=ground_tex),\n translate=(0, 0, -5),\n scale=10,\n rotation=(90, 0, 0))\n scene.add_mesh(mesh)\n\n mesh = tc.Mesh(\n 'plane',\n tc.SurfaceMaterial('pbr', diffuse_map=ground_tex),\n translate=(0, 0, 0),\n scale=10,\n rotation=(0, 0, 0))\n scene.add_mesh(mesh)\n\n mesh = tc.Mesh(\n 'plane',\n tc.SurfaceMaterial('emissive_spot', color=(1, 1, 1), exponential=3),\n translate=(0, 0, -1.5),\n scale=0.1,\n rotation=(-101, 0, 0))\n scene.add_mesh(mesh)\n\n fill_light = 0.03\n mesh = tc.Mesh(\n 'plane',\n tc.SurfaceMaterial(\n 'emissive', color=(fill_light, fill_light, 3 * fill_light)),\n translate=(0, 10, 30),\n scale=1,\n rotation=(-90, 0, 0))\n scene.add_mesh(mesh)\n\n emission = 3\n with tc.transform_scope(rotation=(0, 10, 0)):\n mesh = tc.Mesh(\n 'plane',\n tc.SurfaceMaterial(\n 'emissive_spot',\n color=(emission, emission, emission),\n exponential=100),\n translate=(10, 2, 1),\n scale=0.1,\n rotation=(0, 0, 100))\n scene.add_mesh(mesh)\n\n for j in range(3):\n for i in range(14):\n with tc.transform_scope(translate=(i - 7, (random.random() - 0.5) * 0.4,\n j)):\n with tc.transform_scope(\n rotation=(0, 0, 10 - j * 10),\n translate=(0, -j * 0.3 + i * 0.04 - 0.4, 0)):\n s = random.random() * 0.5 + 0.8\n r = random.random()\n if r < 0.5:\n shape = 'cube'\n else:\n shape = tc.geometry.create_cylinder((100, 2), smooth=False)\n mesh = tc.Mesh(\n shape,\n tc.SurfaceMaterial('diffuse', color=(0.3, 0.2, 0.1)),\n scale=(0.4 * s, 1 * s, 0.4 * s),\n rotation=(-4, -12, 0))\n scene.add_mesh(mesh)\n\n return scene\n\n\nif __name__ == '__main__':\n renderer = tc.Renderer(output_dir='shadows', overwrite=True)\n renderer.initialize(\n preset='pt',\n scene=create_scene(),\n min_path_length=2,\n max_path_length=4,\n luminance_clamping=0.1)\n renderer.set_post_processor(\n tc.post_process.LDRDisplay(exposure=0.2, bloom_radius=0.0, gamma=2.2))\n renderer.render(10000, 20)\n","sub_path":"projects/examples/rendering/trashbin/shadows.py","file_name":"shadows.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"66963954","text":"#! /usr/bin/env python3\n\nimport os\nimport time\nfrom pathlib import Path\nfrom string import Template\n\nfrontmatter = Template(\"\"\"---\nlayout: post\ntitle: \"$title\"\npreview: images/$file_name?nf_resize=fit&w=300\n---\n\n![$title](/images/$file_name?nf_resize=fit&w=900)\n\"\"\")\n\nimages_dir = \"./images\"\nposts_dir = \"./_posts\"\n\nimages = os.listdir(images_dir)\n\nfor image in images:\n name = Path(image).stem\n date = time.strftime(\"%Y-%m-%d\", time.localtime(os.path.getctime(os.path.join(images_dir, image))))\n post_file_name = date + \"-\" + name + \".markdown\"\n title = name.replace('-', ' ').title()\n contents = frontmatter.safe_substitute(title=title, file_name=image)\n print(\"writing\", post_file_name)\n with open(os.path.join(posts_dir, post_file_name), 'w') as f:\n f.write(contents)\n","sub_path":"generate-posts.py","file_name":"generate-posts.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"385068079","text":"import time\nimport pytest\nimport task_7_4a\nimport sys\nsys.path.append('..')\n\nfrom common_functions import check_function_exists, check_function_params\n\n\ndef test_func_created():\n '''Проверяем, что декоратор создан'''\n check_function_exists(task_7_4a, 'retry')\n\n\ndef test_retry_success(capsys):\n @task_7_4a.retry(times=3, delay=1)\n def do_thing(a, b):\n print('done')\n return a + b\n\n return_value = do_thing(2, 3)\n # проверка базовой работы функции\n assert return_value == 5\n\n # должно выводиться сообщение со временем выполнения\n correct_stdout = 'done'\n out, err = capsys.readouterr()\n assert out != '', \"На stdout не выведена информация\"\n assert correct_stdout in out, \"На stdout должно выводиться сообщение\"\n\n\ndef test_retry_failed(capsys):\n @task_7_4a.retry(times=2, delay=1)\n def do_thing(a, b):\n print('done')\n return None\n\n return_value = do_thing(2, 3)\n\n # должно выводиться сообщение со временем выполнения\n correct_stdout = 'done'\n out, err = capsys.readouterr()\n assert out != '', \"На stdout не выведена информация\"\n assert out.count(correct_stdout) == 3, \"При каждом выполнении функции на stdout должно выводиться сообщение\"\n assert out.count('Повторное подключение') == 2, \"При повторном выполнении функции на stdout должно выводиться сообщение\"\n\n","sub_path":"exercises/07_decorators/tests/test_task_7_4a.py","file_name":"test_task_7_4a.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601217800","text":"\"\"\"\nCopyright 2018 Skyscanner Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed\nunder the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\nCONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\n\n\nimport traceback\nimport pytest\nfrom unittest.mock import Mock, patch\nfrom unittest.mock import ANY\nimport glob\nimport os\nfrom moto import mock_s3\n\nfrom cfripper.model.utils import convert_json_or_yaml_to_dict\nfrom cfripper.model.result import Result\nfrom cfripper.rules import DEFAULT_RULES\nfrom cfripper.config.config import Config\nfrom cfripper.model.rule_processor import RuleProcessor\n\n\nclass TestMainHandler:\n def test_wrong_event_type(self):\n event = {}\n\n from cfripper.main import handler\n\n with pytest.raises(ValueError):\n handler(event, None)\n\n def test_correct_event(self):\n event = {\"stack_template_url\": \"https://asdfasdfasdf/bucket/key\", \"stack\": {\"name\": \"blooblah\"}}\n\n mock_created_s3_adapter_object = Mock()\n mock_created_s3_adapter_object.download_template_to_dictionary.return_value = {\"Resources\": {}}\n mock_boto3_adapter = Mock(return_value=mock_created_s3_adapter_object)\n\n mock_created_boto3_client_object = Mock()\n mock_created_boto3_client_object.get_template.return_value = {\"Resources\": {}}\n mock_created_boto3_client_object.compare_outputs.return_value = {}\n mock_boto3_client = Mock(return_value=mock_created_boto3_client_object)\n\n mock_created_rule_processor_object = Mock()\n mock_rule_processor = Mock(return_value=mock_created_rule_processor_object)\n\n with patch(\"cfripper.main.Boto3Client\", new=mock_boto3_adapter):\n with patch(\"cfripper.main.RuleProcessor\", new=mock_rule_processor):\n with patch(\"cfripper.main.Boto3Client\", new=mock_boto3_client):\n from cfripper.main import handler\n\n handler(event, None)\n\n mock_created_s3_adapter_object.download_template_to_dictionary.assert_called_once_with(\n \"https://asdfasdfasdf/bucket/key\"\n )\n mock_created_rule_processor_object.process_cf_template.assert_called_once_with(\n mock_created_s3_adapter_object.download_template_to_dictionary.return_value, ANY, ANY\n )\n\n @mock_s3\n def test_with_templates(self):\n dir_path = os.path.dirname(os.path.realpath(__file__))\n\n test_templates = glob.glob(f\"{dir_path}/test_templates/*.*\")\n for template in test_templates:\n with open(template) as cf_script:\n cf_template = convert_json_or_yaml_to_dict(cf_script.read())\n\n config = Config(\n project_name=template, service_name=template, stack_name=template, rules=DEFAULT_RULES.keys()\n )\n\n # Scan result\n result = Result()\n\n rules = [DEFAULT_RULES.get(rule)(config, result) for rule in config.rules]\n processor = RuleProcessor(*rules)\n processor.process_cf_template(cf_template, config, result)\n\n # Use this to print the stack if there's an error\n if len(result.exceptions):\n print(template)\n traceback.print_tb(result.exceptions[0].__traceback__)\n\n no_resource_templates = [\"vulgar_bad_syntax.yml\", \"rubbish.json\"]\n\n if template.split(\"/\")[-1] in no_resource_templates:\n assert len(result.exceptions) == 1\n else:\n assert len(result.exceptions) == 0\n\n def test_all_rules_valid(self):\n for r in DEFAULT_RULES.values():\n if r.RULE_MODE not in [\"BLOCKING\", \"MONITOR\", \"DEBUG\"]:\n assert False\n assert True\n\n def test_stack_whitelist_joins_all_whitelisted_matching_stack_names(self):\n mock_whitelist = {\n \"stackname\": [\n \"S3CrossAccountTrustRule\",\n ],\n \"notstackname\": [\n \"IAMRolesOverprivilegedRule\",\n ],\n \"stackname_withmorethings\": [\n \"CrossAccountTrustRule\",\n \"ManagedPolicyOnUserRule\",\n ]\n\n }\n\n config = Config(\n project_name=\"project_mock\",\n service_name=\"service_mock\",\n stack_name=\"stackname_withmorethings\",\n stack_whitelist=mock_whitelist,\n rules=DEFAULT_RULES.keys(),\n )\n\n whitelisted_rules = config.get_whitelisted_rules()\n\n assert set(whitelisted_rules) == {\n \"CrossAccountTrustRule\",\n \"ManagedPolicyOnUserRule\",\n \"S3CrossAccountTrustRule\",\n }\n","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":4967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"389947700","text":"import numpy as np\nimport cv2\nimport imutils\nimport datetime\ncamera = cv2.VideoCapture('data/gun4_2.mp4')\nperson_cascade = cv2.CascadeClassifier('haarcascade_upperbody.xml')\ngun_cascade = cv2.CascadeClassifier('cascade.xml')\n# initialize the first frame in the video stream\nfirstFrame = None\n\n# loop over the frames of the video\n\ngun_exist = False\n\nwhile True:\n (grabbed, frame) = camera.read()\n\n # if the frame could not be grabbed, then we have reached the end of the video\n if not grabbed:\n break\n\n # resize the frame, convert it to grayscale, and blur it\n frame = imutils.resize(frame, width=500)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (21, 21), 0)\n \n gun = gun_cascade.detectMultiScale(gray, 1.3, 5, minSize = (100, 100))\n rects = person_cascade.detectMultiScale(gray)\n if len(gun) > 0:\n gun_exist = True\n \n for (x,y,w,h) in gun:\n frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = frame[y:y+h, x:x+w] \n for (x, y, w, h) in rects:\n cv2.rectangle(frame, (x,y), (x+w,y+h),(0,255,0),2)\n \n # if the first frame is None, initialize it\n if firstFrame is None:\n firstFrame = gray\n continue\n\n # show the frame and record if the user presses a key\n cv2.imshow(\"Security Feed\", frame)\n key = cv2.waitKey(1) & 0xFF\n\nif gun_exist:\n print(\"guns detected\")\nelse:\n print(\"guns NOT detected\")\n\n# cleanup the camera and close any open windows\ncamera.release()\ncv2.destroyAllWindows()\n\n\n\n\n\n\n","sub_path":"haarclassifier/video_recognition.py","file_name":"video_recognition.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"317310236","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\ndata = pd.read_excel(r\"E:\\python_learning\\code\\project\\机器学习-线性回归\\files\\data.xlsx\")\n\nx = data[['大小']]\ny = data[['房价']]\n\nimport statsmodels.api as sm\n#添加常数项\nX = sm.add_constant(x)\n\n#最小二乘法\n\nmodel = sm.OLS(y,X)\nresult = model.fit()\n#系数\nresult.params\n#汇总结果\nresult.summary()\n\n#预测\ny_pr = result.fittedvalues\n\n#绘图\n\nimport matplotlib.pyplot as plt\n\nfig,ax = plt.subplots(figsize = (8,6))\n\nax.plot(x,y,'o',label = 'data')\nax.plot(x,y_pr,'r--',label = 'OLS')\nax.legend(loc = 'best')","sub_path":"python/机器学习/各种机器学习算法/statsmodels_实现一元线性回归模型.py","file_name":"statsmodels_实现一元线性回归模型.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"120406368","text":"import sys\nimport os\nimport subprocess\nfrom Bio.SeqIO.FastaIO import SimpleFastaParser\nimport operator\n\n\n# this runs rountines to identify and remove duplicate\n# contigs\n\nfrom AAFTF.utility import calcN50\nfrom AAFTF.utility import softwrap\nfrom AAFTF.utility import fastastats\nfrom AAFTF.utility import execute\nfrom AAFTF.utility import status\nfrom AAFTF.utility import printCMD\nfrom AAFTF.utility import SafeRemove\n\ndef run(parser,args):\n\n def generateFastas(fasta, pref, query, reference):\n qfile = os.path.join(args.workdir, pref +'query.fasta')\n rfile = os.path.join(args.workdir, pref +'reference.fasta')\n with open(qfile, 'w') as qout:\n with open(rfile, 'w') as rout:\n with open(fasta, 'rU') as infile:\n for Header,Seq in SimpleFastaParser(infile):\n if Header in query:\n qout.write('>{:}\\n{:}\\n'.format(Header, softwrap(Seq)))\n elif Header in reference:\n rout.write('>{:}\\n{:}\\n'.format(Header, softwrap(Seq)))\n return qfile, rfile\n \n def runMinimap2(query, reference, name):\n FNULL = open(os.devnull, 'w')\n garbage = False #assume this is a good contig\n for line in execute(['minimap2', '-t', str(args.cpus), '-x', 'asm5', '-N5', reference, query], '.'):\n qID, qLen, qStart, qEnd, strand, tID, tLen, tStart, tEnd, matches, alnLen, mapQ = line.split('\\t')[:12]\n pident = float(matches) / int(alnLen) * 100\n cov = float(alnLen) / int(qLen) * 100\n if args.debug:\n print('\\tquery={:} hit={:} pident={:.2f} coverage={:.2f}'.format(qID, tID, pident, cov))\n \n if pident > args.percent_id and cov > args.percent_cov:\n print(\"{:} duplicated: {:.0f}% identity over {:.0f}% of the contig. length={:}\".format(name, pident, cov, qLen))\n garbage = True\n break\n return garbage #false is good, true is repeat\n\n\n #start here -- functions nested so they can inherit the arguments\n custom_workdir = 1\n if not args.workdir:\n custom_workdir = 0\n args.workdir = 'aaftf-rmdup_'+str(os.getpid())\n if not os.path.exists(args.workdir):\n os.mkdir(args.workdir)\n \n if args.debug:\n status(args)\n status('Looping through assembly shortest --> longest searching for duplicated contigs using minimap2')\n numSeqs, assemblySize = fastastats(args.input)\n fasta_lengths = []\n with open(args.input, 'rU') as infile:\n for Header, Seq in SimpleFastaParser(infile):\n fasta_lengths.append(len(Seq))\n n50 = calcN50(fasta_lengths, num=0.75)\n status('Assembly is {:,} contigs; {:,} bp; and N75 is {:,} bp'.format(numSeqs, assemblySize, n50))\n \n #get list of tuples of sequences sorted by size (shortest --> longest)\n AllSeqs = {}\n with open(args.input, 'rU') as infile:\n for Header, Seq in SimpleFastaParser(infile):\n if not Header in AllSeqs:\n AllSeqs[Header] = len(Seq)\n sortSeqs = sorted(AllSeqs.items(), key=operator.itemgetter(1),reverse=False)\n if args.exhaustive:\n n50 = sortSeqs[-1][1]\n those2check = [x for x in sortSeqs if x[1] < n50]\n status('Will check {:,} contigs for duplication --> those that are < {:,} && > {:,}'.format(len(those2check), n50, args.minlen))\n #loop through sorted list of tuples\n ignore = []\n for i,x in enumerate(sortSeqs):\n sys.stdout.flush()\n if x[1] < args.minlen:\n ignore.append(x[0])\n continue\n if x[1] > n50:\n sys.stdout.flush()\n sys.stdout.write('\\n')\n break\n if args.debug:\n status('Working on {:} len={:} remove_tally={:}'.format(x[0], x[1], len(ignore)))\n else:\n text = \"\\rProgress: {:} of {:}; remove tally={:,}; current={:}; length={:} \".format(i, len(those2check), len(ignore), x[0], x[1])\n sys.stdout.write(text)\n #generate input files for minimap2\n theRest = [i[0] for i in sortSeqs[i+1:]]\n pid = str(os.getpid())\n qfile, rfile = generateFastas(args.input, pid, x[0], theRest)\n #run minimap2\n result = runMinimap2(qfile, rfile, x[0])\n if result:\n ignore.append(x[0])\n \n ignore = set(ignore)\n with open(args.out, 'w') as clean_out:\n with open(args.input, 'rU') as infile:\n for Header, Seq in SimpleFastaParser(infile):\n if not Header in ignore:\n clean_out.write('>{:}\\n{:}\\n'.format(Header, softwrap(Seq)))\n numSeqs, assemblySize = fastastats(args.out)\n status('Cleaned assembly is {:,} contigs and {:,} bp'.format(numSeqs, assemblySize))\n if '_' in args.out:\n nextOut = args.out.split('_')[0]+'.pilon.fasta'\n elif '.' in args.out:\n nextOut = args.out.split('.')[0]+'.pilon.fasta'\n else:\n nextOut = args.out+'.pilon.fasta'\n \n if not args.pipe:\n \tstatus('Your next command might be:\\n\\tAAFTF pilon -i {:} -l PE_R1.fastq.gz -r PE_R2.fastq.gz -o {:}\\n'.format(args.out, nextOut))\n\n if not args.debug and not custom_workdir:\n SafeRemove(args.workdir) \n","sub_path":"AAFTF/rmdup.py","file_name":"rmdup.py","file_ext":"py","file_size_in_byte":5280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"176001352","text":"# this code is modified from the pytorch example code: https://github.com/pytorch/examples/blob/master/imagenet/main.py\n# after the model is trained, you might use convert_model.py to remove the data parallel module to make the model as standalone weight.\n#\n# Bolei Zhou\n\nimport argparse\nimport os\nimport shutil\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport torchvision.models as models\n\nimport wideresnet\nimport pdb\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nmodel_names = sorted(name for name in models.__dict__\n if name.islower() and not name.startswith(\"__\")\n and callable(models.__dict__[name]))\nimport pandas as pd\n\nparser = argparse.ArgumentParser(description='PyTorch Places365 Training')\nparser.add_argument('data', metavar='DIR',\n help='path to dataset')\nparser.add_argument('--arch', '-a', metavar='ARCH', default='resnet18',\n help='model architecture: ' +\n ' | '.join(model_names) +\n ' (default: resnet18)')\nparser.add_argument('-j', '--workers', default=6, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\nparser.add_argument('--epochs', default=90, type=int, metavar='N',\n help='number of total epochs to run')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch-size', default=256, type=int,\n metavar='N', help='mini-batch size (default: 256)')\nparser.add_argument('--lr', '--learning-rate', default=0.1, type=float,\n metavar='LR', help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\nparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,\n metavar='W', help='weight decay (default: 1e-4)')\nparser.add_argument('--print-freq', '-p', default=10, type=int,\n metavar='N', help='print frequency (default: 10)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true',\n help='evaluate model on validation set')\nparser.add_argument('--pretrained', dest='pretrained', action='store_false',\n help='use pre-trained model')\nparser.add_argument('--num_classes',default=365, type=int, help='num of class in the input model')\nparser.add_argument('--num_outClasses',default=10, type=int, help='num of class in the output model')\nparser.add_argument('--dataset',default='places365',help='which dataset to train')\n\nbest_prec1 = 0\n\n\ndef main():\n global args, best_prec1\n args = parser.parse_args()\n #print (args)\n # create model\n print(\"=> creating model '{}'\".format(args.arch))\n if args.arch.lower().startswith('wideresnet'):\n # a customized resnet model with last feature map size as 14x14 for better class activation mapping\n model = wideresnet.resnet50(num_classes=args.num_classes)\n else:\n model = models.__dict__[args.arch](num_classes=args.num_classes)\n\n if args.arch.lower().startswith('alexnet') or args.arch.lower().startswith('vgg'):\n model.features = torch.nn.DataParallel(model.features)\n model\n else:\n model = torch.nn.DataParallel(model)\n\n model = model.cuda()\n device = torch.device('cuda')\n\n # update the fully connected layer\n nInF,nOutF = model.module.fc.in_features,args.num_outClasses # input size from original; 10 integer outputs\n model.module.fc = torch.nn.Linear(nInF,nOutF,bias=True)\n print (model)\n\n #print (model)\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume, map_location=device)\n args.start_epoch = checkpoint['epoch']\n best_prec1 = checkpoint['best_prec1']\n model.load_state_dict(checkpoint['state_dict'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n for param in model.module.parameters():\n param.requires_grad = False\n for param in model.module.fc.parameters():\n param.requires_grad = True\n\n cudnn.benchmark = True\n\n # Data loading code\n traindir = os.path.join(args.data, 'train')\n valdir = os.path.join(args.data, 'val')\n #scenicDF = pd.read_csv(args.data+'/newImagesWithJpg.tsv',sep='\\t')\n #scenicDF = scenicDF[['Images','Average']]\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n train_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(traindir, transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ])),\n batch_size=args.batch_size, shuffle=True,\n num_workers=args.workers, pin_memory=True)\n\n val_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(valdir, transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ])),\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.workers, pin_memory=True)\n\n # define loss function (criterion) and pptimizer\n criterion = nn.CrossEntropyLoss().to(device)\n\n optimizer = torch.optim.SGD(model.parameters(), args.lr,\n momentum=args.momentum,\n weight_decay=args.weight_decay)\n\n actualFull,predicFull=[],[]\n if args.evaluate:\n validate(val_loader, model, criterion, device)\n\n else:\n lossesT,lossesV=[],[]\n for epoch in range(args.start_epoch, args.epochs):\n adjust_learning_rate(optimizer, epoch)\n\n # train for one epoch\n losses,actual,predicted = train(train_loader, model, criterion, optimizer, epoch, device)\n lossesT.append(np.sqrt(float(losses.val)))\n actualFull.append(act for act in actual)\n predicFull.append(prd for prd in predicted)\n\n # evaluate on validation set\n prec1,losses,actual,predicted = validate(val_loader, model, criterion, device)\n lossesV.append(np.sqrt(float(losses.val)))\n actualFull.append(act for act in actual)\n predicFull.append(prd for prd in predicted)\n\n # remember best prec@1 and save checkpoint\n is_best = prec1 > best_prec1\n best_prec1 = max(prec1, best_prec1)\n save_checkpoint({\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': model.state_dict(),\n 'best_prec1': best_prec1,\n }, is_best, args.arch.lower())\n\n# plot stuff\n # loss vs epoch (only for training, not for validation-only processing)\n epochs = range(args.start_epoch,args.epochs)\n plt.plot(epochs,lossesT, 'b', label='Train')\n plt.plot(epochs,lossesV, 'g', label='Test')\n \n plt.xlabel('Epoch')\n plt.ylabel('Loss')\n plt.legend(loc='best') \n plt.savefig('errorVsEpoch.pdf')\n \n plt.clf() # clear\n # predicted vs actual scenery score\n plt.plot(actualFull,predicFull)\n plt.xlabel('Actual Scenery Score')\n plt.ylabel('Predicted Scenery Score')\n plt.savefig('predictedVsActual.pdf')\n\n plt.clf()\n # (predicted - actual) vs actual\n plt.plot(actualFull,(predicFull-actualFull))\n plt.xlabel('Actual Scenery Score')\n plt.ylabel('(Predicted-Actual) Scenery Score')\n plt.savefig('diffVsActual.pdf')\n\n myOutPerfDF = pd.DataFrame(list(zip(actualFull,predicFull)),columns=['Actual','Predicted'])\n myOutPerfDF.to_csv('output_actualPredicted.csv')\n\n myOutLossDF = pd.DataFrame(list(zip(epochs,lossesT,lossesV)),columns=['Epoch','LossTrain','LossVal'])\n myOutLossDF.to_csv('output_lossEpoch.csv')\n\ndef train(train_loader, model, criterion, optimizer, epoch, device):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n\n\n model = model.cuda()\n # switch to train mode\n model.train()\n\n end = time.time()\n\n actual,predicted = [],[]\n for i, (input, target) in enumerate(train_loader):\n # measure data loading time\n data_time.update(time.time() - end)\n input.to(device)\n target.to(device)\n\n target = target\n input_var = torch.autograd.Variable(input).cuda()\n target_var = torch.autograd.Variable(target).cuda()\n # compute output\n output = model(input_var)\n loss = criterion(output, target_var)\n\n # for it,score in enumerate(target):\n # if it==0:\n # print (score,output[it])\n # actual.append(score)\n # predicted.append(output[it])\n \n # measure accuracy and record loss\n myTop=5 if args.num_outClasses>3 else 3\n prec1, prec5 = accuracy(output.data, target, topk=(1, myTop))\n losses.update(loss.data, input.size(0))\n top1.update(prec1, input.size(0))\n top5.update(prec5, input.size(0))\n\n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % args.print_freq == 0:\n print('Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(\n epoch, i, len(train_loader), batch_time=batch_time,\n data_time=data_time, loss=losses, top1=top1, top5=top5))\n\n return losses, actual, predicted\n\ndef validate(val_loader, model, criterion, device):\n batch_time = AverageMeter()\n losses = AverageMeter()\n top1 = AverageMeter()\n top5 = AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n\n actual,predicted = [],[]\n\n with torch.no_grad():\n for i, (input, target) in enumerate(val_loader):\n input.to(device)\n target.to(device)\n\n input_var = torch.autograd.Variable(input).cuda()\n target_var = torch.autograd.Variable(target).cuda()\n \n # compute output\n output = model(input_var)\n loss = criterion(output, target_var)\n theseOuts = nn.functional.softmax(output,1).data.squeeze()\n \n # get actual and predicted for each point\n for img in range(0,target_var.size(0)):\n thisTar = target_var[img].data\n thisOut = theseOuts.argmax(dim=1)[img]\n actual.append(float(thisTar))\n predicted.append(float(thisOut))\n \n # measure accuracy and record loss\n myTop=5 if args.num_outClasses>3 else 3\n prec1, prec5 = accuracy(output.data, target, topk=(1, myTop))\n losses.update(loss.data, input.size(0))\n top1.update(prec1, input.size(0))\n top5.update(prec5, input.size(0))\n \n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n \n if i % args.print_freq == 0:\n print('Test: [{0}/{1}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\\t'\n 'Prec@5 {top5.val:.3f} ({top5.avg:.3f})'.format(\n i, len(val_loader), batch_time=batch_time, loss=losses,\n top1=top1, top5=top5))\n \n print(' * Prec@1 {top1.avg:.3f} Prec@5 {top5.avg:.3f}'\n .format(top1=top1, top5=top5))\n\n return top1.avg,losses,actual,predicted\n\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n torch.save(state, filename + '_latest.pth.tar')\n if is_best:\n shutil.copyfile(filename + '_latest.pth.tar', filename + '_best.pth.tar')\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef adjust_learning_rate(optimizer, epoch):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\n lr = args.lr * (0.1 ** (epoch // 30))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t().cuda()\n correct = pred.eq(target.view(1, -1).cuda().expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"train_placesCNNColab.py","file_name":"train_placesCNNColab.py","file_ext":"py","file_size_in_byte":14125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"141800889","text":"# Django settings for project project.\nimport pathlib\nfrom django.core.exceptions import ImproperlyConfigured\n\nfrom django_jinja.builtins import DEFAULT_EXTENSIONS # noqa\nfrom environ import Env, Path\nfrom jinja2 import Undefined\nfrom model_utils import Choices\nfrom oscar import OSCAR_MAIN_TEMPLATE_DIR, get_core_apps\nfrom oscar.defaults import *\n\nDEBUG = False\n\n\nroot = Path(__file__) - 3\nrepo_root = root - 1\n\nenv = Env(DEBUG=(bool, False),)\nEnv.read_env(repo_root('.env'))\n\nPROJECT_ROOT = root()\nDEBUG = env('DEBUG')\n\nADMINS = (\n ('Ben Beecher', 'Ben@Lightmatter.com'),\n ('Greg Hausheer', 'Greg@Lightmatter.com'),\n ('Jake Kent', 'Jake@Lightmatter.com'),\n ('Chris Weed', 'Chris@Lightmatter.com'),\n ('Kyle Vigorito', 'Kyle@Lightmatter.com'),\n)\n\nMANAGERS = ADMINS\n\n\nMACO_SITE_MANAGER_EMAILS = [email for email in env.list('SITE_MANAGER_EMAILS')]\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'UTC'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# URL prefix for static files.\n# Example: \"http://example.com/static/\", \"http://static.example.com/\"\nSTATIC_URL = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n str(root.path('static_source')),\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\nMIDDLEWARE = (\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'social_django.middleware.SocialAuthExceptionMiddleware',\n 'oscar.apps.basket.middleware.BasketMiddleware',\n 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',\n)\n\nROOT_URLCONF = 'Maco.Maco.urls'\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'Maco.Maco.wsgi.application'\n\nINSTALLED_APPS = (\n 'django.contrib.contenttypes',\n 'django.contrib.auth',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'django.contrib.flatpages',\n\n 'localflavor',\n 'django_extensions',\n 'model_utils',\n 'easy_thumbnails',\n 'django_jinja.contrib._easy_thumbnails',\n 'registration',\n 'import_export',\n 'social_django',\n 'django_jinja',\n 'webpack_loader',\n 'widget_tweaks',\n 'taggit',\n 'django_filters',\n 'hijack',\n 'compat',\n 'pinax.stripe',\n\n 'Maco.home',\n 'Maco.accounts',\n 'Maco.util',\n) + tuple(get_core_apps([\n # Add overwritten oscar apps inside here,\n 'Maco.basket',\n 'Maco.catalogue',\n 'Maco.checkout',\n 'Maco.customer',\n 'Maco.order',\n 'Maco.shipping',\n 'Maco.wishlists',\n # but make sure the dashboard remains last\n 'Maco.dashboard',\n]))\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n\nAUTHENTICATION_BACKENDS = (\n 'oscar.apps.customer.auth_backends.EmailBackend',\n 'django.contrib.auth.backends.ModelBackend',\n 'social_core.backends.facebook.FacebookOAuth2',\n)\n\nAUTH_USER_MODEL = 'accounts.User'\nLOGIN_REDIRECT_URL = '/'\nLOGIN_URL = '/accounts/login/'\nSECURE_BROWSER_XSS_FILTER = True\nSECURE_CONTENT_TYPE_NOSNIFF = True\n\nHIJACK_LOGIN_REDIRECT_URL = '/'\nHIJACK_LOGOUT_REDIRECT_URL = '/dashboard/users/'\n\ndef prefixed_cookie(name):\n return 'Maco_{}'.format(name)\n\nSESSION_COOKIE_NAME = prefixed_cookie('sessionid')\nCSRF_COOKIE_NAME = prefixed_cookie('csrftoken')\nLANGUAGE_COOKIE_NAME = prefixed_cookie('django_language')\n\nTEST_RUNNER = 'django.test.runner.DiscoverRunner'\n\nALLOWED_HOSTS = [\n 'localhost'\n '.herokuapp.com'\n]\n\nDEFAULT_FROM_EMAIL = 'support@getmaco.com'\nSERVER_EMAIL = 'support@getmaco.com'\n\nCONTEXT_PROCESSORS = [\n 'django.contrib.auth.context_processors.auth',\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.template.context_processors.i18n',\n 'django.template.context_processors.media',\n 'django.template.context_processors.static',\n 'django.template.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n 'Maco.home.context_processors.settings',\n 'social_django.context_processors.backends',\n 'social_django.context_processors.login_redirect',\n]\n\nOSCAR_PROCESSORS = ['oscar.apps.search.context_processors.search_form',\n 'oscar.apps.promotions.context_processors.promotions',\n 'oscar.apps.checkout.context_processors.checkout',\n 'oscar.apps.customer.notifications.context_processors.notifications',\n 'oscar.core.context_processors.metadata',\n ]\n\n\nTEMPLATES = [\n {\n \"BACKEND\": \"django_jinja.backend.Jinja2\",\n 'DIRS': [root('templates')],\n \"APP_DIRS\": False,\n \"OPTIONS\": {\n \"match_extension\": None,\n \"match_regex\": r\"^(?!admin/|dashboard/).*\", # this is additive to match_extension\n 'context_processors': CONTEXT_PROCESSORS,\n \"extensions\": DEFAULT_EXTENSIONS + [\n \"webpack_loader.contrib.jinja2ext.WebpackExtension\",\n ],\n 'environment': 'Maco.home.context_processors.jinja_environment',\n }\n },\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [root('templates'), OSCAR_MAIN_TEMPLATE_DIR],\n \"APP_DIRS\": True,\n 'OPTIONS': {\n 'builtins': ['django.contrib.staticfiles.templatetags.staticfiles'],\n 'context_processors': CONTEXT_PROCESSORS + OSCAR_PROCESSORS\n },\n },\n]\n\nJINJA2_ENVIRONMENT_OPTIONS = { 'undefined' : Undefined }\n\nWEBPACK_LOADER = {\n 'DEFAULT': {\n 'CACHE': not DEBUG,\n 'BUNDLE_DIR_NAME': 'bundles/', # must end with slash\n 'STATS_FILE': root('webpack-stats.json'),\n 'POLL_INTERVAL': 0.1,\n 'IGNORE': ['.+\\.hot-update.js', '.+\\.map']\n }\n}\n\n# registration\nACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value.\n\n# social\nSOCIAL_AUTH_PIPELINE = (\n 'social_core.pipeline.social_auth.social_details',\n 'social_core.pipeline.social_auth.social_uid',\n 'social_core.pipeline.social_auth.auth_allowed',\n 'social_core.pipeline.social_auth.social_user',\n 'social_core.pipeline.user.get_username',\n 'social_core.pipeline.user.create_user',\n 'social_core.pipeline.social_auth.associate_user',\n 'social_core.pipeline.social_auth.load_extra_data',\n 'social_core.pipeline.user.user_details',\n 'social_core.pipeline.social_auth.associate_by_email',\n 'accounts.pipeline.save_facebook_details'\n)\n\n\nSOCIAL_AUTH_ENABLED_BACKENDS = ('facebook')\nSOCIAL_AUTH_USER_MODEL = 'accounts.User'\nSOCIAL_AUTH_DEFAULT_USERNAME = \"new_social_auth_user\"\n\nOSCAR_SHOP_NAME = \"Maco\"\nOSCAR_SHOP_TAGLINE = \"Serving Those Who Serve Us\"\nOSCAR_DEFAULT_CURRENCY = \"USD\"\nOSCAR_ALLOW_ANON_CHECKOUT = True\n\noscar_dash_nav = OSCAR_DASHBOARD_NAVIGATION\nbrands_nav_item = {'label': 'Brands', 'url_name': 'dashboard:brand-list-view'}\nsuggestions_nav_item = {'label': 'Product Suggestions', 'url_name': 'dashboard:suggestion-list'}\nif len(oscar_dash_nav) > 1 and 'children' in oscar_dash_nav[1]:\n oscar_dash_nav[1]['children'].append(brands_nav_item)\n oscar_dash_nav[1]['children'].append(suggestions_nav_item)\nOSCAR_DASHBOARD_NAVIGATION = oscar_dash_nav\nOSCAR_DASHBOARD_NAVIGATION += [\n {\n 'label': 'Registry Fulfillment',\n 'url_name': 'dashboard:fulfillment-order-list',\n },\n {\n 'label': 'Registries',\n 'url_name': 'dashboard:registry-list',\n },\n {\n 'label': 'Sitewide Contributions',\n 'url_name': 'dashboard:contribution-list',\n },\n {\n 'label': 'Military users',\n 'url_name': 'dashboard:military-user-index',\n },\n]\n\nORDER_STATES = Choices(\n 'Pending',\n 'Shipped',\n 'Delivered',\n)\n\nOSCAR_ORDER_STATUS_PIPELINE = {\n ORDER_STATES.Pending: [ORDER_STATES.Shipped],\n ORDER_STATES.Shipped: [ORDER_STATES.Delivered],\n ORDER_STATES.Delivered: [],\n}\n\nPINAX_STRIPE_PUBLIC_KEY = STRIPE_PUBLIC_KEY = env('STRIPE_PUBLIC_KEY', default='')\nPINAX_STRIPE_SECRET_KEY = STRIPE_SECRET_KEY = env('STRIPE_SECRET_KEY', default='')\nPINAX_STRIPE_SEND_EMAIL_RECEIPTS = False\nSTRIPE_CURRENCY = \"USD\"\n\nGOOGLE_ANALYTICS_ID = env('GOOGLE_ANALYTICS_ID', default='')\n\n\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',\n },\n}\n\n\ntry:\n from model_mommy import generators # noqa\n MOMMY_CUSTOM_FIELDS_GEN = {\n 'localflavor.us.models.USZipCodeField': generators.gen_string,\n }\nexcept ImportError:\n pass\n\nVERIFICATION_FROM_EMAIL = env('VERIFICATION_FROM_EMAIL', default='support@getmaco.com')\nVERIFICATION_MANUAL_EMAIL = env('VERIFICATION_MANUAL_EMAIL', default='support@getmaco.com')\nVERIFICATION_SALT = env('VERIFICATION_SALT', default='verification')\nACCOUNT_VERIFICATION_DAYS = env('ACCOUNT_ACTIVATION_DAYS', default=30)\nFULFILLMENT_THRESHOLD = env('FULFILLMENT_THRESHOLD', default=65)\n","sub_path":"Maco/Maco/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":10925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"332883898","text":"import logging\nfrom dateutil.parser import parse\n\nfrom O365.address_book import Contact\nfrom O365.drive import Storage\nfrom O365.utils import ApiComponent\n\n\nlog = logging.getLogger(__name__)\n\n\nclass SharepointListItem(ApiComponent):\n \"\"\" A Sharepoint ListItem within a SharepointList \"\"\"\n\n _endpoints = {}\n\n def __init__(self, *, parent=None, con=None, **kwargs):\n assert parent or con, 'Need a parent or a connection'\n self.con = parent.con if parent else con\n\n # Choose the main_resource passed in kwargs over the parent main_resource\n main_resource = kwargs.pop('main_resource', None) or getattr(parent, 'main_resource', None) if parent else None\n\n super().__init__(protocol=parent.protocol if parent else kwargs.get('protocol'), main_resource=main_resource)\n\n cloud_data = kwargs.get(self._cloud_data_key, {})\n\n self.object_id = cloud_data.get('id')\n\n\nclass SharepointList(ApiComponent):\n \"\"\" A Sharepoint site List \"\"\"\n\n _endpoints = {\n 'get_items': '/items'\n }\n list_item_constructor = SharepointListItem\n\n def __init__(self, *, parent=None, con=None, **kwargs):\n assert parent or con, 'Need a parent or a connection'\n self.con = parent.con if parent else con\n\n cloud_data = kwargs.get(self._cloud_data_key, {})\n\n self.object_id = cloud_data.get('id')\n\n # Choose the main_resource passed in kwargs over the parent main_resource\n main_resource = kwargs.pop('main_resource', None) or getattr(parent, 'main_resource', None) if parent else None\n\n # prefix with the current known list\n resource_prefix = 'lists/{list_id}'.format(list_id=self.object_id)\n main_resource = '{}{}'.format(main_resource, resource_prefix)\n\n super().__init__(protocol=parent.protocol if parent else kwargs.get('protocol'), main_resource=main_resource)\n\n self.name = cloud_data.get(self._cc('name'), '')\n self.display_name = cloud_data.get(self._cc('displayName'), '')\n if not self.name:\n self.name = self.display_name\n self.description = cloud_data.get(self._cc('description'), '')\n self.web_url = cloud_data.get(self._cc('webUrl'))\n\n created = cloud_data.get(self._cc('createdDateTime'), None)\n modified = cloud_data.get(self._cc('lastModifiedDateTime'), None)\n local_tz = self.protocol.timezone\n self.created = parse(created).astimezone(local_tz) if created else None\n self.modified = parse(modified).astimezone(local_tz) if modified else None\n\n created_by = cloud_data.get(self._cc('createdBy'), {}).get('user', None)\n self.created_by = Contact(con=self.con, protocol=self.protocol,\n **{self._cloud_data_key: created_by}) if created_by else None\n modified_by = cloud_data.get(self._cc('lastModifiedBy'), {}).get('user', None)\n self.modified_by = Contact(con=self.con, protocol=self.protocol,\n **{self._cloud_data_key: modified_by}) if modified_by else None\n\n # list info\n lst_info = cloud_data.get('list', {})\n self.content_types_enabled = lst_info.get(self._cc('contentTypesEnabled'), False)\n self.hidden = lst_info.get(self._cc('hidden'), False)\n self.template = lst_info.get(self._cc('template'), False)\n\n def get_items(self):\n \"\"\" Returns a collection of Sharepoint Items \"\"\"\n url = self.build_url(self._endpoints.get('get_items'))\n\n response = self.con.get(url)\n\n if not response:\n return []\n\n data = response.json()\n\n return [self.list_item_constructor(parent=self, **{self._cloud_data_key: item})\n for item in data.get('value', [])]\n\n\nclass Site(ApiComponent):\n \"\"\" A Sharepoint Site \"\"\"\n\n _endpoints = {\n 'get_subsites': '/sites',\n 'get_lists': '/lists'\n }\n list_constructor = SharepointList\n\n def __init__(self, *, parent=None, con=None, **kwargs):\n assert parent or con, 'Need a parent or a connection'\n self.con = parent.con if parent else con\n\n cloud_data = kwargs.get(self._cloud_data_key, {})\n\n self.object_id = cloud_data.get('id')\n\n # Choose the main_resource passed in kwargs over the parent main_resource\n main_resource = kwargs.pop('main_resource', None) or getattr(parent, 'main_resource', None) if parent else None\n\n # prefix with the current known site\n resource_prefix = 'sites/{site_id}'.format(site_id=self.object_id)\n main_resource = '{}{}'.format(main_resource, resource_prefix)\n\n super().__init__(protocol=parent.protocol if parent else kwargs.get('protocol'), main_resource=main_resource)\n\n self.root = 'root' in cloud_data # True or False\n self.name = cloud_data.get(self._cc('name'), kwargs.get('name', '')) # Fallback to manual site\n self.display_name = cloud_data.get(self._cc('displayName'), '')\n if not self.name:\n self.name = self.display_name\n self.description = cloud_data.get(self._cc('description'), '')\n self.web_url = cloud_data.get(self._cc('webUrl'))\n\n created = cloud_data.get(self._cc('createdDateTime'), None)\n modified = cloud_data.get(self._cc('lastModifiedDateTime'), None)\n local_tz = self.protocol.timezone\n self.created = parse(created).astimezone(local_tz) if created else None\n self.modified = parse(modified).astimezone(local_tz) if modified else None\n\n # site storage to access Drives and DriveItems\n self.site_storage = Storage(parent=self, main_resource='/sites/{id}'.format(id=self.object_id))\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n return 'Site: {}'.format(self.name)\n\n def get_default_document_library(self, request_drive=False):\n \"\"\"\n Returns the default document library of this site (a Drive instance)\n :param request_drive: True will make an api call to retrieve the drive data\n \"\"\"\n return self.site_storage.get_default_drive(request_drive=request_drive)\n\n def get_document_library(self, drive_id):\n \"\"\"\n Returns a Document Library (a Drive instance)\n :param drive_id: the drive_id to be retrieved.\n \"\"\"\n return self.site_storage.get_drive(drive_id=drive_id)\n\n def list_document_libraries(self, limit=None, *, query=None, order_by=None, batch=None):\n \"\"\" Returns a collection of document libraries for this site (a collection of Drive instances) \"\"\"\n return self.site_storage.get_drives(limit=limit, query=query, order_by=order_by, batch=batch)\n\n def get_subsites(self):\n \"\"\" Returns a list of subsites defined for this site \"\"\"\n url = self.build_url(self._endpoints.get('get_subsites').format(id=self.object_id))\n\n response = self.con.get(url)\n if not response:\n return []\n\n data = response.json()\n\n # Everything received from the cloud must be passed with self._cloud_data_key\n return [self.__class__(parent=self, **{self._cloud_data_key: site}) for site in data.get('value', [])]\n\n def get_lists(self):\n \"\"\" Returns a collection of lists within this site \"\"\"\n url = self.build_url(self._endpoints.get('get_lists'))\n\n response = self.con.get(url)\n if not response:\n return []\n\n data = response.json()\n\n return [self.list_constructor(parent=self, **{self._cloud_data_key: lst}) for lst in data.get('value', [])]\n\n\nclass Sharepoint(ApiComponent):\n \"\"\" A Sharepoint parent class to group functionality \"\"\"\n\n _endpoints = {\n 'get_site': '/sites/{id}',\n 'search': '/sites?search={keyword}'\n }\n site_constructor = Site\n\n def __init__(self, *, parent=None, con=None, **kwargs):\n assert parent or con, 'Need a parent or a connection'\n self.con = parent.con if parent else con\n\n # Choose the main_resource passed in kwargs over the host_name\n main_resource = kwargs.pop('main_resource', '') # defaults to blank resource\n super().__init__(protocol=parent.protocol if parent else kwargs.get('protocol'), main_resource=main_resource)\n\n def __str__(self):\n return self.__repr__()\n\n def __repr__(self):\n return 'Sharepoint'\n\n def search_site(self, keyword):\n \"\"\"\n Search a sharepoint host for sites with the provided keyword\n :param keyword: a keyword to search sites\n \"\"\"\n if not keyword:\n raise ValueError('Must provide a valid keyword')\n\n url = self.build_url(self._endpoints.get('search').format(keyword=keyword))\n\n response = self.con.get(url)\n if not response:\n return []\n\n data = response.json()\n\n # Everything received from the cloud must be passed with self._cloud_data_key\n return [self.site_constructor(parent=self, **{self._cloud_data_key: site}) for site in data.get('value', [])]\n\n def get_root_site(self):\n \"\"\" Returns the root site \"\"\"\n return self.get_site('root')\n\n def get_site(self, *args):\n \"\"\" Returns a sharepoint site\n :param args: It accepts multiple ways of retrieving a site:\n - get_site(host_name): the host_name: host_name ej. 'contoso.sharepoint.com' or 'root'\n - get_site(site_id): the site_id: a comma separated string of (host_name, site_collection_id, site_id)\n - get_site(host_name, path_to_site): host_name ej. 'contoso.sharepoint.com', path_to_site: a url path (with a leading slash)\n - get_site(host_name, site_collection_id, site_id): host_name ej. 'contoso.sharepoint.com'\n \"\"\"\n num_args = len(args)\n if num_args == 1:\n site = args[0]\n elif num_args == 2:\n host_name, path_to_site = args\n path_to_site = '/' + path_to_site if not path_to_site.startswith('/') else path_to_site\n site = '{}:{}:'.format(host_name, path_to_site)\n elif num_args == 3:\n site = ','.join(args)\n else:\n raise ValueError('Incorrect number of arguments')\n\n url = self.build_url(self._endpoints.get('get_site').format(id=site))\n\n response = self.con.get(url)\n if not response:\n return None\n\n data = response.json()\n\n return self.site_constructor(parent=self, **{self._cloud_data_key: data})\n","sub_path":"O365/sharepoint.py","file_name":"sharepoint.py","file_ext":"py","file_size_in_byte":10453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"632450101","text":"#!/usr/bin/env python\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# \n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials\n# provided with the distribution.\n# \n# * Neither the name of Kirk Strauser nor the names of other\n# contributors may be used to endorse or promote products\n# derived from this software without specific prior written\n# permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n# Based on code by Kirk Strauser \n# Rev: 1139; Date: 2008-04-16\n#\n# Modified by mmckerns@caltech.edu\n# to mimic 'map' interface, and allow server configuration\n\n\"\"\"\nVery basic parallel processing support\n\nImplements a work-alike of the builtin map() function that distributes\nwork across many processes. As it uses Parallel Python to do the\nactual multi-processing, code using this must conform to the usual PP\nrestrictions (arguments must be serializable, etc.)\n\"\"\"\n\nimport time\nimport __builtin__\n\nfrom pp import pp\n\n__STATE = {'server': None}\n\ndef ppmap(processes, function, sequence, *sequences):\n \"\"\"Split the work of 'function' across the given number of\n processes. Set 'processes' to None to let Parallel Python\n autodetect the number of children to use.\n\n Although the calling semantics should be identical to\n __builtin__.map (even using __builtin__.map to process\n arguments), it differs in that it returns a generator instead of a\n list. This enables lazy evaluation of the results so that other\n work can be done while the subprocesses are still running.\n\n >>> def rangetotal(n): return n, sum(range(n))\n >>> list(map(rangetotal, range(1, 6)))\n [(1, 0), (2, 1), (3, 3), (4, 6), (5, 10)]\n >>> list(ppmap(1, rangetotal, range(1, 6)))\n [(1, 0), (2, 1), (3, 3), (4, 6), (5, 10)]\n \"\"\"\n\n ppservers = (\"*\",) # autodetect\n #from _ppserver_config import ppservers # read from a config file\n\n # Create a new server if one isn't already initialized\n if not __STATE['server']:\n __STATE['server'] = pp.Server(ppservers=ppservers)\n \n #class dill_wrapper(object):\n # \"\"\"handle non-picklable functions by wrapping with dill\"\"\"\n # def __init__(self, function):\n # from dill import dumps\n # self.pickled_function = dumps(function)\n # def __call__(self, *args):\n # from dill import loads #XXX: server now requires dill\n # f = loads(self.pickled_function) \n # return f(*args)\n\n# def dill_wrapper(function):\n# \"\"\"handle non-picklable functions by wrapping with dill\"\"\"\n# from dill import dumps\n# pickled_function = dumps(function)\n# def unwrap(*args):\n# from dill import loads #XXX: server now requires dill\n# f = loads(pickled_function) \n# return f(*args)\n# return unwrap\n\n def submit(*args): #XXX: needs **kwds to allow \"depfuncs, modules, ...?\n \"\"\"Send a job to the server\"\"\"\n #print globals()['ncalls'] #FIXME: ncalls not in globals()\n #XXX: options for submit...\n #XXX: func -- function to be executed\n #XXX: depfuncs -- functions called from 'func'\n #XXX: modules -- modules to import\n #XXX: callback -- callback function to be called after 'func' completes\n #XXX: callbackargs -- additional args for callback(result, *args)\n #XXX: group -- allows naming of 'job group' to use in wait(group)\n #XXX: globals -- dictionary from which everything imports\n# from mystic.tools import wrap_function, wrap_bounds\n# return __STATE['server'].submit(function, args, \\\n# depfuncs=(wrap_function,wrap_bounds), \\\n## modules=(\"mystic\",\"numpy\"), \\\n# globals=globals())\n # p_function = dill_wrapper(function)\n # return __STATE['server'].submit(p_function, args, globals=globals())\n #print __STATE['server'].get_ncpus(), \"local workers\" #XXX: debug\n return __STATE['server'].submit(function, args, globals=globals())\n\n # Merge all the passed-in argument lists together. This is done\n # that way because as with the map() function, at least one list\n # is required but the rest are optional.\n a = [sequence]\n a.extend(sequences)\n\n # Set the requested level of multi-processing\n #__STATE['server'].set_ncpus(processes or 'autodetect') # never processes=0\n if processes == None:\n __STATE['server'].set_ncpus('autodetect')\n else:\n __STATE['server'].set_ncpus(processes) # allow processes=0\n #print \"running with\", __STATE['server'].get_ncpus(), \"local workers\" #XXX: debug\n\n # First, submit all the jobs. Then harvest the results as they\n # come available.\n return (subproc() for subproc in __builtin__.map(submit, *a))\n\n\ndef pp_map(function, sequence, **kwds):\n '''extend python's parallel map function to parallel python\n\nInputs:\n function -- target function\n sequence -- sequence to process in parallel\n\nAdditional Inputs:\n ncpus -- number of 'local' processors to use [defaut = 'autodetect']\n servers -- available distributed parallel python servers [default = ()]\n '''\n processes = None\n servers = ()\n if kwds.has_key('ncpus'): processes = kwds['ncpus']\n if kwds.has_key('servers'): servers = kwds['servers']\n\n # Create a new server if one isn't already initialized\n if not __STATE['server']:\n __STATE['server'] = job_server = pp.Server(ppservers=servers)\n #print \"Known servers: [('local',)] %s\" % (job_server.ppservers)\n #print \"Starting pp with\", job_server.get_ncpus(), \"local workers\"\n return list(ppmap(processes,function,sequence))\n\n\nif __name__ == '__main__':\n # code moved to \"pathos/examples/pp_map.py\n pass\n\n\n# EOF\n","sub_path":"python/pathos/pp_map.py","file_name":"pp_map.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"306890797","text":"# -*- coding: utf-8 -*-\n\"\"\"Write stream of data to sqlite database.\n Read from sqlite database into pandas DataFrame. \n\"\"\"\n\nimport functools\nimport sqlite3\nimport pandas as pd\n\n# path only relative to 'kep'\n# DB_FILE = 'kep//database//kep.sqlite'\nfrom kep.paths import DB_FILE \n\ndef _create_table(file = DB_FILE):\n conn = sqlite3.connect(file)\n c = conn.cursor()\n c.execute('''CREATE TABLE if not exists \"data\" \n (\"freq\" CHAR NOT NULL, \n \"label\" VARCHAR NOT NULL, \n \"year\" INTEGER NOT NULL, \n \"qtr\" INTEGER, \n \"month\" INTEGER, \n \"val\" FLOAT NOT NULL , \n PRIMARY KEY (\"freq\", \"label\", \"year\", \"qtr\", \"month\", \"val\"))''')\n conn.commit()\n conn.close()\n\ndef wipe_db_tables(file = DB_FILE):\n conn = sqlite3.connect(file)\n c = conn.cursor()\n c.executescript(\"\"\" DELETE FROM \"main\".\"data\" \"\"\")\n conn.commit()\n conn.close()\n\ndef stream_to_database(stream, db_file = DB_FILE):\n \"\"\"\n Incoming *stream* of tuples (freq, year, qtr, month, label, val) written to db_file\n \"\"\"\n conn = sqlite3.connect(db_file)\n conn.executemany(\"INSERT OR REPLACE INTO data VALUES (?, ?, ?, ?, ?, ?)\", stream)\n conn.commit() \n conn.close() \n\n# Read sqlite query results into pandas DataFrame\ndef get_freq(con, lit):\n if lit in ('q','m','a'): # fixed unexpected behavior e.g. \"qm\" or \"ma\" returned True\n return pd.read_sql_query(\"SELECT * from data where freq =?\", con,params=(lit,)) # assembling query with Python's string operations is insecure; DB-API parameter substitution used instead\n else:\n raise ValueError\n\ndef get_annual(con):\n return get_freq(con, \"a\")\n\ndef get_quarterly(con):\n return get_freq(con, \"q\")\n\ndef get_monthly(con):\n return get_freq(con, \"m\")\n \ndef select_unique_labels(con):\n return pd.read_sql_query(\"SELECT DISTINCT label from data\", con) \n\n\n#@functools.lru_cache()\ndef read_dfs(db_file = DB_FILE):\n \"\"\"Get all of DB_FILE as annual, quarterly and monthly dataframes.\"\"\"\n con = sqlite3.connect(db_file)\n dfa = get_annual(con)\n dfq = get_quarterly(con)\n dfm = get_monthly(con)\n con.close()\n return dfa, dfq, dfm\n\ndef get_unique_labels(db_file = DB_FILE):\n con = sqlite3.connect(db_file)\n df = select_unique_labels(con)\n con.close()\n return sorted(df['label'].tolist()) \n \ndef get_period_value(df, label, year, quarter=None, month=None):\n indexer = (df.label == label) & (df.year == year)\n if quarter is not None:\n indexer &= (df.qtr == quarter)\n if month is not None:\n indexer &= (df.month == month)\n filtered = df[indexer]\n assert len(filtered.index) == 1\n return filtered.iloc[0].val\n\n#------------------------------------------------\n# code from test/pytest/test_setup.py \n\nfrom kep.importer.csv2db import import_csv\nfrom kep.paths import CURRENT_MONTH_DATA_FOLDER\n\ndef update_database_to_current_month_folder():\n import_csv(CURRENT_MONTH_DATA_FOLDER)\n\n#------------------------------------------------\n \n \nif __name__ == \"__main__\":\n #test_database()\n pass\n #print (get_unique_labels())\n","sub_path":"kep/database/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"207752042","text":"#!/usr/bin/python3\n'''\npanosend.py -- written by Claude Pageau https://github.com/pageauc/panopi\n\nDescription:\nThis program will take a picamera image and\nsend it to the panohub.py RPI computer via zmq settings.\nIt will then wait for a return message containing the time for the next\nimage to be taken. panohub.py will then\nattempt to stitch images into a panorama image if properly overlapped.\nSettings for panosend.py are set in the panhub.yaml file on panohub RPI.\nThe settings are transferred to each panosend.py RPI and saved as panosend.yaml\nThis is just a copy so don't try to edit this file since it will be overwritten.\n\nPress Ctrl-C To End program\n'''\n\nfrom __future__ import print_function\nimport os\nPROG_VER = '0.66'\nPROG_NAME = os.path.basename(__file__)\nprint('%s ver %s Loading ...' % (PROG_NAME, PROG_VER))\n\nimport sys\nimport time\nimport datetime\nimport socket\nimport numpy as np\n\ntry:\n import yaml\nexcept ImportError:\n print('''panosend.py\n You need to install yaml python library per\n\n sudo pip install pyYAML\n sudo pip3 install pyYAML\n\n ''')\n sys.exit(1)\n\ntry:\n import picamera\nexcept ImportError:\n print('''panosend.py: You need to install picamera library per\n\n sudo apt install -y python-picamera\n sudo apt install -y python3-picamera\n\n ''')\n sys.exit(1)\n\ntry:\n import cv2\nexcept ImportError:\n print('''panosend.py: You need to install opencv library per\n\n sudo apt install -y python-opencv\n sudo apt install -y python3-opencv\n\n Note you may need stretch or buster for python3-opencv install\n ''')\n sys.exit(1)\n\ntry:\n import imagezmq\nexcept ImportError:\n print('''panosend.py: You need to install imagezmq library per\n\n sudo pip3 install imagezmq\n\n ''')\n sys.exit(1)\n\n#---------------------------------------------------------------\ndef read_yaml_file(yaml_file_path, yaml_section_name):\n ''' Read configuration variables from a yaml file\n per the specified yaml file path and yaml file section name.\n Only the specified yaml file section variables will be read,\n all other yaml sections will be ignored.\n '''\n if os.path.isfile(yaml_file_path):\n print(\"panosend.py: Read %s variables from yaml file %s\" %\n (yaml_section_name, yaml_file_path))\n with open(yaml_file_path) as conf:\n config = yaml.safe_load(conf)\n try:\n for var in config[yaml_section_name]:\n globals()[str(var)] = config[yaml_section_name][var]\n print(\"panosend.py: %s = %s\" %(str(var), config[yaml_section_name][var]))\n except KeyError:\n print('panosend.py: ERROR Could Not find yaml_section_name: %s' % yaml_section_name)\n print(' Please verify yaml section name in file %s' % yaml_file_path)\n sys.exit(1)\n else:\n print('panosend.py: ERROR File Not Found %s' % yaml_file_path)\n print(' Cannot Read configuration variables.')\n sys.exit(1)\n\n#---------------------------------------------------------------\ndef timestamp_to_string(my_time):\n ''' Convert text string to datatime format\n '''\n return datetime.datetime.fromtimestamp(my_time).strftime('%Y/%m/%d %H:%M:%S')\n\n#---------------------------------------------------------------\ndef take_stitch_image():\n ''' Take timelapse images and send over network to pano-hub.py via zmq.\n On receipt of image pano-hub.py will send reply with next timelapse timestamp\n This will ensure all panosend.py cameras take images at the same time.\n '''\n RPI_NAME = socket.gethostname()\n print('panosend.py: %s Initializing PiCamera' % RPI_NAME)\n ZMQ_PROTOCOL = 'tcp://'\n ZMQ_HUB = ZMQ_PROTOCOL + ZMQ_PANOHUB_IP + \":\" + str(ZMQ_PANOHUB_PORT)\n print('panosend.py: Connect %s to %s' % (RPI_NAME, ZMQ_HUB))\n sender = imagezmq.ImageSender(connect_to=ZMQ_HUB)\n\n # fix rounding problems with picamera resolution\n fwidth = (CAM_WIDTH + 31) // 32 * 32\n fheight = (CAM_HEIGHT + 15) // 16 * 16\n print('panosend.py: Adjusted camera resolution roundup from %ix%i to %ix%i' %\n (CAM_WIDTH, CAM_HEIGHT, fwidth, fheight))\n\n with picamera.PiCamera() as camera:\n camera.resolution = (fwidth, fheight)\n camera.hflip = CAM_HFLIP\n camera.vflip = CAM_VFLIP\n image_buf = np.empty((fheight, fwidth, 3), dtype=np.uint8)\n time.sleep(2) # Allow Camera to Warm Up\n next_timelapse = datetime.datetime.now()\n while True:\n if datetime.datetime.now() > next_timelapse:\n camera.capture(image_buf, 'bgr')\n ret_code, jpg_buffer = cv2.imencode(\".jpg\",\n image_buf,\n [int(cv2.IMWRITE_JPEG_QUALITY),\n CAM_JPEG_QUALITY])\n print('panosend.py: %s ZMQ Transmit Image to Hub at %s' %\n (ZMQ_HUB, datetime.datetime.now()))\n\n hub_reply = sender.send_jpg(RPI_NAME, jpg_buffer)\n\n # Convert reply_from zmq hub reply message to time format\n next_timelapse = datetime.datetime.strptime(hub_reply.decode('utf-8'),\n '%Y/%m/%d %H:%M:%S')\n print('panosend.py: Waiting for next_timelapse at %s' %\n hub_reply.decode('utf-8'))\n time.sleep(0.01) # slow looping a bit to reduce cpu usage\n\n#---------------------------------------------------------------\nif __name__ == '__main__':\n print('-----------------------------------------------------------')\n print('%s ver %s written by Claude Pageau' % (PROG_NAME, PROG_VER))\n print('-----------------------------------------------------------')\n\n YAML_FILEPATH = './panosend.yaml'\n YAML_SECTION_NAME = 'panosend_settings'\n\n # Read variable settings from yaml file.\n print('panosend.py: Import Settings from %s %s' %\n (YAML_FILEPATH, YAML_SECTION_NAME))\n read_yaml_file(YAML_FILEPATH, YAML_SECTION_NAME)\n try:\n take_stitch_image()\n except KeyboardInterrupt:\n print('')\n print('panosend.py: User Exited with ctrl-c')\n print(\"panosend.py: ver %s Bye ...\" % PROG_VER)\n\n","sub_path":"panosend/panosend.py","file_name":"panosend.py","file_ext":"py","file_size_in_byte":6314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"607587390","text":"from .models import ReparationVelos #Event (dans des anciens test pour le calendrier)\n\n# from bootstrap_datepicker_plus import DatePickerInput, TimePickerInput --- A modifier / supprimer\nfrom django import forms\n\n\n\nclass Test(forms.ModelForm):\n class Meta:\n model = ReparationVelos\n fields = ['rep_date_heure']\n widgets = {\n 'rep_date_heure': forms.DateInput(attrs={'type': 'date', 'class': 'datepicker'})\n }\n\n\nrep_date_heure = forms.DateField()\n\"\"\"\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self.fields['rep_date_heure'].widget = AdminDateWidget()\n\"\"\"\n\n\n\"\"\"\nclass EventForm(forms.ModelForm): \n class Meta:\n model = Event\n fields = ['name', 'start_date', 'end_date', 'start_time', 'end_time']\n widgets = {\n 'start_date':DatePickerInput().start_of('event days'),\n 'end_date':DatePickerInput().end_of('event days'),\n 'start_time':TimePickerInput().start_of('party time'),\n 'end_time':TimePickerInput().end_of('party time'),\n }\n\"\"\" # A modifier / supprimer","sub_path":"reparation/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602871628","text":"\nfrom random import randint\n\ndef test(chose,solution):\n\n\tif chose>solution:\n\t\treturn \"Too high.\"\n\telse :\n\t\treturn \"Too low\"\n\n\n\ncount=0\nnumber=randint(1,100)\n\nwhile True:\n\n\tchose=int(input(\"Enter a number between 1 and 100: \"))\n\t\n\tcount+=1\n\n\tif chose==number:\n\t\t\n\t\tprint (\"Congratulations ! you got it in %s guesses.\"%(count))\n\t\tbreak\n\n\telse: \n\t\tprint (test(chose,number)+\" Try Again \")\n","sub_path":"guessing_game.py","file_name":"guessing_game.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"602930022","text":"from Customer import Customer\nimport random\n\nclass Bank(Customer):\n def __init__(self,customers,numberOfCustomers, bankName):\n self.__customers = customers\n self.__numberOfCustomer = int(numberOfCustomers)\n self.__bankName = bankName\n Customer.__init__(self,'0','0','0','0')\n\n def addCustomer(self, f, l):\n while True:\n username = '17650'+str(random.randint(1000,9999))\n count = 0\n for i in self.__customers:\n if username == i[0]:\n continue\n else :\n count += 1\n if count == len(self.__customers):\n break\n self.__customers.append([username,[f,l],[]])\n return 'Your username is {0}.'.format(username)\n\n def getNumOfCustomers(self):\n return self.__numberOfCustomer\n\n def getCustomers(self,index):\n return self.__customers[index][0]\n\n","sub_path":"Data Project/Jude_Assignment/Banking_Problem_Comp/Bank.py","file_name":"Bank.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"483480503","text":"class Solution:\n def findOrder(self, numCourses, prerequisites):\n\n # rename variables\n N = numCourses\n edges = prerequisites\n\n # build graph\n graph = [[] for i in range(N)]\n in_degree = [0] * N\n for n1, n2 in edges:\n in_degree[n1] += 1\n graph[n2].append(n1)\n\n # initialize roots\n roots = [i for i in range(N) if in_degree[i] == 0]\n ans = []\n\n # remove roots and find new roots\n while roots:\n roots_ = []\n for r in roots:\n ans.append(r)\n for nxt in graph[r]:\n in_degree[nxt] -= 1\n if in_degree[nxt] == 0:\n roots_.append(nxt)\n roots = roots_\n\n # validate result\n return ans if len(ans) == N else []","sub_path":"lc/210_course_schedule_II.py","file_name":"210_course_schedule_II.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"542366405","text":"import os\nimport time\nimport pandas as pd\nimport torch\nimport torchvision\nfrom torchvision.transforms import functional as F\nfrom Modules.DataSet import DataSet\nfrom Modules.FileManager import FileManager\nfrom Modules.Utils import AverageMeter, Logger\nfrom Modules.MLutils import collate_fn, Compose, ToTensor, RandomHorizontalFlip\n\n\nclass Trainer:\n \"\"\"class to coordinate model training and evaluation\"\"\"\n\n def __init__(self, num_epochs, compare_annotations=True):\n \"\"\"initialize trainer\n\n Args:\n num_epochs (int): number of epochs to train\n compare_annotations: If True, evaluate the model on the test set after each epoch. This does not affect the\n end result of training, but does produce more data about model performance at each epoch. Setting to\n True also increases total runtime significantly\n \"\"\"\n self.compare_annotations = compare_annotations\n self.fm = FileManager()\n self.num_epochs = num_epochs\n self._initiate_loaders()\n self._initiate_model()\n self._initiate_loggers()\n\n def train(self):\n \"\"\"train the model for the specified number of epochs.\"\"\"\n for epoch in range(self.num_epochs):\n loss = self._train_epoch(epoch)\n self.scheduler.step(loss)\n if self.compare_annotations:\n self._evaluate_epoch(epoch)\n self._save_model()\n\n def _initiate_loaders(self):\n \"\"\"initiate train and test datasets and dataloaders.\"\"\"\n self.train_dataset = DataSet(self._get_transform(train=True), 'train')\n self.test_dataset = DataSet(self._get_transform(train=False), 'test')\n self.train_loader = torch.utils.data.DataLoader(\n self.train_dataset, batch_size=5, shuffle=True, num_workers=8, pin_memory=True, collate_fn=collate_fn)\n self.test_loader = torch.utils.data.DataLoader(\n self.test_dataset, batch_size=5, shuffle=False, num_workers=8, pin_memory=True, collate_fn=collate_fn)\n\n def _initiate_model(self):\n \"\"\"initiate the model, optimizer, and scheduler.\"\"\"\n self.model = torchvision.models.detection.fasterrcnn_resnet50_fpn(num_classes=3, box_detections_per_img=5)\n self.parameters = self.model.parameters()\n self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n torch.cuda.empty_cache()\n self.model.to(self.device)\n self.optimizer = torch.optim.SGD(self.parameters, lr=0.005, momentum=0.9, weight_decay=0.0005)\n self.scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(self.optimizer, 'min', patience=5)\n\n def _initiate_loggers(self):\n \"\"\"initiate loggers to track training progress.\"\"\"\n self.train_logger = Logger(self.fm.local_paths['train_log'],\n ['epoch', 'loss_total', 'loss_classifier', 'loss_box_reg', 'loss_objectness',\n 'loss_rpn_box_reg', 'lr'])\n\n self.train_batch_logger = Logger(self.fm.local_paths['batch_log'],\n ['epoch', 'batch', 'iter', 'loss_total', 'lr'])\n\n self.val_logger = Logger(self.fm.local_paths['val_log'], ['epoch'])\n\n def _get_transform(self, train):\n \"\"\"get a composition of the appropriate data transformations.\n\n Args:\n train (bool): True if training the model, False if evaluating/testing the model\n\n Returns:\n composition of required transforms\n \"\"\"\n transforms = [ToTensor()]\n if train:\n transforms.append(RandomHorizontalFlip(0.5))\n return Compose(transforms)\n\n def _train_epoch(self, epoch):\n \"\"\"train the model for one epoch.\n\n Args:\n epoch (int): epoch number, greater than or equal to 0\n\n Returns:\n float: averaged epoch loss\n \"\"\"\n print('train at epoch {}'.format(epoch))\n self.model.train()\n\n batch_time = AverageMeter()\n data_time = AverageMeter()\n loss_types = ['loss_total', 'loss_classifier', 'loss_box_reg', 'loss_objectness', 'loss_rpn_box_reg']\n loss_meters = {loss_type: AverageMeter() for loss_type in loss_types}\n end_time = time.time()\n\n for i, (images, targets) in enumerate(self.train_loader):\n data_time.update(time.time() - end_time)\n images = list(image.to(self.device) for image in images)\n targets = [{k: v.to(self.device) for k, v in t.items()} for t in targets]\n loss_dict = self.model(images, targets)\n losses = sum(loss for loss in loss_dict.values())\n loss_meters['loss_total'].update(losses.item(), len(images))\n for key, val in loss_dict.items():\n loss_meters[key].update(val.item(), len(images))\n self.optimizer.zero_grad()\n losses.backward()\n self.optimizer.step()\n\n batch_time.update(time.time() - end_time)\n end_time = time.time()\n\n self.train_batch_logger.log({\n 'epoch': epoch,\n 'batch': i + 1,\n 'iter': (epoch - 1) * len(self.train_loader) + (i + 1),\n 'loss_total': loss_meters['loss_total'].val,\n 'lr': self.optimizer.param_groups[0]['lr']\n })\n\n print('Epoch: [{0}][{1}/{2}]\\t'\n 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n .format(\n epoch,\n i + 1,\n len(self.train_loader),\n batch_time=batch_time,\n data_time=data_time,\n loss=loss_meters['loss_total']))\n self.train_logger.log({\n 'epoch': epoch,\n 'loss_total': loss_meters['loss_total'].avg,\n 'loss_classifier': loss_meters['loss_classifier'].avg,\n 'loss_box_reg': loss_meters['loss_box_reg'].avg,\n 'loss_objectness': loss_meters['loss_objectness'].avg,\n 'loss_rpn_box_reg': loss_meters['loss_rpn_box_reg'].avg,\n 'lr': self.optimizer.param_groups[0]['lr']\n })\n return loss_meters['loss_total'].avg\n\n @torch.no_grad()\n def _evaluate_epoch(self, epoch):\n \"\"\"evaluate the model on the test set following an epoch of training.\n\n Args:\n epoch (int): epoch number, greater than or equal to 0\n\n \"\"\"\n print('evaluating epoch {}'.format(epoch))\n self.model.eval()\n cpu_device = torch.device(\"cpu\")\n results = {}\n for i, (images, targets) in enumerate(self.test_loader):\n images = list(img.to(self.device) for img in images)\n targets = [{k: v.to(self.device) for k, v in t.items()} for t in targets]\n outputs = self.model(images)\n outputs = [{k: v.to(cpu_device).numpy().tolist() for k, v in t.items()} for t in outputs]\n results.update({target[\"image_id\"].item(): output for target, output in zip(targets, outputs)})\n df = pd.DataFrame.from_dict(results, orient='index')\n df['Framefile'] = [os.path.basename(path) for path in self.test_dataset.img_files]\n df = df[['Framefile', 'boxes', 'labels', 'scores']].set_index('Framefile')\n df.to_csv(os.path.join(self.fm.local_paths['predictions_dir'], '{}.csv'.format(epoch)))\n\n def _save_model(self):\n \"\"\"save the weights file (state dict) for the model.\"\"\"\n dest = self.fm.local_paths['weights_file']\n if os.path.exists(dest):\n path = os.path.join(self.fm.local_paths['weights_dir'], str(int(os.path.getmtime(dest))) + '.weights')\n os.rename(dest, path)\n torch.save(self.model.state_dict(), dest)\n\n","sub_path":"Modules/Trainer.py","file_name":"Trainer.py","file_ext":"py","file_size_in_byte":7908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"4008794","text":"import numpy as np\nimport pandas as pd\n\ndef dataset_count(dataset_ss, countfield='col1', save_csv=False):\n \"\"\"\n Count all elements in list and drop duplicates.\n \n Parameters\n ----------\n dataset_ss : iterable, list\n The raw data \n save_csv: boolean, default=False\n Saves csv file\n \n Returns\n -------\n df, pandas.DataFrame object\n \"\"\"\n \n df = pd.DataFrame({countfield:dataset_ss})\n df['count'] = df.groupby(countfield)[countfield].transform('count')\n if save_csv is True:\n df.drop_duplicates().to_csv('count_'+str(len(dataset_ss))+'.csv', index=False)\n return df.drop_duplicates().sort_values('count', ascending=False)\n\ndef dropna_col(df, column='col1'):\n \"\"\"\n \"\"\"\n return df[df[column].notna()]\n\ndef df_columns_lower(df):\n \"\"\"\n \"\"\"\n col_n = [str(i).replace(' ', '').lower() for i in list(df.columns)]\n df.columns = col_n\n return df\n\n\ndef flatten_list(list1):\n \"\"\"\n Flattens python list\n \n Parameters\n ----------\n list1 : iterable, list\n The raw data containing multiple list of lists\n \n Returns\n -------\n flattened list\n \"\"\"\n \n return [j for i in list1 for j in i]\n\ndef df_list_to_excel(df_list, outputname):\n \"\"\"\n \"\"\"\n writer = pd.ExcelWriter(outputname+ '.xlsx')\n for i in range(0, len(df_list)):\n df_list[i].to_excel(writer, sheet_name=str(i), index=False)\n\n writer.save()\n return 'Done'\n\n### RAY MULTIPROCESSING #############################################################\nimport time\n\nimport ray\nray.init(address='auto')\n\n@timefunc\ndef to_x():\n \"\"\"\n \"\"\"\n df = pd.read_csv('')\n y = df.apply(lambda x: def1(x[0]), axis=1)\n return y\n\n@ray.remote\ndef to_x_chunk(df):\n \"\"\"\n \"\"\"\n y = df.apply(lambda x: def1(x[0]), axis=1)\n return y\n\n@timefunc\ndef to_x_ray(chunk):\n \"\"\"\n \"\"\"\n L = 100000\n df = pd.read_csv('')\n ray_y = ray.get([to_x_chunk.remote(dfc) for dfc in df])\n return ray_y\n \n","sub_path":"dataops.py","file_name":"dataops.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"152029059","text":"\"\"\"\nType annotations for comprehend service literal definitions.\n\n[Open documentation](https://vemel.github.io/boto3_stubs_docs/mypy_boto3_comprehend/literals.html)\n\nUsage::\n\n ```python\n from mypy_boto3_comprehend.literals import AugmentedManifestsDocumentTypeFormatType\n\n data: AugmentedManifestsDocumentTypeFormatType = \"PLAIN_TEXT_DOCUMENT\"\n ```\n\"\"\"\nimport sys\n\nif sys.version_info >= (3, 8):\n from typing import Literal\nelse:\n from typing_extensions import Literal\n\n__all__ = (\n \"AugmentedManifestsDocumentTypeFormatType\",\n \"BlockTypeType\",\n \"DocumentClassifierDataFormatType\",\n \"DocumentClassifierModeType\",\n \"DocumentReadActionType\",\n \"DocumentReadFeatureTypesType\",\n \"DocumentReadModeType\",\n \"DocumentTypeType\",\n \"EndpointStatusType\",\n \"EntityRecognizerDataFormatType\",\n \"EntityTypeType\",\n \"InputFormatType\",\n \"JobStatusType\",\n \"LanguageCodeType\",\n \"ListDocumentClassificationJobsPaginatorName\",\n \"ListDocumentClassifiersPaginatorName\",\n \"ListDominantLanguageDetectionJobsPaginatorName\",\n \"ListEndpointsPaginatorName\",\n \"ListEntitiesDetectionJobsPaginatorName\",\n \"ListEntityRecognizersPaginatorName\",\n \"ListKeyPhrasesDetectionJobsPaginatorName\",\n \"ListPiiEntitiesDetectionJobsPaginatorName\",\n \"ListSentimentDetectionJobsPaginatorName\",\n \"ListTopicsDetectionJobsPaginatorName\",\n \"ModelStatusType\",\n \"PageBasedErrorCodeType\",\n \"PartOfSpeechTagTypeType\",\n \"PiiEntitiesDetectionMaskModeType\",\n \"PiiEntitiesDetectionModeType\",\n \"PiiEntityTypeType\",\n \"RelationshipTypeType\",\n \"SentimentTypeType\",\n \"SplitType\",\n \"SyntaxLanguageCodeType\",\n \"TargetedSentimentEntityTypeType\",\n)\n\nAugmentedManifestsDocumentTypeFormatType = Literal[\n \"PLAIN_TEXT_DOCUMENT\", \"SEMI_STRUCTURED_DOCUMENT\"\n]\nBlockTypeType = Literal[\"LINE\", \"WORD\"]\nDocumentClassifierDataFormatType = Literal[\"AUGMENTED_MANIFEST\", \"COMPREHEND_CSV\"]\nDocumentClassifierModeType = Literal[\"MULTI_CLASS\", \"MULTI_LABEL\"]\nDocumentReadActionType = Literal[\"TEXTRACT_ANALYZE_DOCUMENT\", \"TEXTRACT_DETECT_DOCUMENT_TEXT\"]\nDocumentReadFeatureTypesType = Literal[\"FORMS\", \"TABLES\"]\nDocumentReadModeType = Literal[\"FORCE_DOCUMENT_READ_ACTION\", \"SERVICE_DEFAULT\"]\nDocumentTypeType = Literal[\n \"IMAGE\",\n \"MS_WORD\",\n \"NATIVE_PDF\",\n \"PLAIN_TEXT\",\n \"SCANNED_PDF\",\n \"TEXTRACT_ANALYZE_DOCUMENT_JSON\",\n \"TEXTRACT_DETECT_DOCUMENT_TEXT_JSON\",\n]\nEndpointStatusType = Literal[\"CREATING\", \"DELETING\", \"FAILED\", \"IN_SERVICE\", \"UPDATING\"]\nEntityRecognizerDataFormatType = Literal[\"AUGMENTED_MANIFEST\", \"COMPREHEND_CSV\"]\nEntityTypeType = Literal[\n \"COMMERCIAL_ITEM\",\n \"DATE\",\n \"EVENT\",\n \"LOCATION\",\n \"ORGANIZATION\",\n \"OTHER\",\n \"PERSON\",\n \"QUANTITY\",\n \"TITLE\",\n]\nInputFormatType = Literal[\"ONE_DOC_PER_FILE\", \"ONE_DOC_PER_LINE\"]\nJobStatusType = Literal[\n \"COMPLETED\", \"FAILED\", \"IN_PROGRESS\", \"STOPPED\", \"STOP_REQUESTED\", \"SUBMITTED\"\n]\nLanguageCodeType = Literal[\n \"ar\", \"de\", \"en\", \"es\", \"fr\", \"hi\", \"it\", \"ja\", \"ko\", \"pt\", \"zh\", \"zh-TW\"\n]\nListDocumentClassificationJobsPaginatorName = Literal[\"list_document_classification_jobs\"]\nListDocumentClassifiersPaginatorName = Literal[\"list_document_classifiers\"]\nListDominantLanguageDetectionJobsPaginatorName = Literal[\"list_dominant_language_detection_jobs\"]\nListEndpointsPaginatorName = Literal[\"list_endpoints\"]\nListEntitiesDetectionJobsPaginatorName = Literal[\"list_entities_detection_jobs\"]\nListEntityRecognizersPaginatorName = Literal[\"list_entity_recognizers\"]\nListKeyPhrasesDetectionJobsPaginatorName = Literal[\"list_key_phrases_detection_jobs\"]\nListPiiEntitiesDetectionJobsPaginatorName = Literal[\"list_pii_entities_detection_jobs\"]\nListSentimentDetectionJobsPaginatorName = Literal[\"list_sentiment_detection_jobs\"]\nListTopicsDetectionJobsPaginatorName = Literal[\"list_topics_detection_jobs\"]\nModelStatusType = Literal[\n \"DELETING\", \"IN_ERROR\", \"STOPPED\", \"STOP_REQUESTED\", \"SUBMITTED\", \"TRAINED\", \"TRAINING\"\n]\nPageBasedErrorCodeType = Literal[\n \"INTERNAL_SERVER_ERROR\",\n \"PAGE_CHARACTERS_EXCEEDED\",\n \"PAGE_SIZE_EXCEEDED\",\n \"TEXTRACT_BAD_PAGE\",\n \"TEXTRACT_PROVISIONED_THROUGHPUT_EXCEEDED\",\n]\nPartOfSpeechTagTypeType = Literal[\n \"ADJ\",\n \"ADP\",\n \"ADV\",\n \"AUX\",\n \"CCONJ\",\n \"CONJ\",\n \"DET\",\n \"INTJ\",\n \"NOUN\",\n \"NUM\",\n \"O\",\n \"PART\",\n \"PRON\",\n \"PROPN\",\n \"PUNCT\",\n \"SCONJ\",\n \"SYM\",\n \"VERB\",\n]\nPiiEntitiesDetectionMaskModeType = Literal[\"MASK\", \"REPLACE_WITH_PII_ENTITY_TYPE\"]\nPiiEntitiesDetectionModeType = Literal[\"ONLY_OFFSETS\", \"ONLY_REDACTION\"]\nPiiEntityTypeType = Literal[\n \"ADDRESS\",\n \"AGE\",\n \"ALL\",\n \"AWS_ACCESS_KEY\",\n \"AWS_SECRET_KEY\",\n \"BANK_ACCOUNT_NUMBER\",\n \"BANK_ROUTING\",\n \"CA_HEALTH_NUMBER\",\n \"CA_SOCIAL_INSURANCE_NUMBER\",\n \"CREDIT_DEBIT_CVV\",\n \"CREDIT_DEBIT_EXPIRY\",\n \"CREDIT_DEBIT_NUMBER\",\n \"DATE_TIME\",\n \"DRIVER_ID\",\n \"EMAIL\",\n \"INTERNATIONAL_BANK_ACCOUNT_NUMBER\",\n \"IN_AADHAAR\",\n \"IN_NREGA\",\n \"IN_PERMANENT_ACCOUNT_NUMBER\",\n \"IN_VOTER_NUMBER\",\n \"IP_ADDRESS\",\n \"LICENSE_PLATE\",\n \"MAC_ADDRESS\",\n \"NAME\",\n \"PASSPORT_NUMBER\",\n \"PASSWORD\",\n \"PHONE\",\n \"PIN\",\n \"SSN\",\n \"SWIFT_CODE\",\n \"UK_NATIONAL_HEALTH_SERVICE_NUMBER\",\n \"UK_NATIONAL_INSURANCE_NUMBER\",\n \"UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER\",\n \"URL\",\n \"USERNAME\",\n \"US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER\",\n \"VEHICLE_IDENTIFICATION_NUMBER\",\n]\nRelationshipTypeType = Literal[\"CHILD\"]\nSentimentTypeType = Literal[\"MIXED\", \"NEGATIVE\", \"NEUTRAL\", \"POSITIVE\"]\nSplitType = Literal[\"TEST\", \"TRAIN\"]\nSyntaxLanguageCodeType = Literal[\"de\", \"en\", \"es\", \"fr\", \"it\", \"pt\"]\nTargetedSentimentEntityTypeType = Literal[\n \"ATTRIBUTE\",\n \"BOOK\",\n \"BRAND\",\n \"COMMERCIAL_ITEM\",\n \"DATE\",\n \"EVENT\",\n \"FACILITY\",\n \"GAME\",\n \"LOCATION\",\n \"MOVIE\",\n \"MUSIC\",\n \"ORGANIZATION\",\n \"OTHER\",\n \"PERSON\",\n \"PERSONAL_TITLE\",\n \"QUANTITY\",\n \"SOFTWARE\",\n]\n","sub_path":"typings/mypy_boto3_comprehend/literals.pyi","file_name":"literals.pyi","file_ext":"pyi","file_size_in_byte":5966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"60375328","text":"T = int(input())\n\nfor t in range(T):\n s = list(input())\n \n tail_start = len(s) - 1\n marker = s[-1]\n count = 0\n #print(\"initial\", s)\n while (tail_start > 0):\n\n for j in range(len(s)-1, -1, -1):\n if s[j] == marker:\n if (tail_start - j > 1):\n break\n tail_start = j\n \n if tail_start > 0:\n for i in range(tail_start):\n s[i] = ('+' if s[i] == '-' else '-')\n #print(\"after next move\", s)\n count += 1\n\n if s[0] == '-':\n count += 1\n for i in range(len(s)):\n if s[i] == '-':\n s[i] = '+'\n else:\n s[i] = '+'\n #print(s, 'after', count, 'moves')\n print('Case #', t+1, ': ', count, sep='')\n","sub_path":"codes/CodeJamCrawler/16_0_2/nikvander423/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"20684061","text":"\"\"\"This script creates a regression test over metarl-MAML and ProMP-TRPO.\n\nUnlike metarl, baselines doesn't set max_path_length. It keeps steps the action\nuntil it's done. So we introduced tests.wrappers.AutoStopEnv wrapper to set\ndone=True when it reaches max_path_length. We also need to change the\nmetarl.tf.samplers.BatchSampler to smooth the reward curve.\n\"\"\"\nimport argparse\nimport datetime\nimport os\nimport os.path as osp\nimport random\nimport sys\n\nimport numpy as np\nimport dowel\nfrom dowel import logger as dowel_logger\nimport pytest\nimport torch\nimport tensorflow as tf\n\nfrom metarl.envs.ml_wrapper import ML10WithPinnedGoal\n\nfrom metarl.envs import normalize\nfrom metarl.envs.base import MetaRLEnv\nfrom metarl.envs import TaskIdWrapper2\nfrom metarl.experiment import deterministic, LocalRunner, SnapshotConfig\nfrom metarl.np.baselines import LinearFeatureBaseline\nfrom metarl.torch.algos import MAMLTRPO\nfrom metarl.torch.policies import GaussianMLPPolicy\n\nfrom tests import benchmark_helper\nimport tests.helpers as Rh\n\ntest_metarl = True\n\nhyper_parameters = {\n 'hidden_sizes': [100, 100],\n 'max_kl': 0.01,\n 'inner_lr': 0.05,\n 'gae_lambda': 1.0,\n 'discount': 0.99,\n 'max_path_length': 100,\n 'fast_batch_size': 10, # num of rollouts per task\n 'meta_batch_size': 20, # num of tasks\n 'n_epochs': 2500,\n # 'n_epochs': 1,\n 'n_trials': 1,\n 'num_grad_update': 1,\n 'n_parallel': 1,\n 'inner_loss': 'log_likelihood'\n}\n\nclass TestBenchmarkMAML: # pylint: disable=too-few-public-methods\n \"\"\"Compare benchmarks between metarl and baselines.\"\"\"\n\n @pytest.mark.huge\n def test_benchmark_maml(self, _): # pylint: disable=no-self-use\n \"\"\"Compare benchmarks between metarl and baselines.\"\"\"\n timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S-%f')\n benchmark_dir = './data/local/benchmarks/maml-ml10/%s/' % timestamp\n result_json = {}\n env_id = 'ML10'\n meta_env = TaskIdWrapper2(ML10WithPinnedGoal.get_train_tasks())\n\n seeds = random.sample(range(100), hyper_parameters['n_trials'])\n task_dir = osp.join(benchmark_dir, env_id)\n plt_file = osp.join(benchmark_dir, '{}_benchmark.png'.format(env_id))\n promp_csvs = []\n metarl_csvs = []\n\n for trial in range(hyper_parameters['n_trials']):\n seed = seeds[trial]\n trial_dir = task_dir + '/trial_%d_seed_%d' % (trial + 1, seed)\n metarl_dir = trial_dir + '/metarl'\n promp_dir = trial_dir + '/promp'\n\n if test_metarl:\n # Run metarl algorithm\n env = MetaRLEnv(normalize(meta_env, expected_action_scale=10.))\n metarl_csv = run_metarl(env, seed, metarl_dir)\n metarl_csvs.append(metarl_csv)\n env.close()\n\ndef run_metarl(env, seed, log_dir):\n \"\"\"Create metarl PyTorch MAML model and training.\n\n Args:\n env (MetaRLEnv): Environment of the task.\n seed (int): Random positive integer for the trial.\n log_dir (str): Log dir path.\n\n Returns:\n str: Path to output csv file\n\n \"\"\"\n deterministic.set_seed(seed)\n\n policy = GaussianMLPPolicy(\n env_spec=env.spec,\n hidden_sizes=hyper_parameters['hidden_sizes'],\n hidden_nonlinearity=torch.tanh,\n output_nonlinearity=None,\n )\n\n baseline = LinearFeatureBaseline(env_spec=env.spec)\n\n algo = MAMLTRPO(env=env,\n policy=policy,\n baseline=baseline,\n max_path_length=hyper_parameters['max_path_length'],\n discount=hyper_parameters['discount'],\n gae_lambda=hyper_parameters['gae_lambda'],\n meta_batch_size=hyper_parameters['meta_batch_size'],\n inner_lr=hyper_parameters['inner_lr'],\n max_kl_step=hyper_parameters['max_kl'],\n num_grad_updates=hyper_parameters['num_grad_update'])\n\n # Set up logger since we are not using run_experiment\n tabular_log_file = osp.join(log_dir, 'progress.csv')\n dowel_logger.add_output(dowel.StdOutput())\n dowel_logger.add_output(dowel.CsvOutput(tabular_log_file))\n dowel_logger.add_output(dowel.TensorBoardOutput(log_dir))\n\n snapshot_config = SnapshotConfig(snapshot_dir=log_dir,\n snapshot_mode='all',\n snapshot_gap=1)\n\n runner = LocalRunner(snapshot_config=snapshot_config)\n runner.setup(algo, env, sampler_args=dict(n_envs=5))\n runner.train(n_epochs=hyper_parameters['n_epochs'],\n batch_size=(hyper_parameters['fast_batch_size'] *\n hyper_parameters['max_path_length']))\n\n dowel_logger.remove_all()\n\n return tabular_log_file\n\ndef worker(variant):\n variant_str = '-'.join(['{}_{}'.format(k, v) for k, v in variant.items()])\n if 'hidden_sizes' in variant:\n hidden_sizes = variant['hidden_sizes']\n variant['hidden_sizes'] = [hidden_sizes, hidden_sizes]\n hyper_parameters.update(variant)\n\n test_cls = TestBenchmarkMAML()\n test_cls.test_benchmark_maml(variant_str)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--parallel', action='store_true', default=False)\n parser.add_argument('--combined', action='store_true', default=False)\n\n known_args, unknown_args = parser.parse_known_args()\n\n for arg in unknown_args:\n if arg.startswith('--'):\n parser.add_argument(arg, type=float)\n\n args = parser.parse_args()\n print(args)\n\n parallel = args.parallel\n combined = args.combined\n args = vars(args)\n del args['parallel']\n del args['combined']\n\n n_variants = len(args)\n if combined:\n variants = [{\n k: int(v) if v.is_integer() else v for k, v in args.items()\n }]\n else:\n if n_variants > 0:\n variants = [{\n k: int(v) if v.is_integer() else v\n } for k, v in args.items()]\n else:\n variants = [dict(n_trials=1)\n for _ in range(hyper_parameters['n_trials'])]\n\n for key in args:\n assert key in hyper_parameters, \"{} is not a hyperparameter\".format(key)\n\n children = []\n for i, variant in enumerate(variants):\n random.seed(i)\n pid = os.fork()\n if pid == 0:\n worker(variant)\n exit()\n else:\n if parallel:\n children.append(pid)\n else:\n os.waitpid(pid, 0)\n\n if parallel:\n for child in children:\n os.waitpid(child, 0)\n","sub_path":"neurips_launchers/ml10_maml_trpo.py","file_name":"ml10_maml_trpo.py","file_ext":"py","file_size_in_byte":6645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"401669690","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom caffe2.python import core, brew\n\n\nclass ResNetBuilder():\n\n def __init__(self, model, prev_blob, no_bias, is_test):\n self.model = model\n self.comp_count = 0\n self.comp_idx = 0\n self.prev_blob = prev_blob\n self.is_test = is_test\n self.no_bias = 1 if no_bias else 0\n\n def add_conv(self, in_filters, out_filters, kernel, stride=1, pad=0):\n self.comp_idx += 1\n self.prev_blob = brew.conv(\n self.model,\n self.prev_blob,\n 'comp_%d_conv_%d' % (self.comp_count, self.comp_idx),\n in_filters,\n out_filters,\n weight_init=(\"MSRAFill\", {}),\n kernel=kernel,\n stride=stride,\n pad=pad,\n no_bias=self.no_bias,\n )\n return self.prev_blob\n\n def add_relu(self):\n self.prev_blob = brew.relu(\n self.model,\n self.prev_blob,\n self.prev_blob, # in-place\n )\n return self.prev_blob\n\n def add_spatial_bn(self, num_filters):\n self.prev_blob = brew.spatial_bn(\n self.model,\n self.prev_blob,\n 'comp_%d_spatbn_%d' % (self.comp_count, self.comp_idx),\n num_filters,\n epsilon=1e-3,\n is_test=self.is_test,\n )\n return self.prev_blob\n\n def add_simple_block(\n self,\n input_filters,\n num_filters,\n down_sampling=False,\n spatial_batch_norm=True,\n ):\n self.comp_idx = 0\n shortcut_blob = self.prev_blob\n\n if spatial_batch_norm:\n self.add_spatial_bn(input_filters)\n pre_relu = self.add_relu()\n\n self.add_conv(\n input_filters,\n num_filters,\n kernel=3,\n stride=(1 if down_sampling is False else 2),\n pad=1,\n )\n\n if spatial_batch_norm:\n self.add_spatial_bn(num_filters)\n self.add_relu()\n\n last_conv = self.add_conv(num_filters, num_filters, kernel=3, pad=1)\n\n # Increase of dimensions, need a projection for the shortcut\n if (num_filters != input_filters):\n shortcut_blob = brew.conv(\n self.model,\n pre_relu,\n 'shortcut_projection_%d' % self.comp_count,\n input_filters,\n num_filters,\n weight_init=(\"MSRAFill\", {}),\n kernel=1,\n stride=(1 if down_sampling is False else 2),\n no_bias=self.no_bias,\n )\n\n self.prev_blob = brew.sum(\n self.model,\n [shortcut_blob, last_conv],\n 'comp_%d_sum_%d' % (self.comp_count, self.comp_idx),\n )\n self.comp_idx += 1\n self.comp_count += 1\n\n\ndef create_resnet(\n model, data,\n num_input_channels,\n num_groups,\n num_labels,\n is_test=False,\n):\n filters = [16, 32, 64]\n brew.conv(model, data, 'conv1', num_input_channels,\n filters[0], no_bias=1, kernel=3, stride=1, pad=1)\n\n builder = ResNetBuilder(model, 'conv1', no_bias=1, is_test=is_test)\n\n # input: 32x32x16 output: 32x32x16\n for _ in range(num_groups):\n builder.add_simple_block(\n filters[0], filters[0], down_sampling=False)\n\n # input: 32x32x16 output: 16x16x32\n builder.add_simple_block(filters[0], filters[1], down_sampling=True)\n for _ in range(1, num_groups):\n builder.add_simple_block(\n filters[1], filters[1], down_sampling=False)\n\n # input: 16x16x32 output: 8x8x64\n builder.add_simple_block(filters[1], filters[2], down_sampling=True)\n for _ in range(1, num_groups):\n builder.add_simple_block(\n filters[2], filters[2], down_sampling=False)\n\n brew.spatial_bn(model, builder.prev_blob, 'last_spatbn',\n filters[2], epsilon=1e-3, is_test=is_test)\n brew.relu(model, 'last_spatbn', 'last_relu')\n # Final layers\n brew.average_pool(model, 'last_relu', 'final_avg', kernel=8, stride=1)\n last_out = brew.fc(model, 'final_avg', 'last_out', 64, num_labels)\n\n return last_out\n","sub_path":"05_cifar10_multi_gpu/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"57159190","text":"#\n# Copyright (c) 2023 Airbyte, Inc., all rights reserved.\n#\n\nimport requests\nfrom airbyte_cdk.models import SyncMode\nfrom pytest import fixture\nfrom source_onesignal.streams import Devices, IncrementalOnesignalStream, Notifications\n\n\n@fixture\ndef patch_incremental_base_class(mocker):\n # Mock abstract methods to enable instantiating abstract class\n mocker.patch.object(IncrementalOnesignalStream, \"path\", \"v0/example_endpoint\")\n mocker.patch.object(IncrementalOnesignalStream, \"primary_key\", \"test_primary_key\")\n mocker.patch.object(IncrementalOnesignalStream, \"__abstractmethods__\", set())\n\n\n@fixture\ndef args():\n return {\"authenticator\": None,\n \"config\": {\"user_auth_key\": \"\",\n \"start_date\": \"2021-01-01T00:00:00Z\",\n \"outcome_names\": \"\",\n \"applications\": [\n {\"app_id\": \"fake_id\",\n \"app_api_key\": \"fake_api_key\"}\n ]\n }\n }\n\n\n@fixture\ndef stream(patch_incremental_base_class, args):\n return IncrementalOnesignalStream(**args)\n\n\ndef test_cursor_field(stream):\n expected_cursor_field = \"updated_at\"\n assert stream.cursor_field == expected_cursor_field\n\n\ndef test_stream_slices(stream, requests_mock):\n expected_stream_slice = [{'app_api_key': 'fake_api_key', 'app_id': 'fake_id'}]\n assert list(stream.stream_slices(sync_mode=SyncMode.full_refresh)) == expected_stream_slice\n\n\ndef test_supports_incremental(patch_incremental_base_class, mocker, args):\n mocker.patch.object(IncrementalOnesignalStream, \"cursor_field\", \"dummy_field\")\n stream = IncrementalOnesignalStream(**args)\n assert stream.supports_incremental\n\n\ndef test_source_defined_cursor(stream):\n assert stream.source_defined_cursor\n\n\ndef test_stream_checkpoint_interval(stream):\n expected_checkpoint_interval = None\n assert stream.state_checkpoint_interval == expected_checkpoint_interval\n\n\ndef test_next_page_token(stream, requests_mock):\n requests_mock.get(\"https://dummy\", json={\"total_count\": 123, \"offset\": 22, \"limit\": 33})\n resp = requests.get(\"https://dummy\")\n expected_next_page_token = {\"offset\": 55}\n assert stream.next_page_token(resp) == expected_next_page_token\n\n requests_mock.get(\"https://dummy\", json={\"total_count\": 123, \"offset\": 100, \"limit\": 33})\n resp = requests.get(\"https://dummy\")\n expected_next_page_token = None\n assert stream.next_page_token(resp) == expected_next_page_token\n\n\ndef test_request_params(stream, args):\n inputs = {\"stream_state\": {}, \"stream_slice\": {\"app_id\": \"abc\"}}\n inputs2 = {\"stream_state\": {}, \"stream_slice\": {\"app_id\": \"abc\"}, \"next_page_token\": {\"offset\": 42}}\n expected_request_params = {\"app_id\": \"abc\", \"limit\": None}\n expected_request_params2 = {\"app_id\": \"abc\", \"limit\": None, \"offset\": 42}\n\n assert stream.request_params(**inputs) == expected_request_params\n assert stream.request_params(**inputs2) == expected_request_params2\n\n stream2 = Devices(**args)\n expected_request_params[\"limit\"] = 300\n expected_request_params2[\"limit\"] = 300\n assert stream2.request_params(**inputs) == expected_request_params\n assert stream2.request_params(**inputs2) == expected_request_params2\n\n stream3 = Notifications(**args)\n expected_request_params[\"limit\"] = 50\n expected_request_params2[\"limit\"] = 50\n assert stream3.request_params(**inputs) == expected_request_params\n assert stream3.request_params(**inputs2) == expected_request_params2\n\n\ndef test_filter_by_state(stream):\n inputs = {\n \"stream_state\": {\"fake_id\": {\"updated_at\": 100}},\n \"record\": {\"updated_at\": 200},\n \"stream_slice\": {'app_id': \"fake_id\"}\n }\n expected_filter_by_state = True\n assert stream.filter_by_state(**inputs) == expected_filter_by_state\n\n inputs = {\n \"stream_state\": {\"fake_id\": {\"updated_at\": 200}},\n \"record\": {\"updated_at\": 100},\n \"stream_slice\": {'app_id': \"fake_id\"}\n }\n expected_filter_by_state = False\n assert stream.filter_by_state(**inputs) == expected_filter_by_state\n","sub_path":"airbyte-integrations/connectors/source-onesignal/unit_tests/test_incremental_streams.py","file_name":"test_incremental_streams.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"270944850","text":"# coding: utf-8\n\"\"\"\nCopyright (c) 2019 The MITRE Corporation.\n\"\"\"\n\nimport json\nimport mxnet as mx\nimport gluonnlp as nlp\nimport io\nfrom tmnt.seq_vae.tokenization import BasicTokenizer\nfrom tmnt.seq_vae.trans_seq_models import PureTransformerVAE\n\nclass SeqVAEInference(object):\n\n def __init__(self, param_file, config_file, vocab_file, sent_size=None, ctx=mx.cpu()):\n self.max_batch_size = 2\n with open(config_file) as f:\n config = json.loads(f.read())\n with open(vocab_file) as f:\n voc_js = f.read()\n self.vocab = nlp.Vocab.from_json(voc_js)\n self.ctx = ctx\n self.latent_dist = config['latent_dist']\n self.num_units = config['num_units']\n self.num_heads = config['num_heads'] \n self.hidden_size = config['hidden_size']\n self.layers = config['transformer_layers']\n self.n_latent = config['n_latent']\n self.kappa = config['kappa']\n self.embedding_size = config['embedding_size']\n self.pad_id = self.vocab[self.vocab.padding_token]\n self.max_sent_len = sent_size if sent_size else config['sent_size']\n self.model = PureTransformerVAE(self.vocab, self.embedding_size, self.latent_dist, self.num_units, self.hidden_size, self.num_heads,\n self.n_latent, self.max_sent_len, self.layers, kappa=self.kappa, batch_size=1)\n self.tokenizer = BasicTokenizer(do_lower_case=True)\n self.model.load_parameters(str(param_file), allow_missing=False)\n\n\n def prep_text(self, txt):\n toks = self.tokenizer.tokenize(txt)[:(self.max_sent_len-2)]\n toks = [''] + toks + ['']\n ids = []\n for t in toks:\n try:\n ids.append(self.vocab[t])\n except:\n ids.append(self.vocab[self.vocab.unknown_token])\n padded_ids = ids[:self.max_sent_len] if len(ids) >= self.max_sent_len else ids + [self.pad_id] * (self.max_sent_len - len(ids))\n return mx.nd.array(padded_ids, dtype='int').expand_dims(0)\n\n\n def recode_text(self, txt):\n ids = self.prep_text(txt)\n _, _, _, predictions = self.model(ids)\n reconstructed_sent_ids = mx.nd.argmax(predictions[0],1).asnumpy()\n rec_sent = [self.vocab.idx_to_token[int(i)] for i in reconstructed_sent_ids if i != self.pad_id] # remove token from rendering\n return rec_sent\n\n def encode_text(self, txt):\n ids = self.prep_text(txt)\n return mx.nd.squeeze(self.model.encode(ids))\n\n \n \n","sub_path":"tmnt/seq_vae/runtime.py","file_name":"runtime.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"339616082","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport sys\nfrom logging import getLogger\n\nfrom db.mysql_db import select\nfrom networking.nat64 import exec_cmd\nfrom system.system_config import get_process_id\nfrom utils.cache import cache\n\n# pylint: disable=E1101\n\n\nclass NodeBase(object):\n def __init__(self, data):\n for key, val in data.iteritems():\n if isinstance(val, int):\n val = str(val)\n elif isinstance(val, basestring):\n val = val.strip()\n setattr(self, key, val)\n self.old_pid = cache.get('%s-%s' % (self.__class__.__name__, self.id), -1)\n self.all_pids = []\n\n def config(self):\n getLogger('main').info('config %s begin...', self.__class__.__name__)\n if str(self.iStatus) == '1':\n self.enable()\n elif str(self.iStatus) == '0':\n self.disable()\n\n def enable(self):\n self._clean_up()\n self._start_process()\n self._config_iptables()\n\n def disable(self):\n self._clean_up()\n\n def _clean_up(self):\n self._config_iptables(is_add=False)\n if self.old_pid in self.all_pids:\n exec_cmd('kill %s' % self.old_pid)\n cache.set('%s-%s' % (self.__class__.__name__, self.id), -1)\n\n def _start_process(self):\n pass\n\n def _config_iptables(self, is_add=True):\n pass\n\n\nclass CenterNode(NodeBase):\n def __init__(self, data):\n super(CenterNode, self).__init__(data)\n self.all_pids = get_process_id('supernode') or []\n\n def _start_process(self):\n _, pid = exec_cmd('supernode -f %s &>/dev/null & echo $!' % self.sPort)\n cache.set('%s-%s' % (self.__class__.__name__, self.id), int(pid))\n\n def _config_iptables(self, is_add=True):\n cmd = 'iptables -{action} FWINPUT -p udp --dport {port} -j ACCEPT'\n exec_cmd(cmd.format(action={True: 'I', False: 'D'}[is_add], port=self.sPort))\n\n\nclass EdgeNode(NodeBase):\n def __init__(self, data):\n super(EdgeNode, self).__init__(data)\n self.all_pids = get_process_id('edge') or []\n\n def _start_process(self):\n public_ip = ' '.join(['-l %s:%s' % (ip, self.sPort) for ip in self.sPublicIp.split(',') if ip])\n mac_next = self.sVirtualIp.split('.')\n mac34 = mac_next[2].zfill(4)\n mac56 = mac_next[3].zfill(4)\n mac = 'aa:bd' + ':' + mac34[:2] + ':' + mac34[2:] + ':' + mac56[:2] + ':' + mac56[2:]\n cmd = 'edge -f -d {iface} -a {vip} -c {network} -u 0 -g 0 -k {key} {public_ip} -m {mac}'.format(\n iface=self.sVirtualName, vip=self.sVirtualIp, network=self.sNetName,\n key=self.sPassword, public_ip=public_ip, mac=mac)\n _, pid = exec_cmd('%s &>/dev/null & echo $!' % cmd)\n cache.set('%s-%s' % (self.__class__.__name__, self.id), int(pid))\n\n def _config_iptables(self, is_add=True):\n cmd = ('iptables -{action} FWINPUT -p udp -j ACCEPT;'\n 'iptables -{action} FWINPUT -s {vip}/24 -d {vip}/24 -j ACCEPT')\n exec_cmd(cmd.format(action={True: 'I', False: 'D'}[is_add], vip=self.sVirtualIp))\n\n\ndef recover():\n \"\"\"开机恢复与恢复出厂设置\"\"\"\n\n if len(sys.argv) == 1:\n return\n\n trans_map = {\n CenterNode: select('SELECT * FROM m_tbntn_center WHERE iStatus=1;'),\n EdgeNode: select('SELECT * FROM m_tbntn_edge WHERE iStatus=1;'),\n }\n\n for proc_class, datas in trans_map.items():\n for data in datas:\n if sys.argv[1] == 'factory_recover':\n data.iStatus = 0\n proc_class(data).config()\n elif sys.argv[1] == 'boot_recover':\n proc_class(data).config()\n\n\nif __name__ == '__main__':\n recover()\n","sub_path":"chuhuo_2.71/bluedon/ipsecvpn/n_to_n.py","file_name":"n_to_n.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"586941639","text":"from random import uniform\nimport math\n\n\nclass Perceptron:\n def __init__(self):\n self.weights = []\n self.bias = None\n self.last = 0\n for i in range(3):\n self.weights.append(uniform(-1,1))\n self.bias = uniform(-1,+1)\n\n def sigmoid(self, x):\n sigmoids = 1/(1+(math.exp(-x)))\n return sigmoids\n\n def guess(self,inputs):\n sum = 0\n for i in range(0,len(inputs)):\n sum+= inputs[i]*self.weights[i]\n sum+=self.bias\n\n last = self.sigmoid(sum)\n self.last = last\n return last\n\n def train(self,weights = [], targets = [], finals = False):\n if finals == False:\n err = targets[0]-self.last\n print(\"Error {}\".format(err))\n for i in range(0,len(self.weights)):\n self.weights[i] += err\n return err\n\n err = 0\n for i in range(len(targets)):\n err+= (weights[i]/sum(weights))*targets[i]\n\n for i in range(0, len(self.weights)):\n self.weights[i] += err\n return err\n","sub_path":"AI/Color Chooser/Perceptron.py","file_name":"Perceptron.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601141923","text":"def main():\n N = 10\n \n # Bunch of references\n matrixReferences = [[ 0 for i in range(0, N) ] * N] # this is not printing out references...\n \n # Actual new arrays. Confusing at first, but makes sense if you think about it. \n matrixArrays = [[0 for i in range(0, N)] for j in range(0, N)]\n \n print(matrixReferences) # print the references\n print(matrixArrays) # print the arrays\n \nmain()\n\n","sub_path":"LearningPython/Initialization.py","file_name":"Initialization.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"394871259","text":"from tensorflow.examples.tutorials.mnist import input_data\nimport tensorflow as tf\n\nmnist = input_data.read_data_sets(\"mnist_data/\", one_hot=True)\nsess = tf.InteractiveSession()\nx = tf.placeholder(tf.float32, shape = [None, 784])\ny_ = tf.placeholder(tf.float32, shape = [None, 10])\nW = tf.Variable(tf.zeros([784, 10]))\nb = tf.Variable(tf.zeros([10]))\n\n#初期化\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape,stddev=0.1)\n return tf.Variable(initial)\n\n#初期化\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape = shape)\n return tf.Variable(initial)\n\n#入力値xと重みWを引数としてとる\ndef conv2d(x,W):\n #2次元の込畳みこみ\n #1pxずつずらしてずらして適用する\n #入力と同じサイズの出力\n return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')\n\n#畳み込まれたデータの中で\n#2px*2pxの中で一番サイズの大きなデータを出力��して返す\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n\n#一番目の重みとバイアス\nW_conv1 = weight_variable([5,5,1,32])\nb_conv1 = bias_variable([32])\n#Xは複数あるので、Xの数文の入れ物\n#-1は実行時に自動で割り当てるフラグ\nx_image = tf.reshape(x, [-1, 28, 28, 1])\n#畳み込んだ結果に対して、正規化関数のreluを適用しプーリング\nh_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\nh_pool = max_pool_2x2(h_conv1)\n\nW_conv2 = weight_variable([5,5,32,64])\nb_conv2 = bias_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool, W_conv2) + b_conv2)\nh_pool2 = max_pool_2x2(h_conv2)\n#全結合\nW_fc1 = weight_variable([7*7*64, 1024])\nb_fc1 = bias_variable([1024])\nh_pool2_flat = tf.reshape(h_pool2, [-1,7*7*64])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n#dropout過学習に備える\nkeep_prob = tf.placeholder(tf.float32)\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\nW_fc2 = weight_variable([1024, 10])\nb_fc2 = bias_variable([10])\ny_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2\n\n#予測値と実測値の誤差を最小にしていく\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = y_conv, labels = y_))\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n#正解率:確率の高いものと実測値が正しいか\ncorrect_prediction = tf.equal(tf.argmax(y_conv, 1), tf.arg_max(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\nsess.run(tf.global_variables_initializer())\nfor i in range(20000):\n batch = mnist.train.next_batch(50)\n if i%100 == 0:\n train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_:batch[1], keep_prob:1.0})\n print(\"step %d, training accuracy %g\"%(i, train_accuracy))\n train_step.run(feed_dict={x:batch[0], y_:batch[1], keep_prob:0.5})\n\nprint(\"test sccuracy %g\"%accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}))","sub_path":"tensorFlowTest/UmTensor/mnist_experts.py","file_name":"mnist_experts.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"379039566","text":"from math import sqrt\nfrom random import choice, random, randint\nfrom networkx import Graph, max_weight_matching\n\nMAX_PTS_PER_ROUND = 300\nWIN_PTS = 275\nLOSE_PTS = 200\nVAR = 25\n\n#TEST\n\n# fine tune distance between teams\n# figure out the 1/distance thing...\n\nclass team():\n def __init__(self,name=None,id=None):\n self._name = name\n self._id = id\n self._pts = []\n self._wins = 0\n self._losses = 0\n self._played = []\n\n def __gt__(self,other):\n if self._wins > other._wins:\n return True\n elif self._wins == other._wins:\n if sum(self._pts) > sum(other._pts):\n return True\n else:\n return False\n\n def __lt__(self,other):\n if self._wins < other._wins:\n return True\n elif self._wins == other._wins:\n if sum(self._pts) < sum(other._pts):\n return True\n else:\n return False\n\n def __str__(self):\n #return \"ID:{:<2} | W:{:<2} L:{:<2} | Points: {:<4} | played: {}\".format(self._id, self._wins, self._losses, sum(self._pts), \", \".join([x._name for x in self._played]))\n return \"Name: {:<10} | W:{:<2} L:{:<2} | Points: {:<4} | played: {}\".format(self._name, self._wins, self._losses, sum(self._pts), \", \".join([x._name for x in self._played]))\n\n def pretty_print(self,num_indent):\n n = num_indent\n white = n*\" \"\n raw_str = \"Name: {:<10}|W:{:<2} L:{:<2}|Points: {:<4}|played: {}\".format(self._name, self._wins, self._losses, sum(self._pts), \", \".join([x._name for x in self._played]))\n outs = raw_str.split(\"|\")\n #name = outs.pop(0)\n #print(white+name)\n #print(white+\"-\"*20)\n for out in outs:\n print(white+out)\n \n \n def get_name(self):\n return self._name\n\n def set_name(self,new_name):\n self._name = new_name\n \n def inc_wins(self):\n self._wins += 1\n\n def dec_wins(self):\n self._wins -= 1\n \n def get_wins(self):\n return self._wins\n\n def inc_losses(self):\n self._losses += 1\n\n def dec_losses(self):\n self._losses -= 1\n \n def get_losses(self):\n return self._losses\n\n def add_to_played(self,other):\n self._played.append(other)\n\n def add_to_points(self,points):\n self._pts.append(points)\n\n def get_points(self):\n return self._pts\n \n def get_total_pts(self):\n return sum(self._pts)\n\n def get_played(self):\n return self._played\n \n def get_distance(self,other):\n dx = abs(float(self.get_wins() - other.get_wins()))\n \n return dx\n\ndef get_matches(list_of_teams):\n G = Graph()\n teams = list_of_teams[:]\n num_teams = len(teams)\n for idx1 in range(num_teams):\n for idx2 in range(idx1+1,num_teams):\n a = teams[idx1]\n b = teams[idx2]\n if b not in a.get_played():\n dist = a.get_distance(b)\n if dist == 0:\n #perfect match just slightly better than distance 1\n edge_weight = 10**6 + 500\n else:\n edge_weight = int(1000000.0/dist)\n #print(a)\n #print(b)\n #print(edge_weight)\n #print(\"\")\n G.add_edge(a,b,weight = edge_weight)\n \n #print(len(G.edges()))\n\n #use max cardinality to ensure all vertices used\n matches_dict = max_weight_matching(G,maxcardinality=True)\n matches = [(a,b) for a,b in matches_dict.items()]\n #print(len(matches))\n for match in matches:\n x = (match[1],match[0])\n if x in matches:\n matches.remove(x)\n# used = matches_dict.keys()\n# unused = [x for x in teams if x not in used]\n# if len(unused) != 0:\n# a = unused[0]\n# b = unused[1]\n# print(a in b.get_played())\n \n \n return matches\n\ndef get_random_matches(list_of_teams):\n\n if len(list_of_teams) % 2 == 1:\n raise Exception(\"ODD NUMBER OF TEAMS!\")\n\n matches = []\n teams = list_of_teams[:]\n n = len(teams)\n for idx in range(int(n/2)):\n a = choice(teams)\n teams.remove(a)\n b = choice(teams)\n teams.remove(b)\n matches.append((a,b))\n\n if len(matches) == 0:\n raise(\"NO MATCHES!\")\n\n return matches\n \n\n#======================#\n# #\n# Simulation Section #\n# #\n#======================#\n\ndef get_teams(num_teams):\n teams = []\n for idx in range(num_teams):\n teams.append(team(\"Team \" + str(idx),idx))\n\n return teams \n \n \ndef play(teamA, teamB):\n n = random()\n if n > .5:\n teamA.inc_wins()\n teamB.inc_losses()\n teamA.add_to_points(WIN_PTS + randint(-VAR,VAR))\n teamB.add_to_points(LOSE_PTS + randint(-VAR,VAR))\n else:\n teamA.inc_losses()\n teamB.inc_wins()\n teamA.add_to_points(LOSE_PTS + randint(-VAR,VAR))\n teamB.add_to_points(WIN_PTS + randint(-VAR,VAR))\n\n teamA.add_to_played(teamB)\n teamB.add_to_played(teamA)\n \ndef play_round(teams,matches):\n \n \n\n\n if len(matches)==0 or matches == None:\n raise Exception(\"NO MATCHES!!!\")\n\n for match in matches:\n play(match[0],match[1])\n \n\n\n \n","sub_path":"swiss_base.py","file_name":"swiss_base.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"488208284","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport copy\n\nfrom oslo_config import cfg\nfrom oslo_log import log as logging\nfrom oslo_serialization import jsonutils\nfrom toscaparser import tosca_template\nfrom toscaparser.utils import yamlparser\nfrom translator.hot import tosca_translator\nimport yaml\n\nfrom tacker.common import log\nfrom tacker.extensions import common_services as cs\nfrom tacker.extensions import vnfm\nfrom tacker.tosca import utils as toscautils\n\nfrom collections import OrderedDict\n\nLOG = logging.getLogger(__name__)\nCONF = cfg.CONF\n\nOPTS = [\n cfg.DictOpt('flavor_extra_specs',\n default={},\n help=_(\"Flavor Extra Specs\")),\n]\n\nCONF.register_opts(OPTS, group='openstack_vim')\n\nHEAT_VERSION_INCOMPATIBILITY_MAP = {'OS::Neutron::Port': {\n 'port_security_enabled': 'value_specs', }, }\n\nHEAT_TEMPLATE_BASE = \"\"\"\nheat_template_version: 2013-05-23\n\"\"\"\n\nALARMING_POLICY = 'tosca.policies.tacker.Alarming'\nSCALING_POLICY = 'tosca.policies.tacker.Scaling'\n\n\ndef get_scaling_policy_name(action, policy_name):\n return '%s_scale_%s' % (policy_name, action)\n\n\nclass TOSCAToHOT(object):\n \"\"\"Convert TOSCA template to HOT template.\"\"\"\n\n def __init__(self, vnf, heatclient):\n self.vnf = vnf\n self.heatclient = heatclient\n self.attributes = {}\n self.vnfd_yaml = None\n self.unsupported_props = {}\n self.heat_template_yaml = None\n self.monitoring_dict = None\n self.svcmonitoring_dict = None\n self.fields = None\n self.STACK_FLAVOR_EXTRA = cfg.CONF.openstack_vim.flavor_extra_specs\n\n @log.log\n def generate_hot(self):\n\n self._get_vnfd()\n dev_attrs = self._update_fields()\n vnfd_dict = yamlparser.simple_ordered_parse(self.vnfd_yaml)\n ####### VNF DICT is Orderded_dict\n LOG.debug('vnfd_dict %s', vnfd_dict)\n self._get_unsupported_resource_props(self.heatclient)\n\n\n is_tosca_format = False\n self._generate_hot_from_tosca(vnfd_dict, dev_attrs)\n\n is_tosca_format = True\n\n self.fields['template'] = self.heat_template_yaml\n print(\"\\n\")\n if is_tosca_format:\n self._handle_policies(vnfd_dict)\n if self.monitoring_dict:\n self.vnf['attributes']['monitoring_policy'] = jsonutils.dumps(\n self.monitoring_dict)\n if self.svcmonitoring_dict:\n self.vnf['attributes']['service_monitoring_policy'] = jsonutils.dumps(\n self.svcmonitoring_dict)\n\n @log.log\n def _get_vnfd(self):\n self.attributes = self.vnf['vnfd']['attributes'].copy()\n self.vnfd_yaml = self.attributes.pop('vnfd', None)\n if self.vnfd_yaml is None:\n # TODO(kangaraj-manickam) raise user level exception\n LOG.info(\"VNFD is not provided, so no vnf is created !!\")\n return\n LOG.debug('vnfd_yaml %s', self.vnfd_yaml)\n\n @log.log\n def _update_fields(self):\n attributes = self.attributes\n fields = dict((key, attributes.pop(key)) for key\n in ('stack_name', 'template_url', 'template')\n if key in attributes)\n for key in ('files', 'parameters'):\n if key in attributes:\n fields[key] = jsonutils.loads(attributes.pop(key))\n\n # overwrite parameters with given dev_attrs for vnf creation\n dev_attrs = self.vnf['attributes'].copy()\n fields.update(dict((key, dev_attrs.pop(key)) for key\n in ('stack_name', 'template_url', 'template')\n if key in dev_attrs))\n for key in ('files', 'parameters'):\n if key in dev_attrs:\n fields.setdefault(key, {}).update(\n jsonutils.loads(dev_attrs.pop(key)))\n\n self.attributes = attributes\n self.fields = fields\n\n return dev_attrs\n\n @log.log\n def _handle_policies(self, vnfd_dict):\n\n vnf = self.vnf\n (is_scaling_needed, scaling_group_names,\n main_dict) = self._generate_hot_scaling(\n vnfd_dict['topology_template'], 'scaling.yaml')\n (is_enabled_alarm, alarm_resource, heat_tpl_yaml) =\\\n self._generate_hot_alarm_resource(vnfd_dict['topology_template'])\n if is_enabled_alarm and not is_scaling_needed:\n self.fields['template'] = heat_tpl_yaml\n\n if is_scaling_needed:\n if is_enabled_alarm:\n main_dict['resources'].update(alarm_resource)\n main_yaml = yaml.safe_dump(main_dict)\n self.fields['template'] = main_yaml\n self.fields['files'] = {'scaling.yaml': self.heat_template_yaml}\n vnf['attributes']['heat_template'] = main_yaml\n # TODO(kanagaraj-manickam) when multiple groups are\n # supported, make this scaling attribute as\n # scaling name vs scaling template map and remove\n # scaling_group_names\n vnf['attributes']['scaling.yaml'] = self.heat_template_yaml\n vnf['attributes']['scaling_group_names'] = jsonutils.dumps(\n scaling_group_names)\n\n elif not vnf['attributes'].get('heat_template'):\n vnf['attributes']['heat_template'] = self.fields['template']\n self.vnf = vnf\n\n @log.log\n def _update_params(self, original, paramvalues, match=False):\n for key, value in (original).items():\n if not isinstance(value, dict) or 'get_input' not in str(value):\n pass\n elif isinstance(value, dict):\n if not match:\n if key in paramvalues and 'param' in paramvalues[key]:\n self._update_params(value, paramvalues[key]['param'],\n True)\n elif key in paramvalues:\n self._update_params(value, paramvalues[key], False)\n else:\n LOG.debug('Key missing Value: %s', key)\n raise cs.InputValuesMissing(key=key)\n elif 'get_input' in value:\n if value['get_input'] in paramvalues:\n original[key] = paramvalues[value['get_input']]\n else:\n LOG.debug('Key missing Value: %s', key)\n raise cs.InputValuesMissing(key=key)\n else:\n self._update_params(value, paramvalues, True)\n\n @log.log\n def _process_parameterized_input(self, dev_attrs, vnfd_dict):\n param_vattrs_yaml = dev_attrs.pop('param_values', None)\n if param_vattrs_yaml:\n try:\n param_vattrs_dict = yaml.safe_load(param_vattrs_yaml)\n LOG.debug('param_vattrs_yaml', param_vattrs_dict)\n except Exception as e:\n LOG.debug(\"Not Well Formed: %s\", str(e))\n raise vnfm.ParamYAMLNotWellFormed(\n error_msg_details=str(e))\n else:\n self._update_params(vnfd_dict, param_vattrs_dict)\n else:\n raise cs.ParamYAMLInputMissing()\n\n @log.log\n def _process_vdu_network_interfaces(self, vdu_id, vdu_dict, properties,\n template_dict):\n\n networks_list = []\n properties['networks'] = networks_list\n for network_param in vdu_dict['network_interfaces'].values():\n port = None\n if 'addresses' in network_param:\n ip_list = network_param.pop('addresses', [])\n if not isinstance(ip_list, list):\n raise vnfm.IPAddrInvalidInput()\n mgmt_flag = network_param.pop('management', False)\n port, template_dict =\\\n self._handle_port_creation(vdu_id, network_param,\n template_dict,\n ip_list, mgmt_flag)\n if network_param.pop('management', False):\n port, template_dict = self._handle_port_creation(vdu_id,\n network_param,\n template_dict,\n [], True)\n if port is not None:\n network_param = {\n 'port': {'get_resource': port}\n }\n networks_list.append(dict(network_param))\n return vdu_dict, template_dict\n\n @log.log\n def _make_port_dict(self):\n port_dict = {'type': 'OS::Neutron::Port'}\n if self.unsupported_props:\n port_dict['properties'] = {\n 'value_specs': {\n 'port_security_enabled': False\n }\n }\n else:\n port_dict['properties'] = {\n 'port_security_enabled': False\n }\n port_dict['properties'].setdefault('fixed_ips', [])\n return port_dict\n\n @log.log\n def _make_mgmt_outputs_dict(self, vdu_id, port, template_dict):\n mgmt_ip = 'mgmt_ip-%s' % vdu_id\n outputs_dict = template_dict['outputs']\n outputs_dict[mgmt_ip] = {\n 'description': 'management ip address',\n 'value': {\n 'get_attr': [port, 'fixed_ips', 0, 'ip_address']\n }\n }\n template_dict['outputs'] = outputs_dict\n return template_dict\n\n @log.log\n def _handle_port_creation(self, vdu_id, network_param,\n template_dict, ip_list=None,\n mgmt_flag=False):\n ip_list = ip_list or []\n port = '%s-%s-port' % (vdu_id, network_param['network'])\n port_dict = self._make_port_dict()\n if mgmt_flag:\n template_dict = self._make_mgmt_outputs_dict(vdu_id, port,\n template_dict)\n for ip in ip_list:\n port_dict['properties']['fixed_ips'].append({\"ip_address\": ip})\n port_dict['properties'].update(network_param)\n template_dict['resources'][port] = port_dict\n return port, template_dict\n\n @log.log\n def _get_unsupported_resource_props(self, heat_client):\n unsupported_resource_props = {}\n\n for res, prop_dict in (HEAT_VERSION_INCOMPATIBILITY_MAP).items():\n unsupported_props = {}\n for prop, val in (prop_dict).items():\n if not heat_client.resource_attr_support(res, prop):\n unsupported_props.update(prop_dict)\n if unsupported_props:\n unsupported_resource_props[res] = unsupported_props\n self.unsupported_props = unsupported_resource_props\n\n\n @log.log\n def _generate_hot_from_tosca(self, vnfd_dict, dev_attrs):\n\n parsed_params = {}\n if 'param_values' in dev_attrs and dev_attrs['param_values'] != \"\":\n try:\n parsed_params = yaml.safe_load(dev_attrs['param_values'])\n except Exception as e:\n LOG.debug(\"Params not Well Formed: %s\", str(e))\n raise vnfm.ParamYAMLNotWellFormed(error_msg_details=str(e))\n\n svcmonitoring_dict,vnfd_dicttemp = toscautils.get_vdu_servicemonitoring(vnfd_dict)\n toscautils.updateimports(vnfd_dicttemp)\n\n if 'substitution_mappings' in str(vnfd_dicttemp):\n toscautils.check_for_substitution_mappings(vnfd_dicttemp,\n parsed_params)\n\n try:\n tosca = tosca_template.ToscaTemplate(parsed_params=parsed_params,\n a_file=False,\n yaml_dict_tpl=vnfd_dicttemp)\n\n\n except Exception as e:\n LOG.debug(\"tosca-parser error: %s\", str(e))\n raise vnfm.ToscaParserFailed(error_msg_details=str(e))\n\n metadata = toscautils.get_vdu_metadata(tosca)\n monitoring_dict = toscautils.get_vdu_monitoring(tosca)\n\n mgmt_ports = toscautils.get_mgmt_ports(tosca)\n res_tpl = toscautils.get_resources_dict(tosca,self.STACK_FLAVOR_EXTRA)\n\n toscautils.post_process_template(tosca)\n\n try:\n translator = tosca_translator.TOSCATranslator(tosca,parsed_params)\n heat_template_yaml = translator.translate()\n\n except Exception as e:\n LOG.debug(\"heat-translator error: %s\", str(e))\n raise vnfm.HeatTranslatorFailed(error_msg_details=str(e))\n\n\n heat_template_yaml = toscautils.post_process_heat_template(\n heat_template_yaml, mgmt_ports, metadata,\n res_tpl, self.unsupported_props)\n\n self.heat_template_yaml = heat_template_yaml\n self.monitoring_dict = monitoring_dict\n self.svcmonitoring_dict = svcmonitoring_dict\n self.metadata = metadata\n @log.log\n def _generate_hot_scaling(self, vnfd_dict,\n scale_resource_type=\"OS::Nova::Server\"):\n # Initialize the template\n template_dict = yaml.safe_load(HEAT_TEMPLATE_BASE)\n template_dict['description'] = 'Tacker scaling template'\n\n parameters = {}\n template_dict['parameters'] = parameters\n\n # Add scaling related resource defs\n resources = {}\n scaling_group_names = {}\n # policies:\n # - SP1:\n # type: tosca.policies.tacker.Scaling\n if 'policies' in vnfd_dict:\n for policy_dict in vnfd_dict['policies']:\n name, policy = list(policy_dict.items())[0]\n if policy['type'] == SCALING_POLICY:\n resources, scaling_group_names =\\\n self._convert_to_heat_scaling_policy(\n policy['properties'], scale_resource_type, name)\n # TODO(kanagaraj-manickam) only one policy is supported\n # for all vdus. remove this break, once this limitation\n # is addressed.\n break\n\n template_dict['resources'] = resources\n\n # First return value helps to check if scaling resources exist\n return ((len(template_dict['resources']) > 0), scaling_group_names,\n template_dict)\n\n @log.log\n def _convert_to_heat_scaling_group(self, policy_prp, scale_resource_type,\n name):\n group_hot = {'type': 'OS::Heat::AutoScalingGroup'}\n properties = {}\n properties['min_size'] = policy_prp['min_instances']\n properties['max_size'] = policy_prp['max_instances']\n properties['desired_capacity'] = policy_prp['default_instances']\n properties['cooldown'] = policy_prp['cooldown']\n properties['resource'] = {}\n # TODO(kanagaraj-manickam) all VDU members are considered as 1\n # group now and make it to form the groups based on the VDU\n # list mentioned in the policy's targets\n # scale_resource_type is custome type mapped the HOT template\n # generated for all VDUs in the tosca template\n properties['resource']['type'] = scale_resource_type\n # TODO(kanagraj-manickam) add custom type params here, to\n # support parameterized template\n group_hot['properties'] = properties\n\n return group_hot\n\n # TODO(kanagaraj-manickam) now only one group is supported, so name\n # is hard-coded with G1\n @log.log\n def _get_scale_group_name(self, targets):\n return 'G1'\n\n # tosca policies\n #\n # properties:\n # adjust_by: 1\n # cooldown: 120\n # targets: [G1]\n @log.log\n def _convert_to_heat_scaling_policy(self, policy_prp, scale_resource_type,\n name):\n # Add scaling related resource defs\n resources = {}\n scaling_group_names = {}\n\n # Form the group\n scale_grp = self._get_scale_group_name(policy_prp['targets'])\n scaling_group_names[name] = scale_grp\n resources[scale_grp] = self._convert_to_heat_scaling_group(\n policy_prp, scale_resource_type, scale_grp)\n\n grp_id = {'get_resource': scale_grp}\n\n policy_hot = {'type': 'OS::Heat::ScalingPolicy'}\n properties = {}\n properties['adjustment_type'] = 'change_in_capacity'\n properties['cooldown'] = policy_prp['cooldown']\n properties['scaling_adjustment'] = policy_prp['increment']\n properties['auto_scaling_group_id'] = grp_id\n policy_hot['properties'] = properties\n\n # Add scale_out policy\n policy_rsc_name = get_scaling_policy_name(action='out',\n policy_name=name)\n resources[policy_rsc_name] = policy_hot\n\n # Add scale_in policy\n in_value = '-%d' % int(policy_prp['increment'])\n policy_hot_in = copy.deepcopy(policy_hot)\n policy_hot_in['properties']['scaling_adjustment'] = in_value\n policy_rsc_name = get_scaling_policy_name(action='in',\n policy_name=name)\n resources[policy_rsc_name] = policy_hot_in\n return resources, scaling_group_names\n\n @log.log\n def represent_odict(self, dump, tag, mapping, flow_style=None):\n value = []\n node = yaml.MappingNode(tag, value, flow_style=flow_style)\n if dump.alias_key is not None:\n dump.represented_objects[dump.alias_key] = node\n best_style = True\n if hasattr(mapping, 'items'):\n mapping = mapping.items()\n for item_key, item_value in mapping:\n node_key = dump.represent_data(item_key)\n node_value = dump.represent_data(item_value)\n if not (isinstance(node_key, yaml.ScalarNode)\n and not node_key.style):\n best_style = False\n if not (isinstance(node_value, yaml.ScalarNode)\n and not node_value.style):\n best_style = False\n value.append((node_key, node_value))\n if flow_style is None:\n if dump.default_flow_style is not None:\n node.flow_style = dump.default_flow_style\n else:\n node.flow_style = best_style\n return node\n\n @log.log\n def _generate_hot_alarm_resource(self, topology_tpl_dict):\n alarm_resource = dict()\n heat_tpl = self.heat_template_yaml\n heat_dict = yamlparser.simple_ordered_parse(heat_tpl)\n is_enabled_alarm = False\n\n if 'policies' in topology_tpl_dict:\n for policy_dict in topology_tpl_dict['policies']:\n name, policy_tpl_dict = list(policy_dict.items())[0]\n # need to parse triggers here: scaling in/out, respawn,...\n if policy_tpl_dict['type'] == \\\n 'tosca.policies.tacker.Alarming':\n is_enabled_alarm = True\n triggers = policy_tpl_dict['triggers']\n for trigger_name, trigger_dict in triggers.items():\n alarm_resource[trigger_name] =\\\n self._convert_to_heat_monitoring_resource({\n trigger_name: trigger_dict}, self.vnf)\n heat_dict['resources'].update(alarm_resource)\n\n yaml.SafeDumper.add_representer(OrderedDict,\n lambda dumper, value: self.represent_odict(dumper,\n u'tag:yaml.org,2002:map', value))\n heat_tpl_yaml = yaml.safe_dump(heat_dict)\n return (is_enabled_alarm,\n alarm_resource,\n heat_tpl_yaml\n )\n\n def _convert_to_heat_monitoring_resource(self, mon_policy, vnf):\n mon_policy_hot = {'type': 'OS::Aodh::Alarm'}\n mon_policy_hot['properties'] = \\\n self._convert_to_heat_monitoring_prop(mon_policy, vnf)\n return mon_policy_hot\n\n def _convert_to_heat_monitoring_prop(self, mon_policy, vnf):\n metadata = self.metadata\n trigger_name, trigger_dict = list(mon_policy.items())[0]\n tpl_condition = trigger_dict['condition']\n properties = dict()\n if not (trigger_dict.get('metadata') and metadata):\n raise vnfm.MetadataNotMatched()\n matching_metadata_dict = dict()\n properties['meter_name'] = trigger_dict['metrics']\n is_matched = False\n for vdu_name, metadata_dict in metadata['vdus'].items():\n if trigger_dict['metadata'] ==\\\n metadata_dict['metering.vnf']:\n is_matched = True\n if not is_matched:\n raise vnfm.MetadataNotMatched()\n matching_metadata_dict['metadata.user_metadata.vnf'] =\\\n trigger_dict['metadata']\n properties['matching_metadata'] = \\\n matching_metadata_dict\n properties['comparison_operator'] = \\\n tpl_condition['comparison_operator']\n properties['period'] = tpl_condition['period']\n properties['evaluation_periods'] = tpl_condition['evaluations']\n properties['statistic'] = tpl_condition['method']\n properties['description'] = tpl_condition['constraint']\n properties['threshold'] = tpl_condition['threshold']\n # alarm url process here\n alarm_url = vnf['attributes'].get(trigger_name)\n if alarm_url:\n alarm_url = str(alarm_url)\n LOG.debug('Alarm url in heat %s', alarm_url)\n properties['alarm_actions'] = [alarm_url]\n return properties\n","sub_path":"vnfm/infra_drivers/openstack/translate_template.py","file_name":"translate_template.py","file_ext":"py","file_size_in_byte":22004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"88738303","text":"import sys\n\ndef get_test_data(path):\n with open(path) as f:\n content = f.readlines()\n return content\n\n def n_not_anagrams(words):\n \"\"\"\n Return the number of strings in `words` that are not anagrams\n of another string in `words`.\n \"\"\"\n anagrams = set()\n not_yet_anagrams = set()\n for word in words[1:]:\n sorted_word = \"\".join(sorted(word.rstrip()))\n if sorted_word in not_yet_anagrams:\n not_yet_anagrams.remove(sorted_word)\n anagrams.add(sorted_word)\n elif sorted_word not in anagrams:\n not_yet_anagrams.add(sorted_word)\n return len(not_yet_anagrams)\n\n# data = sys.stdin.readlines()\ndata = get_test_data(\"kattis_stuff/utah.anagram/test/test2.in\")\n# n_words, n_letters = data[0].split()\nprint(n_not_anagrams(data))\n","sub_path":"algorithms/anagram/anaga.py","file_name":"anaga.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"172785738","text":"from django.contrib import admin\nfrom .models import Order\nfrom FadeApp.AppUsers.models import AppUser\n\n# Register your models here.\n\nclass OrderModelAdmin(admin.ModelAdmin):\n\tlist_display = [\"order_id\", \"order_time\", \"order_products\",\"service_amont\" , \\\n\t\"tax_amount\", \"tip_amount\", \"total_amount\", \"order_status\", \\\n\t\"order_received_by\"]\n\t# probably need to delete last two(generate by default)\n\tlist_editable = [\"order_status\"]\n\n\tclass Meta:\n\t\tmodel = Order\n\nadmin.site.register(Order,OrderModelAdmin)","sub_path":"FadeApp/orders/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"136665228","text":"TEXT = \"\\\nCopyright (c) 2015, Mark Walter Ruszczycky\\n\\\nAll rights reserved.\\n\\\n\\n\\\nRedistribution and use in source and binary forms, with or without\\n\\\nmodification, are permitted provided that the following conditions\\n\\\nare met:\\n\\\n\\n\\\n 1. Redistributions of source code must retain the above\\n\\\n copyright notice, this list of conditions and the\\n\\\n following disclaimer.\\n\\\n\\n\\\n 2. Redistributions in binary form must reproduce the above\\n\\\n copyright notice, this list of conditions and the following\\n\\\n disclaimer in the documentation and/or other materials\\n\\\n provided with the distribution.\\n\\\n\\n\\\n 3. Neither the name of the copyright holder nor the names of its\\n\\\n contributors may be used to endorse or promote products\\n\\\n derived from this software without specific prior written\\n\\\n permission.\\n\\\n\\n\\\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\\n\\\n'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\\n\\\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\\n\\\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\\n\\\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\\n\\\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\\n\\\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\\n\\\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\\n\\\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\\n\\\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\\n\\\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\\n\"\n","sub_path":"moonsim/resources/license.py","file_name":"license.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631744332","text":"\r\ntabuada = int(input('Tabuada de: '))\r\ninicio = int(input('Comeca: '))\r\nfim = int(input('Fim: '))\r\nc = 1\r\nwhile c <= fim:\r\n produto = tabuada * inicio\r\n print('%.d X %.d = %.d' % (tabuada, inicio, produto))\r\n inicio += 1\r\n c += 1","sub_path":"lista05/lista05_lista01_questao36.py","file_name":"lista05_lista01_questao36.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"137776957","text":"import cv2\nimport numpy as np\nimport glob\nimport xml.etree.ElementTree as ET\nimport time\nimport random\nimport os\nimport sys\n\nbasedir = os.path.dirname(__file__)\nsys.path.append(os.path.abspath(os.path.join(\n basedir,\n os.path.pardir,\n os.path.pardir,\n os.path.pardir)))\n\nfrom Appearance.utils import drawing\n\nDEBUG = False\n\nos.environ['CUDA_VISIBLE_DEVICES'] = str(1)\n\n\ndef main(label_type, time_gap=1, min_size=2000):\n np.set_printoptions(suppress=True)\n np.set_printoptions(precision=4)\n\n wildcard = '/*/' if label_type == 'train' else '/*/'\n dataset_path = '/media/msis_dasol/1TB/dataset/vehicle_identification_without_background/'\n\n if not os.path.exists(os.path.join('labels', label_type)):\n os.makedirs(os.path.join('labels', label_type))\n imageNameFile = open('labels/' + label_type + '/image_names.txt', 'w')\n labelFile = open('labels/' + label_type + '/labels.txt', 'w')\n\n # classes\n class_list = os.listdir(dataset_path)\n\n last_frame = 0\n totalImages = len(glob.glob(dataset_path + wildcard + '*.png')) + len(glob.glob(dataset_path + wildcard + '*.jpg'))\n\n print('totalImages', totalImages)\n\n bboxes = []\n imageSeq = {}\n\n # Load dataset\n print('Load label data...')\n for vv, class_name in enumerate(class_list):\n\n image_path = dataset_path + class_name + '/'\n images = sorted(glob.glob(image_path + '*.png')) + sorted(glob.glob(image_path + '*.jpg'))\n\n if vv != 0:\n last_frame = last_frame + 1\n\n\n\n # save image names\n for idx, name in enumerate(images):\n imageNameFile.write(name + '\\n')\n imageSeq[name] = last_frame + idx\n\n bbox = [imageSeq[name], vv]\n bboxes.append(bbox)\n\n\n last_frame = last_frame + len(images) -1\n\n bboxes = np.array(bboxes)\n\n # [video_id, main_img_seq, pos_img_seq, main_track_id, neg_track_id, main_x1, main_y1, main_x2, main_y2, pos_x1, pos_y1, pos_x2, pos_y2, neg_x1, neg_y1, neg_x2, neg_y2]\n\n # Reorder by video_id, then track_id, then video image number so all labels for a single track are next to each other.\n # This only matters if a single image could have multiple tracks.\n # order = np.lexsort((bboxes[:,0], bboxes[:,3], bboxes[:,2]))\n # bboxes = bboxes[order,:]\n\n # for i in bboxes:\n # print(i)\n if not DEBUG:\n np.save('labels/' + label_type + '/labels.npy', bboxes)\n np.savetxt('labels/' + label_type + '/labels.txt', bboxes)\n\nif __name__ == '__main__':\n main('train')\n #main('val')\n\n","sub_path":"vehicle_tracking/Appearance/datasets/vehicle_identification/make_label_file.py","file_name":"make_label_file.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"235478054","text":"import typing\n\nfrom graphql import format_error, GraphQLSchema, graphql\nfrom starlette import status\nfrom starlette.applications import Starlette\nfrom starlette.background import BackgroundTasks\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, PlainTextResponse, Response\nfrom starlette.routing import BaseRoute, Route\nfrom starlette.types import Receive, Scope, Send\n\nfrom .playground import PLAYGROUND_HTML\n\n\n# from .schema import Schema\n\n\nclass GraphQL(Starlette):\n def __init__(self, schema: GraphQLSchema, playground: bool = True, debug: bool = False,\n routes: typing.List[BaseRoute] = None):\n routes = routes or []\n routes.append(Route('/graphql/', GraphQLApp(schema, playground=playground)))\n super().__init__(debug=debug, routes=routes)\n\n\nclass GraphQLApp:\n def __init__(\n self,\n schema: GraphQLSchema,\n playground: bool = True\n ) -> None:\n self.schema = schema\n self.playground = playground\n\n async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:\n request = Request(scope, receive=receive)\n response = await self.handle_graphql(request)\n await response(scope, receive, send)\n\n async def handle_graphql(self, request: Request) -> Response:\n if request.method in (\"GET\", \"HEAD\"):\n if \"text/html\" in request.headers.get(\"Accept\", \"\"):\n if not self.playground:\n return PlainTextResponse(\n \"Not Found\", status_code=status.HTTP_404_NOT_FOUND\n )\n return HTMLResponse(PLAYGROUND_HTML)\n\n data = request.query_params # type: typing.Mapping[str, typing.Any]\n\n elif request.method == \"POST\":\n content_type = request.headers.get(\"Content-Type\", \"\")\n\n if \"application/json\" in content_type:\n data = await request.json()\n elif \"application/graphql\" in content_type:\n body = await request.body()\n text = body.decode()\n data = {\"query\": text}\n elif \"query\" in request.query_params:\n data = request.query_params\n else:\n return PlainTextResponse(\n \"Unsupported Media Type\",\n status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,\n )\n\n else:\n return PlainTextResponse(\n \"Method Not Allowed\", status_code=status.HTTP_405_METHOD_NOT_ALLOWED\n )\n\n try:\n query = data[\"query\"]\n variables = data.get(\"variables\")\n operation_name = data.get(\"operationName\")\n except KeyError:\n return PlainTextResponse(\n \"No GraphQL query found in the request\",\n status_code=status.HTTP_400_BAD_REQUEST,\n )\n\n background = BackgroundTasks()\n context = {\"request\": request, \"background\": background}\n\n result = await graphql(\n self.schema,\n query,\n variable_values=variables,\n operation_name=operation_name,\n context_value=context,\n )\n error_data = (\n [format_error(err) for err in result.errors]\n if result.errors\n else None\n )\n response_data = {\"data\": result.data, \"errors\": error_data}\n status_code = (\n status.HTTP_400_BAD_REQUEST if result.errors else status.HTTP_200_OK\n )\n\n return JSONResponse(\n response_data, status_code=status_code, background=background\n )\n","sub_path":"gql/asgi.py","file_name":"asgi.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"348577680","text":"import krpc\r\nimport time\r\nimport mission\r\nfrom peg import *\r\n\r\ndef SetAllEngineGimbalLocked(vessel,IsLocked):\r\n if vessel==None:\r\n return None\r\n parts=vessel.parts.engines\r\n if parts==None:\r\n return None\r\n for i in parts:\r\n if i.gimballed==True:\r\n i.gimbal_locked= IsLocked \r\n\r\nconn = krpc.connect(name='test')\r\nvessel = conn.space_center.active_vessel\r\nSetAllEngineGimbalLocked(vessel,False)\r\nbody=vessel.orbit.body\r\nreference_frame=body.non_rotating_reference_frame\r\n\r\nlead_time=7651776.534758-3600\r\ntarget_pe=150000.00000001490000000+6371000\r\ntarget_ap= 416392613.35923040000000000+6371000\r\ntarget_lan=math.radians(0.59637608190271463)\r\ntarget_inc=math.radians(28.5)\r\ntarget_aop=math.radians(164.59591855330967000)\r\nturn_angle=4.0\r\ntarget_normal_vector=target_normal_vector(conn,body,target_inc,target_lan,reference_frame)\r\n\r\n#conn.space_center.warp_to(lead_time)\r\n'''\r\nposition=conn.add_stream(vessel.position,reference_frame)\r\nvelocity=conn.add_stream(vessel.velocity,reference_frame)\r\naltitude = conn.add_stream(getattr, vessel.flight(), 'mean_altitude')\r\nspeed=conn.add_stream(getattr, vessel.flight(reference_frame), 'speed')\r\nhorizontal_speed=conn.add_stream(getattr, vessel.flight(body.reference_frame), 'horizontal_speed')\r\nvertical_speed=conn.add_stream(getattr, vessel.flight(body.reference_frame), 'vertical_speed')\r\n'''\r\npeg=pegas(conn)\r\npeg.set_ref_target(target_pe,target_ap,target_inc,target_lan,target_aop)\r\npeg.update_stages()\r\npeg.vehicle_info()\r\ninput()\r\nwarp_to_launch(conn,target_inc,target_lan,False)\r\n\r\npitch=90\r\nyaw=math.degrees(target_heading(vessel,target_normal_vector,reference_frame))\r\nvessel.auto_pilot.engage()\r\nvessel.auto_pilot.time_to_peak=(6,6,6)\r\nvessel.auto_pilot.stopping_time=(0.2,0.2,0.2)\r\nvessel.auto_pilot.attenuation_angle=(0.2,0.5,0.2)\r\nvessel.auto_pilot.reference_frame=reference_frame\r\nvessel.auto_pilot.shutdown_speed=3e8\r\nvessel.auto_pilot.max_acceleration(4.5*9.8067)\r\nvessel.auto_pilot.target_pitch=pitch\r\nvessel.auto_pilot.target_roll=math.nan\r\nvessel.control.rcs=False\r\n''\r\n#vessel.auto_pilot.target_pitch=90\r\n#vessel.auto_pilot.attenuation_angle=(0.2,0.2,0.2)\r\n\r\nfair_droped=False\r\nstage_one_droped=False\r\nsediment=False\r\n#fair_droped=True\r\n#stage_one_droped=True\r\ncountdown=10\r\nwhile countdown>0:\r\n if countdown==6:\r\n print('ingition!')\r\n vessel.control.throttle = 1.0\r\n vessel.control.activate_next_stage()\r\n else:\r\n print(countdown)\r\n countdown=countdown-1\r\n time.sleep(1)\r\n\r\nprint('lift off')\r\nvessel.control.activate_next_stage()\r\n\r\nturn_start_altitude = vessel.flight().mean_altitude+50\r\nwhile vessel.flight().mean_altitude10:\r\n py=peg.update()\r\n else:\r\n py=peg.slerp()\r\n if py!=None:\r\n pitch=py[0]\r\n yaw=py[1]\r\n tgo=peg.time_to_go()\r\n time_to_stage=peg.time_to_stage()\r\n rd=peg.rd_position()\r\n print('tgo:%f pitch:%f yaw:%f acc:%f time_to_stage:%f pos: %f %f'%(tgo,math.degrees(pitch),math.degrees(yaw),acc,time_to_stage,rd[0],rd[1]),end='\\r')\r\n\r\n #print('tgo',tgo)\r\n #print('py',py)\r\n vessel.auto_pilot.target_pitch_and_heading(math.degrees(pitch),math.degrees(yaw)) \r\n if fair_droped==False and vessel.flight().mean_altitude>100000:\r\n fair_droped=True\r\n vessel.control.activate_next_stage()\r\n time.sleep(0.5)\r\n peg.update_stages()\r\n\r\n if time_to_stage<1.0:\r\n if stage_one_droped==False:\r\n stage_one_droped=True\r\n vessel.control.rcs=True\r\n vessel.control.activate_next_stage()\r\n time.sleep(2.0)\r\n vessel.control.activate_next_stage()\r\n for i in range(20):\r\n peg.update()\r\n else:\r\n stage_one_droped=False\r\n \r\n if acc<1:\r\n if sediment==False:\r\n vessel.control.forward=1.0\r\n vessel.auto_pilot.stopping_time=(300,0.1,300)\r\n sediment=True\r\n else:\r\n if sediment==True:\r\n vessel.auto_pilot.stopping_time=(0.1,0.1,0.1)\r\n vessel.control.forward=0.0\r\n sediment=False\r\n if tgo<0.2:\r\n vessel.auto_pilot.shutdown_speed=0\r\n vessel.control.throttle = 0.0\r\n break\r\n if vessel.orbit.apoapsis>target_ap:\r\n vessel.auto_pilot.shutdown_speed=0\r\n vessel.control.throttle = 0.0\r\n break\r\nvessel.control.rcs=False\r\nSetAllEngineGimbalLocked(vessel,True)\r\ntime.sleep(1)\r\ntime.sleep(1)\r\ninput()\r\nvessel.auto_pilot.disengage()\r\n\r\n","sub_path":"launch_moon.py","file_name":"launch_moon.py","file_ext":"py","file_size_in_byte":5680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"260481546","text":"\"\"\"\nAmazon rainforest convolutional neural network on satellite data.\n\nA program to train a convolutional neural network on the\nAmazon Rainforest satellite data as part of a kaggle competition.\nThis one uses a generator.\nThe model used is the Inception v3 model provided with Keras and the\nmanner in which it is fine tuned here follows the instructions on the\nKeras applications website: https://keras.io/applications/#inceptionv3\n\"\"\"\n\nfrom __future__ import print_function\nimport os\nimport sys\n\nimport numpy as np\nfrom sklearn.metrics import fbeta_score\n\nimport keras\nimport tensorflow as tf\nimport time\n\nfrom models import CallbackDefs\nfrom models import Inception3\nfrom utilities import LoadData\nfrom utilities import Optimisations as Opt\n\n# ----------------------------------------------------------\n# Set run details\n# ----------------------------------------------------------\nJOB_ID = '002'\n\nif len(sys.argv) > 1:\n fold_no = int(sys.argv[1])\nelse:\n fold_no = 0\nprint(\"Fold number \", fold_no)\nGPU = False\n\n# For GPU jobs\nif GPU:\n try:\n JOB_ID = os.environ['JOB_ID']\n except:\n sys.exit('Error: Set the JOB_ID\"')\n\n\n# Define where results will be stored\nfolder = 'train-forest-Inception-%s' % JOB_ID\nwhile os.path.exists(folder):\n JOB_ID = JOB_ID + '_1'\n folder = 'train-forest-Inception-%s' % JOB_ID\nfolder = folder + '/fold_' + str(fold_no)\nos.makedirs(folder)\nprint(\"Writing results to \", folder)\n\n# ----------------------------------------------------------\n# Load data, select what to use\n# ----------------------------------------------------------\n\nKAGGLE_ROOT = os.path.abspath(\"input/\")\nKAGGLE_JPEG_DIR = os.path.join(KAGGLE_ROOT, 'train-jpg')\nKAGGLE_LABEL_CSV = os.path.join(KAGGLE_ROOT, 'train_v2.csv')\n\nprint(\"Loading labels\")\nall_train_labels = LoadData.load_labels(KAGGLE_LABEL_CSV)\nunique_label_list = LoadData.get_unique_labels(all_train_labels)\nall_train_labels = LoadData.do_one_hot_encoding(all_train_labels,\n unique_label_list)\n\nprint(\"Creating list of filenames\")\njpg_list = all_train_labels['image_name'].tolist()\njpg_list = [os.path.join(KAGGLE_JPEG_DIR, jpg_name + '.jpg')\n for jpg_name in jpg_list]\n\n# Define the training and validation sets\n# Full set = 40479\nn_total = len(jpg_list)\n\n\n# The k-fold validation is done manually in this way so that different folds\n# can be run concurrently, the results are later combined using\n# AmazonRainforestPredictions.\nvalid_start = fold_no * 4048\nvalid_end = (fold_no + 1) * 4048\nif valid_end > n_total:\n valid_end = n_total\n\nprint(\"Fold \", fold_no, \" from \", valid_start, \" to \", valid_end)\n\nvalid_jpg_list = jpg_list[valid_start:valid_end]\ntrain_jpg_list = jpg_list\ndel train_jpg_list[valid_start:valid_end]\n\n# Remove filenames to just keep binary data\nfull_set_labels = all_train_labels.values[:, 2:]\n\nvalid_labels = full_set_labels[valid_start:valid_end, :]\ntrain_labels = full_set_labels\ntrain_labels = np.delete(train_labels,\n np.arange(valid_start, valid_end, 1), axis=0)\n\nprint(\"Size of training sample \", len(train_jpg_list))\nprint(\"Size of validation sample \", len(valid_jpg_list))\n\nprint(\"Size of training labels \", len(train_labels))\nprint(\"Size of validation labels \", len(valid_labels))\n\n# ----------------------------------------------------------\n# Set hyperparameters\n# ----------------------------------------------------------\n\nbatch_size = 64\n\nlearning_rate = 1E-3\nn_epochs = 10 # 10\ndecay_rate = learning_rate / n_epochs\n\ncallbacks_list = [CallbackDefs.get_csv_callback(folder),\n CallbackDefs.get_early_stopping_callback(3),\n CallbackDefs.get_best_weights_callback(folder),\n CallbackDefs.LearningRateTracker()]\n\nn_train_events = len(train_jpg_list)\nn_valid_events = len(valid_jpg_list)\n\ntrain_steps_per_epoch = np.floor(float(n_train_events) / batch_size)\nvalid_steps_per_epoch = np.floor(float(n_valid_events) / batch_size)\n\n# ----------------------------------------------------------\n# Second fit hyperparameters\n# ----------------------------------------------------------\n\nlearning_rate_2 = 1E-5\nn_epochs_2 = 30 # 30\ndecay_rate_2 = learning_rate_2 / n_epochs_2\n\n# ----------------------------------------------------------\n# Create generators\n# ----------------------------------------------------------\n\n# Training\ntrain_generator = LoadData.batch_generator(train_jpg_list,\n batch_size,\n channels=3,\n all_labels=train_labels)\n\n# Validation\nvalid_generator = LoadData.batch_generator(valid_jpg_list,\n batch_size,\n channels=3,\n all_labels=valid_labels)\n# Validation for predictions\n# Use a fresh validator so that it starts from the beginning of the sample\n# and it is easier to associate the correct labels\npredict_valid_generator = LoadData.batch_generator(valid_jpg_list,\n batch_size,\n channels=3,\n all_labels=valid_labels)\n\n# ----------------------------------------------------------\n# Start session\n# ----------------------------------------------------------\n\nprint(\"Starting session\")\n\nstart_time = time.time()\n\nif GPU:\n # GPU setup\n session_conf = tf.ConfigProto()\nelse:\n # Limit available CPU to one thread\n session_conf = tf.ConfigProto(intra_op_parallelism_threads=1,\n inter_op_parallelism_threads=1)\n\nkeras.backend.tensorflow_backend.set_session(tf.Session(config=session_conf))\n\n# ----------------------------------------------------------\n# Load and compile model\n# ----------------------------------------------------------\n\nbase_model, model = Inception3.get_models()\n\nprint(model.summary())\n\n# First: train only the top layers (which were randomly initialized)\n# i.e. freeze all convolutional InceptionV3 layers\nfor layer in base_model.layers:\n layer.trainable = False\n\n# Compile the model (should be done *after* setting layers to non-trainable)\nmodel.compile(loss='binary_crossentropy',\n optimizer=keras.optimizers.Adam(learning_rate, decay=decay_rate),\n metrics=['accuracy'])\n\n# ----------------------------------------------------------\n# Fit model\n# ----------------------------------------------------------\n\nprint(\"Fitting model...\")\n\n# Train the model on the new data for a few epochs\nmodel.fit_generator(train_generator,\n steps_per_epoch=train_steps_per_epoch,\n epochs=n_epochs,\n verbose=1,\n callbacks=callbacks_list,\n validation_data=valid_generator,\n validation_steps=valid_steps_per_epoch)\n\n# At this point, the top layers are well trained and we can start fine-tuning\n# convolutional layers from inception V3. We will freeze the bottom N layers\n# and train the remaining top layers.\n\n# Let's visualize layer names and layer indices to see how many layers\n# we should freeze:\nfor i, layer in enumerate(base_model.layers):\n print(i, layer.name)\n\n# We chose to train the top 2 inception blocks, i.e. we will freeze\n# the first 249 layers and unfreeze the rest:\nfor layer in model.layers[:249]:\n layer.trainable = False\nfor layer in model.layers[249:]:\n layer.trainable = True\n\n# ----------------------------------------------------------\n# Recompile and refit model\n# ----------------------------------------------------------\n\n# We need to recompile the model for these modifications to take effect\n# We use a low learning rate\nmodel.compile(loss='binary_crossentropy',\n optimizer=keras.optimizers.Adam(learning_rate_2,\n decay=decay_rate_2),\n metrics=['accuracy'])\n\n# We train our model again (this time fine-tuning the top 2 inception blocks\n# alongside the top Dense layers)\nmodel.fit_generator(train_generator,\n steps_per_epoch=train_steps_per_epoch,\n epochs=n_epochs_2,\n verbose=1,\n callbacks=callbacks_list,\n validation_data=valid_generator,\n validation_steps=valid_steps_per_epoch)\n\nmodel.save(folder + '/model.h5') # save final trained model\nprint(\"Running time\")\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n# ----------------------------------------------------------\n# Load best weights to make predictions on validation data\n# ----------------------------------------------------------\n\nweights_filepath = folder + '/weights.best.hdf5'\nmodel.load_weights(weights_filepath, by_name=False)\n\n# ----------------------------------------------------------\n# Make predictions on validation data\n# ----------------------------------------------------------\n\nprint(\"Making predictions\")\n\n# First predictions from the model as probabilities\nfull_p_preds = model.predict_generator(predict_valid_generator,\n valid_steps_per_epoch+1)\n# Truth must be same type to calculate score\nfull_trues = np.array(valid_labels, np.uint8)\n\n# Need to slice predictions because generator produces too many, wraps around\nfull_p_preds = full_p_preds[0:n_valid_events]\n\n# Choose the thresholds\nfull_thresholds = Opt.optimise_f2_thresholds(full_trues, full_p_preds)\nprint(\"Set of thresholds chosen: \", full_thresholds)\n\n# Predictions now for classes\nfull_preds_var = np.zeros_like(full_p_preds)\nfor i in range(17):\n full_preds_var[:, i] = (full_p_preds[:, i] >\n full_thresholds[i]).astype(np.int)\n\n# ----------------------------------------------------------\n# Evaluate model\n# ----------------------------------------------------------\n\nprint(\"Model performance (loss, accuracy)\")\nprint(\"Train: %.4f, %.4f\" % tuple(model.evaluate_generator(train_generator,\n train_steps_per_epoch)))\nprint(\"Valid: %.4f, %.4f\" % tuple(model.evaluate_generator(valid_generator,\n valid_steps_per_epoch)))\n\nscore = fbeta_score(full_trues, full_preds_var, beta=2, average='samples')\nprint(\"New f2 is : \", score)\n\n# ----------------------------------------------------------\n# Save all data\n# ----------------------------------------------------------\nnp.save(folder + '/preds.npy', full_p_preds, allow_pickle=False)\n\nnp.save(folder + '/trues.npy', full_trues, allow_pickle=False)\n\nfull_thresholds_np = np.array(full_thresholds)\nnp.save(folder + '/thresholds.npy', full_thresholds_np, allow_pickle=False)\n","sub_path":"AmazonRainforestRunner.py","file_name":"AmazonRainforestRunner.py","file_ext":"py","file_size_in_byte":10836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"174531729","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport shutil\nimport logging\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\ntry:\n import gdal\nexcept ModuleNotFoundError as e:\n from osgeo import gdal\nexcept ModuleNotFoundError:\n raise e\nimport rasterio\nimport numpy as np\nimport geopandas as gpd\nfrom shapely.ops import unary_union\nfrom retrying import retry\n\nfrom ost.helpers import raster as ras, vector as vec\n\nlogger = logging.getLogger(__name__)\n\n@retry(stop_max_attempt_number=3, wait_fixed=1)\ndef mt_layover_old(list_of_files, config_file):\n \"\"\"\n\n :param list_of_files:\n :param config_file:\n :return:\n \"\"\"\n\n # this is a godale thing\n with open(config_file) as file:\n config_dict = json.load(file)\n temp_dir = Path(config_dict['temp_dir'])\n update_extent = (\n config_dict['processing']['time-series_ARD']['apply_ls_mask']\n )\n\n target_dir = Path(list_of_files[0]).parent.parent.parent\n outfile = target_dir.joinpath(f'{target_dir.name}.ls_mask.tif')\n extent = target_dir.joinpath(f'{target_dir.name}.extent.gpkg')\n burst_dir = Path(outfile).parent\n burst = burst_dir.name\n\n logger.info(\n f'Creating common Layover/Shadow mask for track {target_dir.name}.'\n )\n\n with TemporaryDirectory(prefix=f'{temp_dir}/') as temp:\n\n # temp to Path object\n temp = Path(temp)\n\n # create path to temp file\n ls_layer = temp.joinpath(Path(outfile).name)\n\n # create a vrt-stack out of\n vrt_options = gdal.BuildVRTOptions(srcNodata=0, separate=True)\n gdal.BuildVRT(\n str(temp.joinpath('ls.vrt')),\n list_of_files,\n options=vrt_options\n )\n\n with rasterio.open(temp.joinpath('ls.vrt')) as src:\n\n # get metadata\n meta = src.meta\n # update driver and reduced band count\n meta.update(driver='GTiff', count=1, dtype='uint8')\n\n # create outfiles\n with rasterio.open(ls_layer, 'w', **meta) as out_min:\n\n # loop through blocks\n for _, window in src.block_windows(1):\n\n # read array with all bands\n stack = src.read(range(1, src.count + 1), window=window)\n\n # get stats\n arr_max = np.nanmax(stack, axis=0)\n arr = np.divide(arr_max, arr_max)\n\n out_min.write(np.uint8(arr), window=window, indexes=1)\n\n ras.mask_by_shape(\n ls_layer, outfile, extent, to_db=False,\n datatype='uint8', rescale=False, ndv=0\n )\n\n ls_layer.unlink()\n\n extent_ls_masked = None\n if update_extent:\n\n logger.info(\n 'Calculating symmetrical difference of extent and ls_mask'\n )\n\n # polygonize the multi-temporal ls mask\n ras.polygonize_raster(outfile, f'{str(outfile)[:-4]}.gpkg')\n\n # create file for masked extent\n extent_ls_masked = burst_dir.joinpath(\n f'{burst}.extent.masked.gpkg'\n )\n\n # calculate difference between burst extent\n # and ls mask, for masked extent\n try:\n vec.difference(\n extent, f'{outfile.stem}.gpkg', extent_ls_masked\n )\n except:\n shutil.copy(extent, extent_ls_masked)\n\n return burst_dir, list_of_files, outfile, extent_ls_masked\n\n@retry(stop_max_attempt_number=3, wait_fixed=1)\ndef mt_layover(list_of_ls):\n\n import warnings\n warnings.filterwarnings('ignore', 'GeoSeries.isna', UserWarning)\n\n target_dir = Path(list_of_ls[0]).parent.parent.parent\n bounds = target_dir.joinpath(f'{target_dir.name}.min_bounds.json')\n outfile = target_dir.joinpath(f'{target_dir.name}.ls_mask.json')\n valid_file = target_dir.joinpath(f'{target_dir.name}.valid.json')\n\n logger.info(\n f'Creating common Layover/Shadow mask for track {target_dir.name}.'\n )\n\n for i, file in enumerate(list_of_ls):\n\n if i == 0:\n df1 = gpd.read_file(file)\n df1 = df1[~(df1.geometry.is_empty | df1.geometry.isna())]\n geom = df1.geometry.buffer(0).unary_union\n\n if i > 0:\n\n df2 = gpd.read_file(file)\n df2 = df2[~(df2.geometry.is_empty | df2.geometry.isna())]\n geom2 = df2.geometry.buffer(0).unary_union\n geom = unary_union([geom, geom2])\n\n # make geometry valid in case it isn't\n geom = geom.buffer(0)\n\n # remove slivers\n buffer = 0.00001\n geom = geom.buffer(\n -buffer, 1, join_style=2\n ).buffer(\n buffer, 1, cap_style=1, join_style=2\n ).__geo_interface__\n\n # write to output\n with open(outfile, 'w') as file:\n json.dump(geom, file)\n\n # create difference file for valid data shape\n vec.difference(bounds, outfile, valid_file)\n","sub_path":"ost/generic/ts_ls_mask.py","file_name":"ts_ls_mask.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"253754676","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2016-2018, Eric Jacob \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\nANSIBLE_METADATA = {\n 'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'\n}\n\nDOCUMENTATION = '''\n---\nmodule: f5bigip_util_clientssl_ciphers\nshort_description: BIG-IP util client ssl ciphers module\ndescription:\n - Shows all ciphers that match the given cipher string.\nversion_added: \"2.4\"\nauthor:\n - \"Gabriel Fortin (@GabrielFortin)\"\n - \"Eric Jacob (@erjac77)\"\noptions:\n cipher_string:\n description:\n - Specifies the cipher string.\n required: true\nrequirements:\n - BIG-IP >= 12.0\n - ansible-common-f5\n - f5-sdk\n'''\n\nEXAMPLES = '''\n- name: Returns all ciphers matching the specified cipher string\n f5bigip_util_clientssl_ciphers:\n f5_hostname: 172.16.227.35\n f5_username: admin\n f5_password: admin\n f5_port: 443\n cipher_string: 'DEFAULT'\n delegate_to: localhost\n'''\n\nRETURN = '''\nstdout:\n description: The output of the command.\n returned: success\n type: list\n sample:\n - ['...', '...']\nstdout_lines:\n description: A list of strings, each containing one item per line from the original output.\n returned: success\n type: list\n sample:\n - [['...', '...'], ['...'], ['...']]\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible_common_f5.base import AnsibleF5Error\nfrom ansible_common_f5.base import F5_PROVIDER_ARGS\nfrom ansible_common_f5.bigip import F5BigIpUnnamedObject\nfrom ansible_common_f5.utils import to_lines\n\n\nclass ModuleParams(object):\n @property\n def argument_spec(self):\n argument_spec = dict(\n cipher_string=dict(type='str', required=True)\n )\n argument_spec.update(F5_PROVIDER_ARGS)\n return argument_spec\n\n @property\n def supports_check_mode(self):\n return True\n\n\nclass F5BigIpUtilClientSslCiphers(F5BigIpUnnamedObject):\n def _set_crud_methods(self):\n self._methods = {\n 'run': self._api.tm.util.clientssl_ciphers.exec_cmd\n }\n\n def flush(self):\n result = dict(changed=False, stdout=list())\n\n try:\n output = self._methods['run']('run', utilCmdArgs=self._params['cipherString'])\n # result['changed'] = True\n except Exception:\n raise AnsibleF5Error(\"Could not execute the Client SSL Ciphers command.\")\n\n if hasattr(output, 'commandResult'):\n result['stdout'].append(str(output.commandResult))\n result['stdout_lines'] = list(to_lines(result['stdout']))\n\n return result\n\n\ndef main():\n params = ModuleParams()\n module = AnsibleModule(argument_spec=params.argument_spec, supports_check_mode=params.supports_check_mode)\n\n try:\n obj = F5BigIpUtilClientSslCiphers(check_mode=module.check_mode, **module.params)\n result = obj.flush()\n module.exit_json(**result)\n except Exception as exc:\n module.fail_json(msg=str(exc))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/f5bigip_util_clientssl_ciphers.py","file_name":"f5bigip_util_clientssl_ciphers.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"489695245","text":"\nfrom common.objects import BaseObj\nfrom order_service.api import *\n \n\nclass MemberLevelListObj(BaseOrder):\n \"\"\"api controller obj\"\"\"\n def __init__(self, **kwargs):\n super(MemberLevelListObj, self).__init__()\n self.info = \"查询所有会员等级\"\n self.uri = \"/memberLevel/list\"\n self.method = \"get\"\n self.body = self.Body(**kwargs)\n self.resp = self.Resp()\n \n class Body(BaseObj):\n def __init__(self, **kwargs):\n self.defaultStatus = None\n BaseObj.__init__(self, **kwargs)\n \n class Resp(object):\n def __init__(self):\n super(MemberLevelListObj.Resp, self).__init__()\n self.code = None # None\n self.data = [self.UmsMemberLevel()] # None\n self.message = None # None\n \n class UmsMemberLevel(object):\n \"\"\"None\"\"\"\n def __init__(self):\n self.commentGrowthPoint = None # 每次评价获取的成长值\n self.defaultStatus = None # 是否为默认等级:0->不是;1->是\n self.freeFreightPoint = None # 免运费标准\n self.growthPoint = None # None\n self.id = None # None\n self.name = None # None\n self.note = None # None\n self.priviledgeBirthday = None # 是否有生日特权\n self.priviledgeComment = None # 是否有评论获奖励特权\n self.priviledgeFreeFreight = None # 是否有免邮特权\n self.priviledgeMemberPrice = None # 是否有会员价格特权\n self.priviledgePromotion = None # 是否有专享活动特权\n self.priviledgeSignIn = None # 是否有签到特权\n \n","sub_path":"Python接口自动化/GWE_test/common/scripts/controller/UmsMemberLevelController/MemberLevelListObj.py","file_name":"MemberLevelListObj.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"630036527","text":"#!/usr/bin/env python3\n\n\"\"\" This module contains classes for manipulating HTML and converting HTML to plain text. \"\"\"\n\n# import modules.\nimport codecs\nimport logging\nimport os\nimport subprocess\nfrom bs4 import BeautifulSoup\nimport platform\n\nif platform.system() == \"Windows\":\n lynx_exec = \"C:\\Program Files (x86)\\lynx\\lynx.exe\"\n\nif platform.system() == \"Linux\":\n lynx_exec = \"lynx\"\n\n\nclass ModifyHTML():\n \"\"\" A class with tools to modify the HTML DOM via BeautifulSoup.\n \n Example:\n >>> html = open(\"sample.html\").read() # string.\n >>> html = ModifyHTML(html, \"html5lib\") #BeautifulSoup object.\n >>> html.shift_links()\n >>> html.remove_images()\n >>> html.raw() # string version of the HTML with shifted links and no images.\n \"\"\"\n\n\n def __init__(self, html, parser=\"html5lib\"):\n \"\"\" Sets instance attributes. \"\"\"\n\n # set logger; suppress logging by default. \n self.logger = logging.getLogger(__name__)\n self.logger.addHandler(logging.NullHandler())\n\n # compose BeautifulSoup object.\n self.root = BeautifulSoup(html, parser)\n\n\n def shift_links(self):\n \"\"\" Appends each A tag's @href value to the tag's text value if the @href value starts\n with \"http\" or \"https\", i.e. \"foo\" to \"foo [bar]\".\n\n Returns:\n None\n \"\"\"\n\n #self.logger.info(\"Shifting @href values to parent tags.\")\n\n # get all A tags.\n a_tags = self.root.find_all(\"a\")\n \n # append @href values to text values.\n for a_tag in a_tags:\n \n if a_tag.string is None:\n continue\n if \"href\" not in a_tag.attrs:\n continue\n \n # get @href; ignore non-http|https values. \n href = a_tag[\"href\"]\n if href[0:4].lower() == \"http\": # case insensitive.\n text = a_tag.string + \" [\" + href + \"]\" \n a_tag.string.replace_with(text)\n\n return\n\n\n def remove_images(self, preserve_alt=False):\n \"\"\" Removes image tags from DOM.\n\n Args:\n - preserve_alt (bool): If True, the \"alt\" attribute in the tag will be \n extracted and placed in a new and adjacent tag to preserve the attribute \n value.\n \n Returns:\n None\n \"\"\"\n \n #self.logger.info(\"Removing image tags.\")\n \n # get all image tags; remove them.\n img_tags = self.root.find_all(\"img\")\n for img_tag in img_tags:\n if preserve_alt:\n if \"alt\" in img_tag.attrs and img_tag[\"alt\"] != \"\":\n span = BeautifulSoup.new_tag(self.root, \"span\")\n span.string = \"[IMAGE: \" + img_tag[\"alt\"] + \"]\"\n img_tag.insert_after(span)\n img_tag.extract()\n\n return\n\n\n def raw(self):\n \"\"\" Returns string version of current DOM.\n \n Returns:\n str: The return value.\n \"\"\"\n\n self.logger.debug(\"Converting BeautifulSoup object to HTML string.\")\n strroot = str(self.root)\n return strroot\n\n\nclass HTMLToText():\n \"\"\" A class to convert HTML files OR strings to plain text via the Lynx browser.\n \n Examples:\n >>> h2t = HTMLToText()\n >>> h2t.text(\"sample.html\") # returns plain text version of \"sample.html\"\n >>> ht2.text(\"

    Hello World!

    \", is_raw=True)\n '\\nHello World!\\n\\n'\n \"\"\"\n \n def __init__(self, custom_options=None, temp_file=os.path.join(os.getcwd(), \"_tmp.html\")):\n \"\"\" Sets instance attributes.\n \n Args:\n - custom_options (dict): Custom Lynx options per: http://lynx.browser.org/lynx2.8.8/breakout/lynx_help/Lynx_users_guide.html#InteractiveOptions (Retrieved: April 2017).\n - temp_file (str): File in which to store raw HTML strings.\n \"\"\"\n\n # set logger; suppress logging by default. \n self.logger = logging.getLogger(__name__)\n self.logger.addHandler(logging.NullHandler())\n\n # set default options for Lynx.\n options = {\"nolist\":True, \"nomargins\":True, \"dump\":True}\n\n # add in custom options.\n if isinstance(custom_options, dict):\n for key, val in custom_options.items():\n options[key] = val\n self.options = options\n\n # set persistent temporary file name.\n self.temp_file = os.path.abspath(temp_file)\n\n\n def __del__(self):\n \"\"\" Trys to remove temporary file if it exists. Passes on permission error. \"\"\"\n\n if os.path.isfile(self.temp_file):\n try:\n self.logger.debug(\"Removing temporary HTML file: {}\".format(self.temp_file))\n os.remove(self.temp_file)\n except PermissionError:\n self.logger.warning(\"Unable to remove temporary file: {}\".format(\n self.temp_file))\n pass\n\n def text(self, html, is_raw=False, charset=\"utf-8\"):\n \"\"\" Converts HTML files OR strings to plain text string via the Lynx browser.\n\n Args:\n - html (str): The HTML file OR the raw HTML string to convert to text.\n - is_raw (bool): If True, @html is saved to self.temp_file prior to conversion.\n - charset (str): The encoding for the converted text.\n\n Returns:\n str: The return value.\n \"\"\"\n \n #self.logger.info(\"Converting HTML to plain text.\")\n\n # create beginning Lynx command line snippet.\n arg_options = [key for key, val in self.options.items() if val]\n args = []\n args.append(lynx_exec)\n for opt in arg_options:\n args.append(\"-{}\".format(opt))\n\n\n # if @is_raw == True, write @html to temporary file.\n # complete command line snippet.\n if is_raw:\n self.logger.debug(\n \"Writing HTML to temporary HTML file: {}\".format(self.temp_file))\n with codecs.open(self.temp_file, \"w\", encoding=charset) as tmp:\n tmp.write(html)\n #args += \" \" + self.temp_file\n args.append(self.temp_file)\n else:\n #args += \" \" + html\n args.append(html)\n\n # run Lynx.\n self.logger.debug(\"Converting HTML to text via: '{}'\".format(args))\n text = html\n try:\n cmd = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)\n text = cmd.stdout.decode(encoding=charset, errors=\"backslashreplace\")\n except FileNotFoundError as e:\n print(e)\n self.logger.error(e)\n self.logger.error(html)\n\n # return stdout.\n\n return text\n\n\nif __name__ == \"__main__\": \n pass\n\n","sub_path":"Servers/tomes_server/tomes_tool/lib/html_to_text.py","file_name":"html_to_text.py","file_ext":"py","file_size_in_byte":6814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"115541026","text":"from urllib.parse import urlencode\n\nfrom feedgen.feed import FeedGenerator\n\nfrom core.model import PodcastItem\nfrom core.options import GlobalOptions\nfrom core.plugin import Plugin\n\n\ndef render_feed(feed_id: str, plugin: Plugin, options: GlobalOptions, base_url: str):\n feed = plugin.get_feed(feed_id)\n fg = FeedGenerator()\n fg.load_extension('podcast')\n fg.title(feed.title)\n fg.description(feed.description)\n fg.link(href=feed.link, rel='alternate')\n fg.image(options.icon or feed.image)\n fg.id(feed.feed_id)\n for item in reversed(feed.items):\n fe = fg.add_entry()\n fe.id(item.item_id)\n fe.title(item.title)\n fe.description(item.description)\n fe.pubDate(item.date)\n fe.podcast.itunes_image(item.image)\n fe.enclosure(generate_url(item, plugin, options, base_url), item.content_length, item.content_type)\n return fg.rss_str(pretty=True) if options.format == 'rss' else fg.atom_str(pretty=True)\n\n\ndef generate_url(episode: PodcastItem, plugin: Plugin, options: GlobalOptions, base_url: str):\n if options.proxy_url:\n return f'{base_url}download?' + urlencode(options.dict() | plugin.options.dict() | {'id': episode.item_id})\n else:\n return plugin.get_item_url(episode.item_id)\n","sub_path":"core/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"181853454","text":"import re\nimport time\n\nimport requests\n\nurlprotocol = \"\"\n\n\n# 获取并检验要爬取的网站\ndef url_get():\n \"\"\"\n 找出url中的域名\n 比如从https://www.xiaogeng.top/article/page/id=3筛选出www.xiaogeng.top\n \"\"\"\n # url = input(\"please input the url:\")\n url = \"http://scce.ustb.edu.cn/\"\n try:\n kv = {'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/74.0.3729.131 Safari/537.36',\n 'Connection': 'close'}\n requests.get(url, headers=kv)\n return url\n except Exception:\n print(\"your url is incorrect!!\")\n return url_get()\n\n\ndef url_same(url):\n # 判断输入的网站使用的是https还是http\n urlprotocol = re.findall(r'.*(?=://)', url)[0]\n print('该站使用的协议是:' + urlprotocol)\n if len(re.findall(r'/', url)) > 2:\n if urlprotocol == 'https':\n sameurl = re.findall(r'(?<=https://).*?(?=/)', url)[0]\n else:\n sameurl = re.findall(r'(?<=http://).*?(?=/)', url)[0]\n else:\n url = url + '/'\n if urlprotocol == 'https':\n sameurl = re.findall(r'(?<=https://).*?(?=/)', url)[0]\n else:\n sameurl = re.findall(r'(?<=http://).*?(?=/)', url)[0]\n print('域名地址:' + sameurl)\n return urlprotocol + \"://\" + sameurl\n\n\n# 爬取url页面中的链接\ndef get_page_include_url(url):\n kv = {'user_agent': 'Mozilla/5.0'}\n downloadimages = \"\"\n try:\n r = requests.get(url, headers=kv)\n r.encoding = r.apparent_encoding\n pagetext = r.text\n pagelinks = re.findall(r'(?<=href=\").*?(?=\")|(?<=href=\\'). *?(?=\\')', pagetext)\n downloadimages = re.findall(r'(?<=src=\")(.+?\\.jpg|png)(?=\")|(?<=src=\\').*?(?=\\')', pagetext)\n except requests.exceptions.InvalidURL:\n pagelinks = \"\"\n print(\"Invalid URL \" + url)\n except requests.exceptions.ConnectionError:\n pagelinks = \"\"\n print(\"Connection Error \" + url)\n except Exception:\n pagelinks = \"\"\n print(str(Exception) + url)\n return pagelinks, downloadimages\n\n\n# 将一个列表写入文件\ndef write2file(url_list):\n file = open('urls.txt', 'w')\n for url in url_list:\n file.write(url + '\\n')\n file.close()\n\n\ndef write2images(url_list):\n file = open('images.txt', 'w')\n for url in url_list:\n file.write(url + '\\n')\n file.close()\n i = 0\n for imageUrl in url_list:\n # with open(re.search(r\".{4}.jpg|png\", imageUrl).group(), 'wb') as f:\n i += 1\n try:\n with open(str(i) + re.search(r\".jpg|png\", imageUrl).group(), 'wb') as f:\n images = requests.get(imageUrl)\n time.sleep(0.1)\n f.write(images.content)\n except requests.exceptions.InvalidURL:\n print(\"Invalid URL \" + imageUrl)\n except requests.exceptions.ConnectionError:\n print(\"Connection Error \" + imageUrl)\n except Exception:\n print(str(Exception) + imageUrl)\n\n\n# url集合,循环遍历会用到\nclass LinkQueue:\n def __init__(self):\n # 已访问的url集合\n self.visited = []\n # 待访问的url集合\n self.unvisited = []\n\n # 获取访问过的url队列\n def get_visited_url(self):\n return self.visited\n\n # 获取未访问的url队列\n def get_unvisited_url(self):\n return self.unvisited\n\n # 添加url到访问过得队列中\n def add_visited_url(self, url):\n return self.visited.append(url)\n\n # 移除访问过的url\n def remove_visited_url(self, url):\n return self.visited.remove(url)\n\n # 从未访问队列中取一个url\n def unvisited_url_dequeue(self):\n try:\n return self.unvisited.pop()\n except IndexError:\n return None\n\n # 添加url到未访问的队列中\n def add_unvisited_urllist(self, urllist):\n\n # 筛选pagelinks中的url\n def url_filtrate(pagelinks):\n \"\"\"\n print(\"我现在在筛选\")\n \"\"\"\n i = 0\n # 补全网址\n while i < len(pagelinks):\n if re.match('@', pagelinks[i]) is True:\n pagelinks[i] = \"\"\n elif re.match('tel:', pagelinks[i]) is True:\n pagelinks[i] = \"\"\n elif re.match('.+\\..+\\..+', pagelinks[i]) is None:\n pagelinks[i] = sameurl + pagelinks[i]\n i = i + 1\n # 去除不是该站点的url\n same_target_url = []\n for link in pagelinks:\n if re.findall(sameurl, link):\n same_target_url.append(link)\n # 去除重复url\n unrepect_url = []\n for link in same_target_url:\n if link not in unrepect_url:\n unrepect_url.append(link)\n return unrepect_url\n\n urllist = url_filtrate(urllist)\n for link in urllist:\n if link != \"\" and link not in self.visited and link not in self.unvisited:\n self.unvisited.append(link)\n return self.unvisited\n\n # 获得已访问的url数目\n\n def get_visited_url_count(self):\n return len(self.visited)\n\n # 获得未访问的url数目\n def get_unvisted_url_count(self):\n return len(self.unvisited)\n\n # 判断未访问的url队列是否为空\n def unvisited_url_empty(self):\n return len(self.unvisited) == 0\n\n\n# 真正的爬取函数\nclass Spider:\n linkQueue: LinkQueue\n imageQueue: LinkQueue\n\n def __init__(self, url):\n self.linkQueue = LinkQueue() # 引入linkQueue类\n self.imageQueue = LinkQueue()\n urllist = [url, ]\n self.linkQueue.add_unvisited_urllist(urllist) # 并将需要爬取的url添加进linkQueue对列中\n\n def crawler(self):\n # i = 10\n while not self.linkQueue.unvisited_url_empty(): # 若未访问队列非空\n # time.sleep(0.01)\n # print(\"嘀嘀嘀我又爬到一个\")\n # while i > 0:\n # i -= 1\n visited_url = self.linkQueue.unvisited_url_dequeue() # 取一个url\n if visited_url is None or visited_url == '':\n continue\n print(visited_url)\n initial_links, images_links = get_page_include_url(visited_url) # 爬出该url页面中所有的链接\n self.linkQueue.add_visited_url(visited_url) # 将该url放到访问过的url队列中\n self.linkQueue.add_unvisited_urllist(initial_links)\n self.imageQueue.add_unvisited_urllist(images_links)\n\n print(\"哥我爬完了\")\n return self.linkQueue.visited, self.imageQueue.unvisited\n\n\nif __name__ == '__main__':\n url = url_get()\n sameurl = url_same(url)\n spider = Spider(url)\n urlList, imageList = spider.crawler()\n write2file(urlList)\n write2images(imageList)\n","sub_path":"homework3-4/spiderPhoto.py","file_name":"spiderPhoto.py","file_ext":"py","file_size_in_byte":6967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"297948440","text":"import os\nimport logging\n\nimport weakref\nimport logzero\nfrom logzero import logger\nfrom connection_registry import ConnectionRegistry\nimport hashlib\nfrom exceptions import PubsubException, AlreadySubscribed\n\nlogzero.loglevel(logging.getLevelName(os.environ.get(\"log.level\")))\n\n\ndef subscribe(func):\n \"\"\"Decorator detect subscription object in result and subscribe connection\"\"\"\n\n def inner(self, *args, **kwargs):\n subs = func(self, *args, **kwargs)\n return Pubsub.subscribe(self.connection_ref(), subs)\n\n return inner\n\n\ndef unsubscribe(func):\n \"\"\"Decorator detect subscription object in result and subscribe connection\"\"\"\n\n def inner(self, *args, **kwargs):\n subs = func(self, *args, **kwargs)\n if isinstance(subs, Subscription):\n return Pubsub.unsubscribe(self.connection_ref(), subscribtion=subs)\n else:\n return Pubsub.unsubscribe(self.connection_ref(), key=subs)\n\n return inner\n\n\nclass Subscription(object):\n def __init__(self, event=None, **params):\n if hasattr(self, \"event\"):\n if event:\n raise Exception(\"Event name already defined in Subscription object\")\n else:\n if not event:\n raise Exception(\"Pass event in constructor\")\n else:\n self.event = event\n\n self.params = params\n self.connection_ref = None\n\n def process(self, *args, **kwargs):\n return args\n\n def get_key(self):\n \"\"\"This is an identifier for current subscription. It is sent to the\n client, so result should not contain any sensitive information\n \"\"\"\n\n return hashlib.md5(str((self.event, self.params))).hexdigest()\n\n def get_session(self):\n \"\"\"Connection session may be useful in filter or process functions\"\"\"\n\n return self.connection_ref().get_session()\n\n @classmethod\n def emit(cls, *args, **kwargs):\n \"\"\"Shortcut for emitting this event to all subscribers\"\"\"\n if not hasattr(cls, \"event\"):\n raise Exception(\"Subscription.emit() can be used only for subclasses with filled 'event' class variable\")\n return Pubsub.emit(cls.event, *args, **kwargs)\n\n def emit_single(self, *args, **kwargs):\n \"\"\"Perform emit of this event just for current subscriptions\"\"\"\n connection = self.connection_ref()\n\n if connection is None:\n # Connection is closed\n return\n\n payload = self.process(*args, **kwargs)\n if payload is None:\n if isinstance(payload, (tuple, list)):\n connection.writeJsonRequest(self.event, payload, is_notification=True)\n self.after_emit(*args, **kwargs)\n else:\n raise Exception(\"Return object from process() method must be list or None\")\n\n def after_emit(self, *args, **kwargs):\n pass\n\n def after_subscribe(self, *args, **kwargs):\n pass\n\n def __eq__(self, other):\n return isinstance(other, Subscription) and other.get_key() == self.get_key()\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n\nclass Pubsub(object):\n __subscriptions = {}\n\n @classmethod\n def subscribe(cls, connection, subscription):\n if connection is None:\n raise PubsubException(\"Subscriber not connected\")\n\n key = subscription.get_key()\n session = ConnectionRegistry.get_session(connection)\n\n if session is None:\n raise PubsubException(\"No session found\")\n\n subscription.connection_ref = weakref.ref(connection)\n session.setdefault(\"subscriptions\", {})\n\n if key in session[\"subscriptions\"]:\n raise AlreadySubscribed(\"This connection is already subscribed\")\n\n session[\"subscriptions\"][key] = subscription\n\n cls.__subscriptions.setdefault(subscription.event, weakref.WeakKeyDictionary())\n cls.__subscriptions[subscription.event][subscription] = None\n\n if hasattr(subscription, \"after_subscribe\"):\n if connection.on_finish is not None:\n # If subscription is processed during the request, wait to finish\n # and then process the callback\n connection.on_finish.addCallback(subscription.after_subscribe)\n else:\n # If subscription is not processed during the request, process callback\n # instantly\n subscription.after_subscribe(True)\n\n return ((subscription.event, key),)\n\n @classmethod\n def unsubscribe(cls, connection, subscription=None, key=None):\n if connection is None:\n raise PubsubException(\"Subscriber not connected\")\n\n session = ConnectionRegistry.get_session(connection)\n if session is None:\n raise PubsubException(\"No session found\")\n\n if subscription:\n key = subscription.get_key()\n\n try:\n # Subscription do not need to be remoived from cls.__subscriptions,\n # because it uses weak reference\n del session[\"subscriptions\"][key]\n except KeyError:\n logger.warning(\"Cannot remove subscriptions from connection session\")\n return False\n\n return True\n\n @classmethod\n def get_subscription_count(cls, event):\n return len(cls.__subscriptions.get(event, {}))\n\n @classmethod\n def get_subscription(cls, connection, event, key=None):\n \"\"\"Return subscription object for given connection and event\"\"\"\n session = ConnectionRegistry.get_session(connection)\n\n if session is None:\n raise PubsubException(\"No session found\")\n\n if key is None:\n sub = [sub for sub in session.get(\"subscriptions\", {}).values() if sub.event == event]\n\n try:\n return sub[0]\n except IndexError:\n raise PubsubException(f\"Not subscribed for event {event}\")\n\n @classmethod\n def iterate_subscribers(cls, event):\n for subscription in cls.__subscriptions.get(event, weakref.WeakKeyDictionary()).iterkeyrefs():\n subscription = subscription()\n if subscription is None:\n # subscriber is not connected\n continue\n yield subscription\n\n @classmethod\n def emit(cls, event, *args, **kwargs):\n for subscription in cls.iterate_subscribers(event):\n subscription.emit_single(*args, **kwargs)\n","sub_path":"stratum/pubsub.py","file_name":"pubsub.py","file_ext":"py","file_size_in_byte":6439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"407744122","text":"class Rules:\n @staticmethod\n def test_victory(board):\n '''\n Tests if the states it's a vitory\n and returns the label of who wins\n PS.: there's better way of implement, put evering into a single\n loop, but i prefer this way because it's more ditatic\n '''\n for line in board:\n if Rules.check_line(line):\n return line[0]\n\n for column in range(0, len(board)):\n column_ = []\n\n for line in board:\n column_.append(line[column])\n\n if Rules.check_line(column_):\n return column_[0]\n\n left_diagonal = []\n for line in board:\n left_diagonal.append(line[len(left_diagonal)])\n\n right_diagonal = [] \n for line in board:\n right_diagonal.append(line[-1 - len(right_diagonal)])\n\n if Rules.check_line(left_diagonal):\n return left_diagonal[0]\n if Rules.check_line(right_diagonal):\n return right_diagonal[0]\n\n return False\n\n @staticmethod\n def test_draw(board):\n if not Rules.test_victory(board):\n for line in board:\n if '' in line:\n return False\n return True\n return False\n\n def check_line(line):\n first = line[0]\n for item in line:\n if item != first or item == '':\n return False\n return True\n\n\n","sub_path":"tic_tac_toe/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"147808909","text":"m, n = map(int, input().split())\nmc, nc, d = map(int, input().split())\ncboard = [[0] * n for _ in range(m)]\nboard = [[int(x) for x in input().split()]for _ in range(m)]\n\ndx = [-1, 0, 1, 0]\ndy = [0, 1, 0, -1]\n\ndef turn_left():\n global d\n d -= 1\n if d == -1:\n d = 3\n\ncnt = 0\nturn_cnt = 0\nwhile True:\n turn_left()\n nx = mc + dx[d]\n ny = nc + dy[d]\n if board[nx][ny] == 0 and cboard[nx][ny] == 0:\n cboard[nx][ny] = 1\n cnt += 1\n mc = nx\n nc = ny\n turn_cnt = 0\n print(mc, nc)\n continue\n else:\n turn_cnt += 1\n if turn_cnt == 4:\n nx = mc - dx[d]\n ny = nc - dy[d]\n if board[nx][ny] == 0:\n mc = nx\n nc = ny\n else:\n break\n turn_cnt = 0\n\nprint(cnt)\n\n# 틀렸음\n'''나의 해결 : 손도 대지 못했다.'''\n'''해결 아이디어\n1. 간곳을 체크하기 위해 0으로 초기화 되어있는 똑같은 크기의 판을 따로 만든다(나는 원래 판에서 수정하려고 했다)\n2. 방향문제 같은 경우는 m과 n따로 배열로 정리해두는게 문제풀때 유용하다\n3. 왼쪽으로 회전하는 함수를 생성한다(-1씩 빼주면 다음 방향으로 간다, 단 북에서 서로갈때는 3이 나와야하므로 -1에서 3으로 수정해줘야 한다)\n4. 방문횟수와 회전횟수의 변수를 생성한후에 trun_left 함수를 호출함으로써 작업을 시작한다\n5. 방향에 해당하는 값을 더해줘서 0이면은 m,n초기화 및 cboard배열 초기화 cnt 증가 turn_cnt를 0으로 초기화하고 만약 바다이거나 이미 가본곳이면\nturn_cnt만 +1 해준다\n6. 만약 trun_cnt가 4라면(다돌았을때) 뒤로 가는데 만약 0이라면 뒤로감으로써 m,n을 초기화해주고 1이라면 break문을 걸어준다\nturn_cnt는 다시 0으로 초기화 된다'''","sub_path":"구현/게임 개발(실전).py","file_name":"게임 개발(실전).py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"564880080","text":"#!/usr/bin/python3\n\nimport sys\n\n# strip, default is whitespace characters\nn = int(input().strip())\n\narr = []\nfor i in range(n): \n a = [int(ele) for ele in input().strip().split(' ')] # syntax \n arr.append(a)\n\ndSum0 = 0\ndSum1 = 0\n\n# get diagonal sum\nfor i in range(n): \n dSum0 += arr[i][i]\n dSum1 += arr[i][n -1 -i]\n\nprint(abs(dSum0 - dSum1))\n","sub_path":"hackerrank/etc/digonal.diff.py","file_name":"digonal.diff.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"430499824","text":"import json\nimport os\nfrom bs4 import BeautifulSoup\nimport re\nimport requests\nfrom webob.compat import urlparse\n\n__author__ = 'moonkwonkim@gmail.com'\n# 출처: https://moonkwonkim.github.io/python/2017/11/07/url_parsing.html\n\n\nclass NaverFinanceNewsCrawler:\n URL_NAVER_FINANCE = \"http://finance.naver.com\"\n URL_NAVER_FINANCE_NEWS_QUERY = \"http://finance.naver.com/news/news_search.nhn?q=%s&x=0&y=0\" # params: query\n URL_NAVER_FINANCE_NEWS_CODE = \"http://finance.naver.com/item/news_news.nhn?code=%s&page=%s\" # params: (code, page)\n URL_NAVER_NEWS_FLASH = \"http://finance.naver.com/news/news_list.nhn?mode=LSS2D§ion_id=101§ion_id2=258\"\n URL_NAVER_STOCK_NOTICE = \"http://finance.naver.com/item/news_notice.nhn?code=%s&page=%s\" # params: (code, page)\n\n def __init__(self):\n pass\n\n def crawl(self, query=None, code=None, page=1):\n \"\"\"\n\n :param query:\n :param code:\n :param page:\n :return:\n \"\"\"\n if query:\n return self._crawl_by_query(query)\n elif code:\n return self._crawl_by_code(code, page=page)\n else:\n raise Exception(\"[Error] 'query' or 'code' should be entered.\")\n\n def _crawl_by_query(self, query):\n \"\"\"\n Crawl Naver Finance News\n :param query: string; search keywords\n :return: generator; [{title, summary, url, articleId, content, codes}, ...]\n \"\"\"\n\n # Convert the query to euc-kr string\n q = \"\"\n for c in query.encode('euc-kr'):\n q += \"%%%s\" % format(c, 'x').capitalize()\n\n r_url = NaverFinanceNewsCrawler.URL_NAVER_FINANCE_NEWS_QUERY % (q)\n r = requests.get(r_url)\n\n soup = BeautifulSoup(r.text, \"lxml\")\n news = soup.find('div', class_='newsSchResult').find('dl', class_='newsList')\n news_title = news.find_all('dt', class_='articleSubject')\n news_summary = news.find_all('dd', class_='articleSummary')\n for title, summary in zip(news_title, news_summary):\n url = NaverFinanceNewsCrawler.URL_NAVER_FINANCE + title.a.get(\"href\")\n res = {\n \"title\": title.a.text,\n \"summary\": summary.find(text=True).strip(' \\t\\n\\r'),\n \"url\": url,\n \"articleId\": urlparse.parse_qs(urlparse.urlparse(url).query)[\"article_id\"][0]\n }\n res.update(self._crawl_content(url))\n yield res\n\n def _crawl_by_code(self, code, page=1):\n \"\"\"\n Crawl Naver Stock News\n :param code: string; a stock code\n :return: generator;\n \"\"\"\n\n r_url = NaverFinanceNewsCrawler.URL_NAVER_FINANCE_NEWS_CODE % (code, page)\n r = requests.get(r_url)\n\n soup = BeautifulSoup(r.text, \"lxml\")\n news_rows = soup.find('table', class_='type2').find_all('td', class_='title')\n\n for row in news_rows:\n yield {\"title\": row.a.text.strip(' \\t\\n\\r'), \"url\": row.a.get('href')}\n\n def _crawl_content(self, url):\n r = requests.get(url)\n soup = BeautifulSoup(r.text, \"lxml\")\n content = soup.find('div', id=\"content\", class_='articleCont')\n codes = re.findall(r\"\\d{6}\", content.text)\n return {\"content\": content.text.strip(' \\t\\n\\r'), \"codes\": codes}\n\nif __name__ == \"__main__\":\n crawler = NaverFinanceNewsCrawler()\n docs = crawler.crawl(query='삼성전자')\n for i, d in enumerate(docs):\n print(\"{i}번째 문서\".format(i=i+1), end=\" \" + \"-\" * 50)\n print(\"-\" * 50)\n print(\"내용: {content}\".format(content=d[\"content\"]))\n print(\"문서에 포함된 종목 코드: {codes}\".format(codes=d[\"codes\"]))","sub_path":"naver_finance_news/naver_finance_news.py","file_name":"naver_finance_news.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"87447560","text":"#problema 2\ndef get_prim(p):\n '''Verifica daca numarul este prim\n :param :p intreg\n :return: 1 daca este prim sau 0 daca nu\n '''\n if p<2:\n return 0\n else:\n for div in range(2,p//2+1):\n if p%div==0:\n return 0\n return 1\n\n\ndef test_get_prim():\n assert get_prim(3)==1\n assert get_prim(6)==0\n\n\ndef get_longest_all_primes(lst):\n '''\n Determinarea secventa cea mai lunga cu prop ca nr sunt prime\n :param lst: lista de nr intregi\n :return: rez : lista care reprezinta secventa de lungime maxima\n cu prop ca nr sunt prime\n '''\n rez = [] # rezultatul final\n temp = [] # solutia curenta\n for x in lst: # foreach\n if get_prim(x)==1:\n temp.append(x)\n else:\n if (len(temp) > len(rez)):\n rez = temp[:]\n temp.clear()\n if (len(temp) > len(rez)):\n rez = temp[:]\n return rez\n\n\ndef test_get_longest_all_primes ():\n assert get_longest_all_primes([3, 5, 7, 9,11])==[3,5,7]\n assert get_longest_all_primes([3,11,13,12,11,11,11,13,13,13])==[11,11,11,13,13,13]\n\n\n#problema 13\ndef get_cif_prim(n):\n '''testeaza daca un numar este format doar din cifre prime\n :param: n numar intreg\n :return: 1 daca toate cifrele sunt prime si 0 in rest\n '''\n while n!=0:\n uc=n%10\n if get_prim(uc)==0:\n return 0\n\n n=n//10\n return 1\n\n\ndef test_get_cif_prim():\n assert get_cif_prim(12)==0\n assert get_cif_prim(123)==0\n assert get_cif_prim (1)==0\n assert get_cif_prim(357) == 1\n\n\ndef get_longest_prime_digits(lst):\n '''Determina secventa cea mai lunga cu proprietatea ca toate cifrele numerelor sunt prime\n :param: lst\n :return: rez :lista numerelor cu proprietatea anuntata mai sus\n '''\n rez = [] # rezultatul final\n temp = [] # solutia curenta\n for x in lst: # foreach\n if get_cif_prim(x)==1:\n temp.append(x)\n else:\n if (len(temp) > len(rez)):\n rez = temp[:]\n temp.clear()\n if (len(temp) > len(rez)):\n rez = temp[:]\n return rez\n\n\n\ndef test_get_longest_prime_digits():\n assert get_longest_prime_digits([23,235,35,4,12,35])==[23,235,35]\n assert get_longest_prime_digits([77,23,65,55])==[77,23]\n\n\n#problema 10\ndef get_longest_all_even(lst):\n '''Determina secventa cea mai lunga cu proprietatea ca toate numerele sunt pare\n :param: lst: lista de nr intregi\n :return: rez: lista numerelor cu proprietatea anuntata mai sus'''\n rez = [] # rezultatul final\n temp = [] # solutia curenta\n for x in lst:\n if x%2==0:\n temp.append(x)\n else:\n if (len(temp) > len(rez)):\n rez = temp[:]\n temp.clear()\n if (len(temp) > len(rez)):\n rez = temp[:]\n return rez\n\n\ndef test_get_longest_all_even():\n assert get_longest_all_even([2,4,6,11])==[2,4,6]\n assert get_longest_all_even([1,3,2,8,0])==[2,8,0]\n\n\ndef meniu():\n print(\"\"\"\n1.Citire date\n2.Determinarea celei mai lungi secvente cu proprietatea de la pb 2\n3.Determinarea celei mai lungi secvente cu proprietatea de la pb 13\n4.Determinarea celei mai lungi secvente cu proprietatea de la pb 10\n5.Iesire\"\"\")\n\n\ndef citire(n):\n lst=[]\n for i in range(0,n):\n p=int(input(\"introduceti elemntul\"))\n lst.append(p)\n return lst\n\n\ndef teste():\n test_get_prim()\n test_get_cif_prim()\n test_get_longest_all_primes()\n test_get_longest_prime_digits()\n test_get_longest_all_even()\n\n\ndef main():\n lst=[]\n teste()\n while True:\n meniu()\n cmd=int(input(\"introduceti comanda\"))\n if cmd==1:\n n=int(input(\"cate numere sa fie in lista?\"))\n lst=citire(n)\n elif cmd==2:\n print(get_longest_all_primes(lst))\n elif cmd==3:\n print(get_longest_prime_digits(lst))\n elif cmd==4:\n print(get_longest_all_even(lst))\n elif cmd==5:\n break\n else:\n print(\"comanda invalida\")\n\n\nif __name__ == '__main__':main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"106681875","text":"#!/usr/bin/env python\n\nimport unittest\nimport template_creator\nimport yaml\n\n\nclass TestVpcMethods(unittest.TestCase):\n\n def setUp(self):\n with open('template_config.yaml', 'r') as f:\n self.config = yaml.load(f.read())\n self.cloudformation = template_creator.Cloudformation(self.config)\n\n self.securityGroup = {\n 'Type': 'AWS::EC2::SecurityGroup', 'Properties': {\n 'VpcId': {\n 'Ref': 'VPC'}, 'Tags': [\n {\n 'Value': 'ApiDev', 'Key': 'Environment'}, {\n 'Value': 'ApiDev-Dev-VPC-Bastion-SG', 'Key': 'Name'}, {\n 'Value': 'Foo industries', 'Key': 'Owner'}, {\n 'Value': 'ServiceVPC', 'Key': 'Service'}, {\n 'Value': 'Dev', 'Key': 'VPC'}], 'GroupDescription': 'Used for source/dest rules'}}\n\n def test_create_bsg(self):\n print(self.cloudformation.vpc.Bsg.to_dict())\n self.assertDictEqual(\n self.cloudformation.vpc.Bsg.to_dict(),\n self.securityGroup)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_BastionSG.py","file_name":"test_BastionSG.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"98711891","text":"class Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n result = []\n while left <= right:\n A = list(str(left))\n flag = True\n for a in A:\n if a == '0' or left % int(a) != 0:\n flag = False\n break\n if flag:\n result.append(left)\n left += 1\n return result","sub_path":"SelfDividingNumbers/SelfDividingNumbers_1.py","file_name":"SelfDividingNumbers_1.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89081820","text":"import csv\n\n# Constants that define the sort of match that is played\nwinning_limit = 20000\ntotal_players = 4\nhigh_stakes_players = 2\n\n# Some stats that we measure\nmatches_won = [0, 0, 0, 0]\nthis_match = []\n\n\ndef find_winner(d):\n v = list(d.values())\n k = list(d.keys())\n return k[v.index(max(v))]\n\n\ndef export_throw_stats(match, number):\n with open(\"data/throws_match_\" + str(number) + \".csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerow([\"Player\", \"Dice\", \"Throw_Score\", \"Turn_Score\"])\n writer.writerows(match)\n\n\ndef make_exports(scoreboard):\n result = []\n for i in scoreboard.keys():\n result.append([int(i), scoreboard[i]])\n return result\n\n\ndef export_final_stats(scoreboard, number):\n with open(\"data/final_match_\" + str(number) + \".csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerow([\"Player\", \"Final Score\"])\n writer.writerows(scoreboard)\n","sub_path":"py_files/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"5780223","text":"# 195, might have to run it several times\n# https://adventofcode.com/2015/day/19\n\nimport sys\nimport re\nimport pprint\nimport random\n\nrulesFilename = sys.argv[1]\nwith open(rulesFilename, 'r') as inputFile:\n lines = inputFile.readlines()\n\n# Al => ThF\n# Al => ThRnFAr\n\nreplacements = {}\nruleExpr = re.compile('(?P.+) => (?P.+)')\nfor line in lines:\n if line == \"\":\n break\n match = ruleExpr.match(line)\n if match:\n replacements[match.group('out')] = match.group('in')\n\n\ninput = lines[-1]\n\nsortedRules = sorted(replacements.keys())\n\nsrules = sorted(replacements.keys() , key = len, reverse = True)\n\nkeysShuffled = list(replacements.keys())\n\nrandom.shuffle(keysShuffled)\n\ncurrent = input\nfound = False\nwhile not found:\n current = input\n count = 0\n mutations = 0\n random.shuffle(keysShuffled)\n while input != 'e':\n for s in keysShuffled:\n mutations += current.count(s)\n current = current.replace(s, replacements[s])\n count += 1\n if count > 20:\n # print('might need to rerun several times to get answers, uses randomization')\n # print(current)\n break\n if current == 'e':\n found = True\n # pprint.pprint(keysShuffled)\n # print(mutations)\n break\n\nprint(mutations)\n\n","sub_path":"day19/day19-2.py","file_name":"day19-2.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"316984016","text":"from django.conf.urls.defaults import *\nfrom django.views.generic.simple import direct_to_template\nfrom django.contrib.auth import views as auth_views\nfrom django.conf import settings\n\n\nurlpatterns = patterns('friends.views',\n\n url(r'^$',\n 'list_friends',\n name='friends_friends'),\n\n url(r'^invite/(?P[\\.\\w]+)/$',\n 'invite_friend',\n name='friends_invite'),\n\n url(r'^remove/(?P[\\.\\w]+)/$',\n 'remove_friend',\n name='friends_remove'),\n\n url(r'^invitations/received/$',\n 'list_received_invitations',\n name='friends_received_invitations'),\n\n url(r'^invitations/sent/$',\n 'list_sent_invitations',\n name='friends_sent_invitations'),\n\n url(r'^invitation/(?P[\\d]+)/$',\n 'show_invitation',\n name='friends_show_invitation'),\n\n url(r'^invitation/(?P[\\d]+)/remove/$',\n 'remove_invitation',\n name='friends_remove_invitation'),\n\n url(r'^invitation/(?P[\\d]+)/accept/$',\n 'respond_to_invitation',\n {'resp': 'a'},\n name='friends_accept_invitation'),\n\n url(r'^invitation/(?P[\\d]+)/decline/$',\n 'respond_to_invitation',\n {'resp': 'd'},\n name='friends_decline_invitation'),\n\n url(r'(?P[\\.\\w]+)/$',\n 'list_friend_friends',\n name='friends_friend_friends'),\n\n\n)\n\n","sub_path":"friends/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"428465885","text":"from tensorflow.keras.layers import Conv2D, UpSampling2D, LeakyReLU, Concatenate\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.applications import MobileNetV2\nimport tensorflow as tf\n\nclass FinalUpscaleBlock(Model):\n def __init__(self, filters, name):\n super(FinalUpscaleBlock, self).__init__()\n self.up = UpSampling2D(size=(2, 2), interpolation='bilinear', name=name+'_upsampling2d')\n self.concat = Concatenate(name=name+'_concat')\n self.convA = Conv2D(filters=filters, kernel_size=3, strides=1, padding='same', name=name+'_convA')\n self.reluA = LeakyReLU(alpha=0.2)\n self.convB = Conv2D(filters=filters, kernel_size=3, strides=1, padding='same', name=name+'_convB')\n self.reluB = LeakyReLU(alpha=0.2)\n def call(self, x):\n return self.reluB( self.convB( self.reluA( self.convA( self.concat( [self.up(x[0]), x[1]] ) ) ) ) )\n\n\nclass Encoder(Model):\n def __init__(self):\n super(Encoder, self).__init__()\n self.base_model = MobileNetV2(input_shape=(480,640, 3), include_top=False, weights='imagenet')\n print('Base model loaded')\n\n outputs = [self.base_model.outputs[-1]]\n for name in ['block_1_expand_relu','block_3_expand_relu','block_6_expand_relu','block_13_expand_relu'] : outputs.append( self.base_model.get_layer(name).output )\n self.encoder = Model(inputs=self.base_model.inputs, outputs=outputs)\n\n def call(self, x):\n return self.encoder(x)\n\nclass Decoder(Model):\n def __init__(self, decode_filters):\n super(Decoder, self).__init__()\n self.conv2 = Conv2D(filters=decode_filters, kernel_size=1, padding='same', name='conv2')\n self.fup1 = FinalUpscaleBlock(filters=decode_filters//2, name='fup1')\n self.fup2 = FinalUpscaleBlock(filters=decode_filters//4, name='fup2')\n self.fup3 = FinalUpscaleBlock(filters=decode_filters//8, name='fup3')\n self.fup = FinalUpscaleBlock(filters=decode_filters//16, name='fup')\n self.conv3 = Conv2D(filters=1, kernel_size=3, strides=1, padding='same', name='conv3')\n\n def call(self, features):\n x,d1,d2,d3,d4 = features[0], features[1], features[2], features[3], features[4]\n upo0 = self.conv2(x)\n upo1 = self.fup1([upo0,d4])\n upo2 = self.fup2([upo1,d3])\n upo3 = self.fup3([upo2,d2])\n upo4 = self.fup([upo3,d1])\n upo5=self.conv3(upo4)\n return upo5\n\nclass DepthEstimate(Model):\n def __init__(self):\n super(DepthEstimate, self).__init__()\n self.encoder = Encoder()\n self.decoder = Decoder( decode_filters = int(self.encoder.layers[-1].output[0].shape[-1] // 2 ) )\n print('\\nModel created.')\n\n def call(self, x):\n return self.decoder(self.encoder(x))\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"293325245","text":"import time, threading, address, sys, remote, random, socket, network, json, rsa, aesHmac, Crypto.Util.number as crypto_number\nfrom config import *\n\ndef repeatAndSleep(sleep_time):\n\tdef inside(func):\n\t\tdef insideInside(self, *args, **kwargs):\n\t\t\tself._shutdownMutex.acquire()\n\t\t\tshutdown_status = self._shutdown\n\t\t\tmutexReleaser(self._shutdownMutex)\n\t\t\twhile not shutdown_status:\n\t\t\t\tret = func(self, *args, **kwargs)\n\t\t\t\tif not ret:\n\t\t\t\t\treturn\n\t\t\t\ttime.sleep(sleep_time)\n\t\t\t\tself._shutdownMutex.acquire()\n\t\t\t\tshutdown_status = self._shutdown\n\t\t\t\tmutexReleaser(self._shutdownMutex)\n\t\treturn insideInside\n\treturn inside\n\ndef retryOnSocketError(retry_limit):\n\tdef decorator(func):\n\t\tdef inner(self, *args, **kwargs):\n\t\t\tretry_count = 0\n\t\t\tself._shutdownMutex.acquire()\n\t\t\tshutdown_status = self._shutdown\n\t\t\tmutexReleaser(self._shutdownMutex)\n\t\t\twhile retry_count < retry_limit and not shutdown_status:\n\t\t\t\ttry:\n\t\t\t\t\tret = func(self, *args, **kwargs)\n\t\t\t\t\treturn ret\n\t\t\t\texcept socket.error:\n\t\t\t\t\ttime.sleep(retry_count)\n\t\t\t\t\tretry_count += 1\n\t\t\t\tself._shutdownMutex.acquire()\n\t\t\t\tshutdown_status = self._shutdown\n\t\t\t\tmutexReleaser(self._shutdownMutex)\n\t\t\tif retry_count == retry_limit:\n\t\t\t\tself._shutdown = True\n\t\t\t\tsys.exit(-1)\n\t\treturn inner\n\treturn decorator\n\t\ndef mutexReleaser(f):\n\ttry:\n\t\tf.release()\n\texcept:\n\t\tpass\n\nclass Node:\n\tdef __init__(self, key, localAddress, hostAddress = None, bits = RSA_BITS):\n\t\taddress.validateAddress(localAddress)\n\t\tself._address = localAddress\n\t\t\n\t\ttry:\n\t\t\tself._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\t\tself._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\t\t\tself._socket.bind((self._address.addr, self._address.port))\n\t\t\tself._socket.close()\n\t\texcept:\n\t\t\traise Exception('local address already in use ({}:{})'.format(localAddress.addr, localAddress.port))\n\t\t\n\t\tif hostAddress:\n\t\t\taddress.validateAddress(hostAddress)\n\t\t\t\n\t\tself._path = '{}\\\\{}.rsa.keys'.format(localAddress.hash, bits)\n\t\ttry:\n\t\t\tself._e, self._d = json.loads(aesHmac.readEncryptedFile(self._path, key))[-1]\n\t\texcept FileNotFoundError:\n\t\t\tkeys = rsa.newKeys(RSA_BITS)\n\t\t\taesHmac.writeEncryptedFile(self._path, json.dumps([keys]), key)\n\t\t\tself._e, self._d = keys\n\t\t\t\n\t\tself._keysMutex = threading.BoundedSemaphore()\n\t\tself._shutdownMutex = threading.BoundedSemaphore()\n\t\t\n\t\tself._shutdown = False\n\t\tself._daemons = {}\n\t\tself._succ = []\n\t\tself._commands = {}\n\t\t\n\t\tif not self.join(hostAddress):\n\t\t\traise Exception('host address not found, connection refused')\n\t\t\n\tdef __del__(self):\n\t\tself.shutdown()\n\t\t\t\n\tdef getKeys(self):\n\t\tself._keysMutex.acquire()\n\t\tret = self._e, self._d\n\t\tmutexReleaser(self._keysMutex)\n\t\treturn ret\n\t\n\tdef updateKeys(self, key, bits = RSA_BITS):\n\t\ttry:\n\t\t\tkey_set = json.loads(aesHmac.readEncryptedFile(self._path, key))\n\t\t\tkeys = rsa.newKeys(bits)\n\t\t\tself._keysMutex.acquire()\n\t\t\tself._e, self._d = keys\n\t\t\tmutexReleaser(self._keysMutex)\n\t\t\tkey_set.append(keys)\n\t\t\taesHmac.writeEncryptedFile(self._path, json.dumps(key_set), key)\n\t\t\treturn True\n\t\texcept:\n\t\t\treturn False\n\t\t\t\n\tdef isOurs(self, id):\n\t\tassert id >= 0 and id < SIZE\n\t\treturn address.inrange(id, self._pred.id(1), self.id(1))\n\t\t\n\tdef isMe(self, i):\n\t\treturn i and i.addr == self.addr and i.port == self.port\n\t\t\n\tdef getNeighbours(self):\n\t\tA = {}\n\t\tlists = self._finger + self._succ + [self._pred]\n\t\tfor i in lists:\n\t\t\tif i and not self.isMe(i) and i.ping():\n\t\t\t\ta = (i.addr, i.port)\n\t\t\t\tif not (a in A):\n\t\t\t\t\tA[a] = i\n\t\treturn A\n\n\tdef shutdown(self):\n\t\ttry:\n\t\t\tmutexReleaser(self._shutdownMutex)\n\t\t\tmutexReleaser(self._keysMutex)\n\t\t\tself._shutdownMutex.acquire()\n\t\t\tself._shutdown = True\n\t\t\tmutexReleaser(self._shutdownMutex)\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\ttry:\n\t\t\t\tself._socket.shutdown(socket.SHUT_RDWR)\n\t\t\t\tself._socket.close()\n\t\t\texcept socket.error:\n\t\t\t\tpass\n\t\t\tfor v in self._finger:\n\t\t\t\tif v and not self.isMe(v):\n\t\t\t\t\tv.shutdown()\n\t\t\tfor v in self._succ:\n\t\t\t\tif v and not self.isMe(v):\n\t\t\t\t\tv.shutdown()\n\t\t\tv = self._pred\n\t\t\tif v and not self.isMe(v):\n\t\t\t\tv.shutdown()\n\t\texcept:\n\t\t\tpass\n\t\tself._socket = None\n\t\t\n\t@property\n\tdef addr(self):\n\t\treturn self._address.addr\n\t\t\n\t@property\n\tdef port(self):\n\t\treturn self._address.port\n\t\t\n\t@property\n\tdef hash(self):\n\t\treturn self._address.hash\n\t\t\n\tdef id(self, offset = 0):\n\t\treturn self._address.id(offset)\n\t\t\n\tdef start(self):\n\t\tself._daemons['run'] = threading.Thread(target = self.run)\n\t\tself._daemons['fix_fingers'] = threading.Thread(target = self.fixFingers)\n\t\tself._daemons['stabilize'] = threading.Thread(target = self.stabilize)\n\t\tself._daemons['update_successors'] = threading.Thread(target = self.updateSuccessors)\n\t\tfor k, v in self._daemons.items():\n\t\t\tv.daemon = True \n\t\t\tv.start()\n\t\t\n\tdef ping(self):\n\t\treturn True\n\t\t\n\tdef join(self, hostAddress = None):\n\t\tself._finger = [None] * LOGSIZE\n\t\tself._pred = None\n\t\tif hostAddress:\n\t\t\taddress.validateAddress(hostAddress)\n\t\t\tself._finger[0] = remote.Remote(hostAddress, self).findSuccessor(self.id())\n\t\t\tif self._finger[0] == None:\n\t\t\t\treturn False\n\t\telse:\n\t\t\tself._finger[0] = self\n\t\treturn True\n\t\t\t\n\t@repeatAndSleep(STABILIZE_INT)\n\t@retryOnSocketError(STABILIZE_RET)\n\tdef stabilize(self, ret = True):\n\t\tsuc = self.successor()\n\t\tif suc.id() != self._finger[0].id():\n\t\t\tself._finger[0] = suc\n\t\tx = suc.predecessor()\n\t\tif x != None and \\\n\t\t address.inrange(x.id(), self.id(1), suc.id()) and \\\n\t\t self.id(1) != suc.id() and \\\n\t\t x.ping():\n\t\t\tself._finger[0] = x\n\t\tself.successor().notify(self)\n\t\treturn ret\n\n\tdef notify(self, remote):\n\t\tif self.predecessor() == None or \\\n\t\t address.inrange(remote.id(), self.predecessor().id(1), self.id()) or \\\n\t\t not self.predecessor().ping():\n\t\t\tself._pred = remote\n\n\t@repeatAndSleep(FIX_FINGERS_INT)\n\tdef fixFingers(self, ret = True):\n\t\ti = random.randrange(LOGSIZE - 1) + 1\n\t\tself._finger[i] = self.findSuccessor(self.id(1 << i))\n\t\treturn ret\n\n\t@repeatAndSleep(UPDATE_SUCCESSORS_INT)\n\t@retryOnSocketError(UPDATE_SUCCESSORS_RET)\n\tdef updateSuccessors(self, ret = True):\n\t\tsuc = self.successor()\n\t\tif suc.id() != self.id():\n\t\t\tsuccessors = [suc]\n\t\t\tsuc_list = suc.getSuccessors()\n\t\t\tif suc_list:\n\t\t\t\tfor i in suc_list:\n\t\t\t\t\tsuccessors.append(remote.Remote(address.Address(i[0], i[1]), self))\n\t\t\tself._succ = successors\n\t\treturn ret\n\n\tdef getSuccessors(self):\n\t\tA = []\n\t\tfor i in self._succ[:N_SUCCESSORS - 1]:\n\t\t\tA.append((i._address.addr, i._address.port))\n\t\treturn A\n\t\t\n\tdef successor(self):\n\t\tlists = [self._finger[0]] + self._succ\n\t\tfor remote in lists:\n\t\t\tif remote and remote.ping():\n\t\t\t\tself._finger[0] = remote\n\t\t\t\treturn remote\n\t\tself._shutdown = True\n\t\tsys.exit(-1)\n\n\tdef predecessor(self):\n\t\treturn self._pred\n\n\t@retryOnSocketError(FIND_SUCCESSOR_RET)\n\tdef findSuccessor(self, id):\n\t\tif self.predecessor() and self.isOurs(id):\n\t\t\treturn self\n\t\tnode = self.findPredecessor(id)\n\t\treturn node.successor() if node else node\n\n\t@retryOnSocketError(FIND_PREDECESSOR_RET)\n\tdef findPredecessor(self, id):\n\t\tnode = self\n\t\tif node.successor().id() == node.id():\n\t\t\treturn node\n\t\ttry:\n\t\t\twhile node and not address.inrange(id, node.id(1), node.successor().id(1)):\n\t\t\t\tnode = node.closestPrecedingFinger(id)\n\t\t\treturn node\n\t\texcept:\n\t\t\tpass\n\n\tdef closestPrecedingFinger(self, id):\n\t\tlists = self._succ + self._finger\n\t\tfor remote in reversed(lists):\n\t\t\tif remote != None and address.inrange(remote.id(), self.id(1), id) and remote.ping():\n\t\t\t\treturn remote\n\t\treturn self\n\t\t\n\tdef command(self, cmd, id = None):\n\t\tif not id:\n\t\t\tsuc = self.successor()\n\t\t\treturn suc.command(cmd) if not self.isMe(suc) else None\n\t\telse:\n\t\t\tsuc = self.findSuccessor(id)\n\t\t\treturn suc.command(cmd) if suc != None and not self.isMe(suc) and suc.id() == id else None\n\t\t\n\tdef reply(self, args):\n\t\ttry:\n\t\t\tconn, addr = args\n\n\t\t\tb = crypto_number.getRandomInteger(DIFFIE_HELLMEN_KEY_SIZE) % N\n\t\t\t\t\t\n\t\t\tA = network.read_from_socket_as_string(conn)\n\t\t\n\t\t\tif A:\n\t\t\t\tA = json.loads(A)\n\t\t\t\n\t\t\t\tif type(A) != dict:\n\t\t\t\t\traise Exception\n\t\t\t\n\t\t\t\tsig = A.pop('sig')\n\t\t\t\tif not rsa.verify(sig, json.dumps(A, sort_keys = True), A['public key']):\n\t\t\t\t\traise Exception\n\t\t\t\n\t\t\t\tga_modn = A['key']\n\t\t\t\n\t\t\t\tpk, sk = self.getKeys()\n\t\t\t\n\t\t\t\tA = {\n\t\t\t\t\t'key': pow(G, b, N),\n\t\t\t\t\t'public key': pk\n\t\t\t\t}\n\t\t\t\n\t\t\t\tA['sig'] = rsa.sign(json.dumps(A, sort_keys = True), sk)\n\t\t\t\n\t\t\t\tnetwork.send_to_socket_as_string(conn, json.dumps(A))\n\t\t\t\n\t\t\t\tgab_modn = pow(ga_modn, b, N)\n\t\t\t\n\t\t\t\trequest = network.read_from_socket_as_bytes(conn)\n\t\t\t\n\t\t\t\tif request:\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\trequest = aesHmac.symmDecryption(request, gab_modn)\n\t\t\t\t\n\t\t\t\t\tcommand = request.split(' ')[0]\n\t\t\t\t\n\t\t\t\t\trequest = request[len(command) + 1:]\n\n\t\t\t\t\tresult = json.dumps(\"\")\n\t\t\t\t\n\t\t\t\t\tif command == 'get_successor':\n\t\t\t\t\t\tsuccessor = self.successor()\n\t\t\t\t\t\tresult = json.dumps((successor.addr, successor.port))\n\t\t\t\t\telif command == 'get_predecessor':\n\t\t\t\t\t\tif self._pred != None:\n\t\t\t\t\t\t\tpredecessor = self.predecessor()\n\t\t\t\t\t\t\tresult = json.dumps((predecessor.addr, predecessor.port))\n\t\t\t\t\telif command == 'find_successor':\n\t\t\t\t\t\tsuccessor = self.findSuccessor(int(request))\n\t\t\t\t\t\tresult = json.dumps((successor.addr, successor.port))\n\t\t\t\t\telif command == 'closest_preceding_finger':\n\t\t\t\t\t\tclosest = self.closestPrecedingFinger(int(request))\n\t\t\t\t\t\tresult = json.dumps((closest.addr, closest.port))\n\t\t\t\t\telif command == 'notify':\n\t\t\t\t\t\tnpredecessor = address.Address(request.split(' ')[0], int(request.split(' ')[1]))\n\t\t\t\t\t\tself.notify(remote.Remote(npredecessor, self))\n\t\t\t\t\telif command == 'get_successors':\n\t\t\t\t\t\tresult = json.dumps(self.getSuccessors())\n\t\t\t\t\telse:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tt = self._commands[command]\n\t\t\t\t\t\t\tdef f(A):\n\t\t\t\t\t\t\t\tnetwork.send_to_socket_as_bytes(conn, aesHmac.symmEncryption(A, gab_modn))\n\t\t\t\t\t\t\tt(request, f)\n\t\t\t\t\t\t\tconn.close()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\t\tpass\n\t\t\t\t\t\t\n\t\t\t\t\tnetwork.send_to_socket_as_bytes(conn, aesHmac.symmEncryption(result, gab_modn))\n\t\texcept:\n\t\t\tpass\n\t\tconn.close()\n\n\tdef run(self):\n\t\tself._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\t\tself._socket.bind((self._address.addr, self._address.port))\n\t\tself._socket.listen(LISTEN_LIMIT)\n\t\tself._shutdownMutex.acquire()\n\t\tshutdown_status = self._shutdown\n\t\tmutexReleaser(self._shutdownMutex)\n\t\twhile not shutdown_status:\n\t\t\ttry:\n\t\t\t\tclient = self._socket.accept()\n\t\t\texcept socket.error:\n\t\t\t\tself._shutdownMutex.acquire()\n\t\t\t\tself._shutdown = True\n\t\t\t\tmutexReleaser(self._shutdownMutex)\n\t\t\t\treturn\n\t\t\trecv_thread = threading.Thread(target = self.reply, args = (client,))\n\t\t\trecv_thread.daemon = True\n\t\t\trecv_thread.start()\n\t\t\tself._shutdownMutex.acquire()\n\t\t\tshutdown_status = self._shutdown\n\t\t\tmutexReleaser(self._shutdownMutex)\n\t\t\t\t\t\t\t\n\tdef registerCommand(self, cmd, func):\n\t\tself._commands[cmd] = func\n\t\t\n\tdef unregisterCommand(self, cmd):\n\t\ttry:\n\t\t\tdel self._commands[cmd]\n\t\t\treturn True\n\t\texcept KeyError:\n\t\t\treturn False\n","sub_path":"agent/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":10808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"405343686","text":"from pylab import *\nfrom scipy.integrate import odeint\nimport matplotlib.animation as animation\n\n\nk = 20\nl = 3\nm = 1\ng = 9.81\nf0 = pi/4\ntime = 60\n\n\ndef pendulum(y, t):\n y1, y2, y3, y4 = y\n return [y2,\n k*(l - sqrt(y1**2 + y3**2))*y1/(m*sqrt(y1**2 + y3**2)),\n y4,\n k * (l - sqrt(y1 ** 2 + y3 ** 2)) * y3 / (m * sqrt(y1 ** 2 + y3 ** 2)) - g]\n\n\nt = arange(0, time, 0.05)\ny0 = [l*sin(f0), 0, -l*cos(f0), 0]\n[y1, y2, y3, y4] = odeint(pendulum, y0, t, full_output=False).T\n\n\ndef pendAnimation():\n fig2 = plt.figure(facecolor='white')\n ax = plt.axes(xlim=(np.amin(y3)-0.1, abs(np.amin(y3))+0.1), ylim=(np.amin(y3)-0.1, 0))\n line, = ax.plot([], [], 'g', lw=2)\n ax.grid(True)\n def redraw(i):\n x = y1[0:i+1]\n y = y3[0:i+1]\n line.set_data(x, y)\n anim = animation.FuncAnimation(fig2, redraw, frames=900, interval=1)\n plt.show()\n\n\ndef main():\n plot(y1, y3, linewidth=1)\n xlim(np.amin(y3) - 0.1, abs(np.amin(y3)) + 0.1)\n ylim(np.amin(y3) - 0.1, 0)\n grid(True)\n pendAnimation()\n show()\n\n\nmain()\n\n\n\n","sub_path":"lab3_pendulum.py","file_name":"lab3_pendulum.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"140935339","text":"import requests\n\n\ndef get_playlist_stream(uri):\n # .pls and .m3u are not supported by gui player, parse the file\n if \".pls\" in uri or \".m3u\" in uri:\n txt = requests.get(uri).text\n for l in txt.split(\"\\n\"):\n if l.startswith(\"http\"):\n return {\"uri\": l}\n return {\"uri\": uri}\n\n","sub_path":"ovos_plugin_common_play/ocp/stream_handlers/playlists.py","file_name":"playlists.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"99689479","text":"from django.urls import path, include\nfrom globus_portal_framework.urls import register_custom_index\nfrom xpcs_portal.xpcs_index.views import (\n ReprocessingTaskCreate, AutomateDashboard, XPCSActionDetail,\n XPCSProjectDetail, XPCSManifestCheckoutView,\n XPCSReprocessDatasetsCheckoutView\n)\nfrom xpcs_portal.xpcs_index.api import toggle_filename_filter\n\napp_name = 'xpcs-index'\nregister_custom_index('xpcs_index', ['xpcs'])\n\napipatterns = [\n path('filename_filter/toggle/', toggle_filename_filter, name='toggle-filename-filter'),\n]\n\nurlpatterns = [\n path('/xpcs-reprocess-datasets-checkout//',\n XPCSReprocessDatasetsCheckoutView.as_view(), name='xpcs-reprocess-datasets-checkout'),\n path('/xpcs-manifest-checkout//',\n XPCSManifestCheckoutView.as_view(), name='xpcs-manifest-project-checkout'),\n path('/projects///',\n XPCSProjectDetail.as_view(), name='tp-project-detail'),\n path('/automation/',\n ReprocessingTaskCreate.as_view(), name='reprocessing-task-create'),\n path('/automate/',\n AutomateDashboard.as_view(), name='automate-dashboard'),\n path('/automate/actions//',\n XPCSActionDetail.as_view(), name='automate-action-detail'),\n path('/api/', include(apipatterns)),\n\n # path('/bags/', XPCSBagListView.as_view(),\n # name='bag-list'),\n # path('/automation//',\n # Automation.as_view(), name='automation-detail'),\n]\n","sub_path":"xpcs_portal/xpcs_index/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"208562427","text":"n=int(input())\nnode=[[] for i in range(n+1)]\nfor i in range(n-1):\n a, b=map(int, input().split())\n node[a].append(b)\n node[b].append(a)\nvisit=[0]*(n+1)\nstack=[1]\nvisit[1]=1\ncount=0\nwhile stack:\n now=stack.pop()\n for t in node[now]:\n if len(node[t])==1:\n visit[t]=1+visit[now]\n count+=visit[t]-1\n continue\n if visit[t]==0:\n visit[t]=1+visit[now]\n stack.append(t)\nif count%2: print(\"Yes\")\nelse: print(\"No\")\n","sub_path":"BOJ/15900.py","file_name":"15900.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"335733752","text":"def xmaslight():\n # This is the code from my \n \n #NOTE THE LEDS ARE GRB COLOUR (NOT RGB)\n \n # Here are the libraries I am currently using:\n import time\n import board\n import neopixel\n import re\n import math\n \n # You are welcome to add any of these:\n # import random\n # import numpy\n # import scipy\n # import sys\n \n # If you want to have user changable values, they need to be entered from the command line\n # so import sys sys and use sys.argv[0] etc\n # some_value = int(sys.argv[0])\n \n # IMPORT THE COORDINATES (please don't break this bit)\n \n coordfilename = \"Python/coords.txt\"\n \n fin = open(coordfilename,'r')\n coords_raw = fin.readlines()\n \n coords_bits = [i.split(\",\") for i in coords_raw]\n \n coords = []\n \n for slab in coords_bits:\n new_coord = []\n for i in slab:\n new_coord.append(int(re.sub(r'[^-\\d]','', i)))\n coords.append(new_coord)\n \n #set up the pixels (AKA 'LEDs')\n PIXEL_COUNT = len(coords) # this should be 500\n \n pixels = neopixel.NeoPixel(board.D18, PIXEL_COUNT, auto_write=False)\n \n \n # YOU CAN EDIT FROM HERE DOWN\n\n # pause between cycles (normally zero as it is already quite slow)\n slow = 0\n \n # scale down to within unit sphere\n coords = [ (x/500., y/500., z/500.) for x,y,z in coords ]\n\n gamma = 2.2\n factor = 255 / (255**gamma)\n gamma_map = [ int( (x**gamma * factor + .5) ) for x in range(256) ]\n\n def led_color(color):\n r, g, b = color\n r = max(0, min(255, int(r)))\n g = max(0, min(255, int(g)))\n b = max(0, min(255, int(b)))\n return [gamma_map[g],gamma_map[r],gamma_map[b]]\n\n def light(color, dist):\n \"\"\" color at distance x \"\"\"\n return tuple( float(x*dist*dist) for x in color )\n\n def dist_sq(a,b):\n ax,ay,az=a\n bx,by,bz=b\n dx,dy,dz=ax-bx,ay-by,az-bz\n return dx*dx+dy*dy+dz*dz\n\n def shader(color, a, b):\n d2 = dist_sq(a,b)\n r, g, b = color\n return r/d2, g/d2, b/d2\n\n class Attractor:\n def __init__(self, pos, color):\n self.pos = pos\n self.color = color\n\n def next(self):\n sigma, rho, beta = 10., 28., 8/3.\n dt = 1/1000.\n x, y, z = self.pos\n for i in range(10):\n dx, dy, dz = sigma*(y-x)*dt, (x*(rho-z)-y)*dt, (x*y-beta*z)*dt\n x, y, z = x+dx, y+dy, z+dz\n self.pos = (x,y,z)\n\n class LorenzAni:\n\n def __init__(self, coords):\n self.coords = [ (x*35,y*35,z*23+15) for x,y,z in coords ]\n #self.coords = [ (x*.11,y*.11,z*.11) for x,y,z in coords ]\n self.buf = [ [0.,0.,0.] for x in range(len(coords)) ]\n self.attractors = [ Attractor( (1,1,.5), light( (255, 32, 127), 5 ) ) ,\n Attractor( (1,20,.5), light( (255, 255, 63), 5 ) ) ,\n Attractor( (10,-40,0), light( (0, 0, 255), 5 ) ) ]\n\n def clear(self):\n for c in self.buf:\n c[0] = c[1] = c[2] = 0.\n\n def next(self):\n self.clear()\n for a in self.attractors:\n a.next()\n for i,pos in enumerate(self.coords):\n ri,gi,bi = shader(a.color, pos, a.pos)\n self.buf[i][0]+=ri\n self.buf[i][1]+=gi\n self.buf[i][2]+=bi\n\n ani = LorenzAni(coords)\n\n while True:\n time.sleep(slow)\n ani.next()\n for i, color in enumerate(ani.buf):\n pixels[i] = led_color(color)\n pixels.show()\n \n return 'DONE'\n\n\n# yes, I just put this at the bottom so it auto runs\nxmaslight()\n","sub_path":"xmaslights-lorenz.py","file_name":"xmaslights-lorenz.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"396553479","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 tensorflow as tf\n\nfrom pykg2vec.core.KGMeta import ModelMeta\n\n\nclass NTN(ModelMeta):\n \"\"\"\n ------------------Paper Title-----------------------------\n Reasoning With Neural Tensor Networks for Knowledge Base Completion\n ------------------Paper Authors---------------------------\n Richard Socher∗, Danqi Chen*, Christopher D. Manning, Andrew Y. Ng\n Computer Science Department, Stanford University, Stanford, CA 94305, USA\n richard@socher.org, {danqi,manning}@stanford.edu, ang@cs.stanford.edu\n ------------------Summary---------------------------------\n It is a neural tensor network which represents entities as an average of their\n constituting word vectors. It then projects entities to their vector embeddings\n in the input layer. The two entities are then combined and mapped to a non-linear hidden layer.\n https://github.com/siddharth-agrawal/Neural-Tensor-Network/blob/master/neuralTensorNetwork.py\n ---\n \"\"\"\n\n def __init__(self, config=None):\n self.config = config\n self.data_stats = self.config.kg_meta\n self.model_name = 'NTN'\n\n def def_inputs(self):\n self.pos_h = tf.placeholder(tf.int32, [None])\n self.pos_t = tf.placeholder(tf.int32, [None])\n self.pos_r = tf.placeholder(tf.int32, [None])\n self.neg_h = tf.placeholder(tf.int32, [None])\n self.neg_t = tf.placeholder(tf.int32, [None])\n self.neg_r = tf.placeholder(tf.int32, [None])\n self.test_h = tf.placeholder(tf.int32, [1])\n self.test_t = tf.placeholder(tf.int32, [1])\n self.test_r = tf.placeholder(tf.int32, [1])\n self.test_h_batch = tf.placeholder(tf.int32, [None])\n self.test_t_batch = tf.placeholder(tf.int32, [None])\n self.test_r_batch = tf.placeholder(tf.int32, [None])\n\n def def_parameters(self):\n num_total_ent = self.data_stats.tot_entity\n num_total_rel = self.data_stats.tot_relation\n d = self.config.ent_hidden_size\n k = self.config.rel_hidden_size\n\n with tf.name_scope(\"embedding\"):\n self.ent_embeddings = tf.get_variable(name=\"ent_embedding\", shape=[num_total_ent, d],\n initializer=tf.contrib.layers.xavier_initializer(uniform=False))\n self.rel_embeddings = tf.get_variable(name=\"rel_embedding\", shape=[num_total_rel, k],\n initializer=tf.contrib.layers.xavier_initializer(uniform=False))\n\n with tf.name_scope(\"weights_and_parameters\"):\n self.mr1 = tf.get_variable(name=\"mr1\", shape=[d, k],\n initializer=tf.contrib.layers.xavier_initializer(uniform=False))\n self.mr2 = tf.get_variable(name=\"mr2\", shape=[d, k],\n initializer=tf.contrib.layers.xavier_initializer(uniform=False))\n self.br = tf.get_variable(name=\"br\", shape=[k, 1],\n initializer=tf.contrib.layers.xavier_initializer(uniform=False))\n self.mr = tf.get_variable(name=\"mr\", shape=[k, d, d],\n initializer=tf.contrib.layers.xavier_initializer(uniform=False))\n\n self.parameter_list = [self.ent_embeddings, self.rel_embeddings, \\\n self.mr1, self.mr2, self.br, self.mr]\n\n def def_loss(self):\n self.ent_embeddings = tf.nn.l2_normalize(self.ent_embeddings, axis=1)\n self.rel_embeddings = tf.nn.l2_normalize(self.rel_embeddings, axis=1)\n\n pos_h_e, pos_r_e, pos_t_e = self.embed(self.pos_h, self.pos_r, self.pos_t)\n neg_h_e, neg_r_e, neg_t_e = self.embed(self.neg_h, self.neg_r, self.neg_t)\n\n energy_pos = tf.reduce_sum(pos_r_e * self.train_layer(pos_h_e, pos_t_e), -1)\n energy_neg = tf.reduce_sum(neg_r_e * self.train_layer(neg_h_e, neg_t_e), -1)\n\n self.loss = tf.reduce_sum(tf.maximum(energy_neg + self.config.margin - energy_pos, 0))\n\n def train_layer(self, h, t):\n k = self.config.rel_hidden_size\n # h => [m, d], self.mr1 => [d, k]\n mr1h = tf.matmul(h, self.mr1)\n # t => [m, d], self.mr2 => [d, k]\n mr2t = tf.matmul(t, self.mr2)\n # br = [k]\n br = tf.squeeze(self.br, -1)\n\n # [m, k, 1, d]\n expanded_h = tf.tile(tf.expand_dims(tf.expand_dims(h, 1), 1), [1, k, 1, 1])\n\n # [m, k, d, d]\n expanded_mr = tf.tile(tf.expand_dims(self.mr, 0), [tf.shape(h)[0], 1, 1, 1])\n\n # [m, k, d, 1]\n expanded_t = tf.tile(tf.expand_dims(tf.expand_dims(t, 1), 3), [1, k, 1, 1])\n\n # [m, k]\n htmrt = tf.squeeze(tf.matmul(tf.matmul(expanded_h, expanded_mr), expanded_t), [2, 3])\n\n return tf.tanh(mr1h + mr2t + br + htmrt)\n\n def test_layer(self, h, t):\n num_entity = self.data_stats.tot_entity\n # h => [m, d], self.mr1 => [d, k]\n mr1h = tf.matmul(h, self.mr1)\n # t => [m, d], self.mr2 => [d, k]\n mr2t = tf.matmul(t, self.mr2)\n # br = [k]\n br = tf.squeeze(self.br, -1)\n htmrt = tf.cond(tf.shape(h)[0] > tf.shape(t)[0],\n lambda: tf.tensordot(t, tf.tensordot(h, self.mr, axes=((-1), (-1))), axes=((-1), (-1))),\n lambda: tf.tensordot(h, tf.tensordot(t, self.mr, axes=((-1), (-1))), axes=((-1), (-1))))\n mr1h = tf.cond(tf.shape(mr1h)[0] < num_entity, lambda: tf.expand_dims(mr1h, axis=1), lambda: mr1h)\n mr2t = tf.cond(tf.shape(mr2t)[0] < num_entity, lambda: tf.expand_dims(mr2t, axis=1), lambda: mr2t)\n\n return tf.tanh(mr1h + mr2t + br + htmrt)\n\n def test_batch(self):\n num_entity = self.data_stats.tot_entity\n\n h_vec, r_vec, t_vec = self.embed(self.test_h_batch, self.test_r_batch, self.test_t_batch)\n\n energy_h = tf.reduce_sum(\n tf.expand_dims(r_vec, axis=1) * self.test_layer(tf.nn.l2_normalize(self.ent_embeddings, axis=1), t_vec), -1)\n energy_t = tf.reduce_sum(\n tf.expand_dims(r_vec, axis=1) * self.test_layer(h_vec, tf.nn.l2_normalize(self.ent_embeddings, axis=1)), -1)\n\n _, head_rank = tf.nn.top_k(tf.negative(energy_h), k=num_entity)\n _, tail_rank = tf.nn.top_k(tf.negative(energy_t), k=num_entity)\n\n return head_rank, tail_rank\n\n def embed(self, h, r, t):\n \"\"\"function to get the embedding value\"\"\"\n emb_h = tf.nn.embedding_lookup(tf.nn.l2_normalize(self.ent_embeddings, axis=1), h)\n emb_r = tf.nn.embedding_lookup(tf.nn.l2_normalize(self.rel_embeddings, axis=1), r)\n emb_t = tf.nn.embedding_lookup(tf.nn.l2_normalize(self.ent_embeddings, axis=1), t)\n return emb_h, emb_r, emb_t\n\n def get_embed(self, h, r, t, sess=None):\n \"\"\"function to get the embedding value in numpy\"\"\"\n emb_h, emb_r, emb_t = self.embed(h, r, t)\n h, r, t = sess.run([emb_h, emb_r, emb_t])\n return h, r, t\n\n def get_proj_embed(self, h, r, t, sess):\n \"\"\"function to get the projected embedding value in numpy\"\"\"\n return self.get_embed(h, r, t, sess)\n","sub_path":"pykg2vec/core/NTN.py","file_name":"NTN.py","file_ext":"py","file_size_in_byte":7194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"545664017","text":"#Very first machine learning project recognising MNIST handwritten letters\n\nimport tensorflow as tf\nimport keras\nimport numpy as np\nfrom tensorflow.keras import layers\nfrom keras.datasets import mnist\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Dense\nfrom keras.layers import Flatten\nimport matplotlib as plt\n\nnumber_epochs = 1\n \n#Load dataset \nmnist = tf.keras.datasets.mnist \n(train_X, train_Y), (test_X, test_Y) = mnist.load_data() \n \n#Convert from int to float\ntrain_X = train_X.astype('float32')\ntest_X = test_X.astype('float32')\n\n#One hot encoding\ntrain_Y = to_categorical(train_Y)\ntest_Y = to_categorical(test_Y)\n \n#Normalise data\ntrain_X = train_X / 255.0\ntest_X = test_X / 255.0\n\n#Reshape dataset\ntrain_X = train_X.reshape((train_X.shape[0], 28, 28, 1))\ntest_X = test_X.reshape((test_X.shape[0], 28, 28, 1))\n\n#Create model\nmodel = tf.keras.Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))\n\n#Compile model\ncompile_model = model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\ntraining = model.fit(train_X, train_Y, epochs = number_epochs)\n\n#Evaluate model\nval_loss, val_acc = model.evaluate(test_X, test_Y)\nprint(val_loss, val_acc)\n\nmodel.save(\"epic_num_reader.model\")\nnew_model = tf.keras.models.load_model('epic_num_reader.model')\npredictions = new_model.predict([test_X])\nprint(predictions)\n\nprint(np.argmax(predictions[0]))\n\nplt.imshow(test_X[0])\nplt.show()\n","sub_path":"MNIST Neural Network.py","file_name":"MNIST Neural Network.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"601559905","text":"import networks.PyTorch.jojo as jojo, argparse, torch.optim as optim\nimport torch.utils.data, shutil, os\nfrom helper.functions import saveStatePytorch\nfrom tensorboardX import SummaryWriter\nfrom datasetClass.structures import loadSiameseDatasetFromFolder\nfrom torchvision import transforms\nimport torch.nn as nn\n\ndef getActivation(model,input,outpu):\n print('oh nooo')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Train Deep Models')\n parser.add_argument('-p', '--pathBase', default='generated_images_lbp_frgc', help='Path for faces', required=False)\n parser.add_argument('--others', help='Path other siamese data', required=True)\n parser.add_argument('-b', '--batch', type=int, default=500, help='Size of the batch', required=False)\n parser.add_argument('-c', '--classNumber', type=int, default=466, help='Quantity of classes', required=False)\n parser.add_argument('-e', '--epochs', type=int, default=10, help='Epochs to be run', required=False)\n parser.add_argument('--fineTuneWeights', default=None, help='Do fine tuning with weights', required=False)\n parser.add_argument('--output', default=None, help='Output Folder', required=False)\n parser.add_argument('--extension', help='Extension from files', required=False, default='png')\n parser.add_argument('--layers', help='Quantitye of layers', required=False, default=None)\n parser.add_argument('--learningRate', help='Learning Rate', required=False, default=0.001, type=float)\n args = parser.parse_args()\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n print('Carregando dados')\n folds = loadSiameseDatasetFromFolder(args.pathBase, otherFolds=args.others.split('__'), validationSize='auto')\n gal_loader = torch.utils.data.DataLoader(folds[0], batch_size=args.batch, shuffle=True)\n pro_loader = torch.utils.data.DataLoader(folds[1], batch_size=args.batch, shuffle=False)\n\n if os.path.exists(args.output):\n shutil.rmtree(args.output)\n\n print('Criando diretorio')\n os.makedirs(args.output)\n muda = jojo.SyameseJolyne(args.classNumber)\n muda.to(device)\n\n print('Criando otimizadores')\n optimizer = optim.SGD(muda.parameters(),lr=args.learningRate)\n scheduler = optim.lr_scheduler.StepLR(optimizer, 20, gamma=0.8)\n criterion = nn.CrossEntropyLoss().to(device)\n\n print('Iniciando treino')\n if args.fineTuneWeights is not None:\n print('Loading Pre-trained')\n checkpoint = torch.load(args.fineTuneWeights)\n #optimizer.load_state_dict(checkpoint['optimizer'])\n muda.load_state_dict(checkpoint['state_dict'])\n\n cc = SummaryWriter()\n bestForFold = bestForFoldTLoss = 500000\n bestRankForFold = -1\n print(muda)\n for ep in range(args.epochs):\n ibl = ibr = ibtl = ' '\n muda.train()\n scheduler.step()\n lossAcc = []\n for bIdx, (currBatch, currTargetBatch) in enumerate(gal_loader):\n #currTargetBatch, currBatch = currTargetBatch.to(device), currBatch.to(device)\n currBatch[0] = currBatch[0].to(device)\n currBatch[1] = currBatch[1].to(device)\n output, features = muda(currBatch)\n\n loss = criterion(output, currTargetBatch.to(device))\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n lossAcc.append(loss.item())\n\n lossAvg = sum(lossAcc) / len(lossAcc)\n cc.add_scalar('GioGioFullTraining/fullData/loss', lossAvg, ep)\n\n muda.eval()\n total = 0\n correct = 0\n loss_val = []\n with torch.no_grad():\n for bIdx, (currBatchProbe, currTargetBatchProbe) in enumerate(pro_loader):\n currBatchProbe[0] = currBatchProbe[0].to(device)\n currBatchProbe[1] = currBatchProbe[1].to(device)\n currTargetBatchProbe = currTargetBatchProbe.to(device)\n\n outputs, fs = muda(currBatchProbe)\n _, predicted = torch.max(outputs.data, 1)\n\n loss = criterion(outputs, currTargetBatchProbe)\n loss_val.append(loss)\n\n total += currTargetBatchProbe.size(0)\n correct += (predicted == currTargetBatchProbe).sum().item()\n\n cResult = correct / total\n tLoss = sum(loss_val) / len(loss_val)\n cc.add_scalar('GioGioFullTraining/fullData/accuracy', cResult, ep)\n cc.add_scalar('GioGioFullTraining/fullData/Validation_loss', tLoss, ep)\n\n state_dict = muda.state_dict()\n opt_dict = optimizer.state_dict()\n fName = '%s_current.pth.tar' % ('jolyne')\n fName = os.path.join(args.output, fName)\n saveStatePytorch(fName, state_dict, opt_dict, ep + 1)\n\n if bestRankForFold < cResult:\n ibr = 'X'\n fName = '%s_best_rank.pth.tar' % ('jolyne')\n fName = os.path.join(args.output, fName)\n saveStatePytorch(fName, state_dict, opt_dict, ep + 1)\n bestRankForFold = cResult\n\n if bestForFold > lossAvg:\n ibl = 'X'\n fName = '%s_best_loss.pth.tar' % ('jolyne')\n fName = os.path.join(args.output, fName)\n saveStatePytorch(fName, state_dict, opt_dict, ep + 1)\n bestForFold = lossAvg\n\n if bestForFoldTLoss > tLoss:\n ibtl = 'X'\n fName = '%s_best_val_loss.pth.tar' % ('jolyne')\n fName = os.path.join(args.output, fName)\n saveStatePytorch(fName, state_dict, opt_dict, ep + 1)\n bestForFoldTLoss = tLoss\n\n print(\n '[EPOCH %03d] Accuracy of the network on the %d validating images: %.2f %% Training Loss %.5f Validation Loss %.5f [%c] [%c] [%c]' % (\n ep, total, 100 * cResult, lossAvg, tLoss, ibl, ibtl, ibr))","sub_path":"trainTestSiamesePytorch.py","file_name":"trainTestSiamesePytorch.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"230797507","text":"import RPi.GPIO as GPIO\n\nGPIO_modeSel = 16\nGPIO_LED = 21\n\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(GPIO_modeSel,GPIO.IN)\nGPIO.setup(GPIO_LED,GPIO.OUT)\n\nGPIO.output(GPIO_LED, False)\n\nFlag = False\nprev = False\nwhile True:\n try:\n\n if GPIO.input(GPIO_modeSel) and Flag:\n print(\"In full battery mode\")\n GPIO.output(GPIO_LED, True)\n Flag = False\n elif not GPIO.input(GPIO_modeSel) and Flag:\n print(\"In battery saver mode\")\n GPIO.output(GPIO_LED, False)\n Flag = False\n else:\n curr = GPIO.input(GPIO_modeSel)\n if prev != curr:\n Flag = True\n prev = curr\n \n except KeyboardInterrupt:\n\n GPIO.cleanup()\n","sub_path":"program_Tests/test_switch.py","file_name":"test_switch.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"418317917","text":"# burgers.py\nfrom flask_app import app\nfrom flask_bcrypt import Bcrypt\nfrom flask import render_template,redirect,request,session,flash\nfrom flask_app.models.user import User\nfrom flask_app.models.recipe import Recipe\n\n\nbcrypt = Bcrypt(app)\n\n#Login and Registration\n@app.route(\"/\")\ndef index():\n users = User.get_all()\n print(users)\n return render_template(\"index.html\")\n\n@app.route(\"/recipes/new\")\ndef new_recipe():\n logged_in = bool(session)\n\n if not logged_in:\n return redirect('/')\n \n return render_template(\"create_recipe.html\")\n\n@app.route('/create_recipe', methods=[\"POST\"])\ndef create_recipe():\n radio_check = None\n\n if not Recipe.validate_recipe(request.form):\n return redirect('/recipes/new')\n\n if request.form[\"flexRadioDefault\"] == 'On':\n radio_check = \"Yes\"\n else:\n radio_check = \"No\"\n\n data = {\n \"name\": request.form[\"name\"],\n \"description\" : request.form[\"description\"],\n \"instructions\" : request.form[\"instructions\"],\n \"flexRadioDefault\" : radio_check,\n \"date\" : request.form[\"date\"],\n \"user_id\": session['user_id']\n }\n\n Recipe.save(data)\n return redirect(\"/dashboard\")\n\n@app.route('/recipes/')\ndef get_recipe(recipe_id):\n logged_in = bool(session)\n\n if not logged_in:\n return redirect('/')\n\n data = {\n 'id': recipe_id\n }\n\n recipe_info = Recipe.get_one(data)\n\n user_data = {\n 'id': session['user_id']\n }\n\n user_name = User.get_one(user_data)\n\n return render_template(\"instructions.html\", recipe_info= recipe_info, user_name=user_name)\n\n@app.route('/delete/')\ndef delete_recipe(recipe_id):\n data = {\n 'id': recipe_id\n }\n\n print(data)\n print('^^^^^^^^')\n\n Recipe.delete(data)\n\n return redirect('/dashboard')\n\n@app.route('/edit/')\ndef edit_recipe(recipe_id):\n logged_in = bool(session)\n\n if not logged_in:\n return redirect('/')\n\n data = {\n 'id': recipe_id\n }\n\n edit_recipe = Recipe.get_one(data)\n\n return render_template('edit.html', edit_recipe= edit_recipe)\n\n@app.route(\"/edit//update\", methods=[\"POST\"])\ndef update_recipe(recipe_id):\n\n if not Recipe.validate_recipe(request.form):\n return redirect(f'/edit/{recipe_id}')\n\n if request.form[\"flexRadioDefault\"] == 'On':\n radio_check = \"Yes\"\n else:\n radio_check = \"No\"\n\n data = {\n \"id\": recipe_id,\n \"name\": request.form[\"name\"],\n \"description\" : request.form[\"description\"],\n \"instructions\" : request.form[\"instructions\"],\n \"flexRadioDefault\" : radio_check,\n \"date\" : request.form[\"date\"],\n \"user_id\": session['user_id']\n }\n Recipe.update(data)\n \n return redirect('/dashboard')\n\n#------------------------------------------------------------------\n#Login/Register classes\n@app.route('/register_email', methods=[\"POST\"])\ndef register_email():\n\n if not User.validate_user(request.form):\n # we redirect to the template with the form.\n return redirect('/')\n \n email_check = { \"email\" : request.form[\"email\"] }\n user_in_db = User.get_by_email(email_check)\n\n if user_in_db:\n flash(\"Email is already registered\")\n return redirect(\"/\")\n\n pw_hash = bcrypt.generate_password_hash(request.form['password'])\n print(pw_hash)\n # put the pw_hash into the data dictionary\n data = {\n \"first_name\": request.form['first_name'],\n \"last_name\": request.form['last_name'],\n \"email\": request.form['email'],\n \"password\" : pw_hash\n }\n\n user_id = User.save(data)\n\n session['user_id'] = user_id\n\n session['first_name'] = request.form['first_name']\n return redirect('/dashboard')\n\n\n@app.route('/validate_email', methods=[\"POST\"])\ndef validate_email():\n\n data = { \"email_login\" : request.form[\"email_login\"] }\n user_in_db = User.get_by_email(data)\n\n if not user_in_db:\n flash(\"Invalid Email/Password\")\n return redirect(\"/\")\n\n if not bcrypt.check_password_hash(user_in_db.password, request.form['password_login']):\n flash(\"Invalid Email/Password\")\n return redirect(\"/\")\n \n session['user_id'] = user_in_db.id\n\n return redirect('/dashboard')\n\n#Next two classes are used to see if the user has logged out and it clears the session info\n@app.route(\"/dashboard\")\ndef success_login():\n logged_in = bool(session)\n\n if not logged_in:\n return redirect('/')\n\n data = {\n 'id': session['user_id']\n }\n print(data)\n fav_recipes = User.get_user_info(data)\n print(fav_recipes)\n print('$$$$$$$$$')\n\n user_name = User.get_one(data)\n\n return render_template(\"dashboard.html\", fav_recipes=fav_recipes, user_name=user_name)\n\n@app.route(\"/logout\")\ndef logout():\n session.clear()\n return redirect('/')\n","sub_path":"flask_app/controllers/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"250959271","text":"\"\"\" Server side Python code \"\"\"\nimport socket\nimport os\n\nhote = ''\nport = 12800\n\nconnexion_principale = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nconnexion_principale.bind((hote, port))\nconnexion_principale.listen(5)\nprint(\"The server is now listening on the port {}\".format(port))\n\nconnexion_avec_client, infos_connexion = connexion_principale.accept()\n\nmsg_recu = b\"\"\nwhile msg_recu != b\"fin\":\n msg_recu = connexion_avec_client.recv(1024)\n # L'instruction ci-dessous peut lever une exception si le message\n # Réceptionné comporte des accents\n print(msg_recu.decode())\n connexion_avec_client.send(b\"5 / 5\")\n\nprint(\"Closing the connection\")\nconnexion_avec_client.close()\nconnexion_principale.close()\nos.system(\"pause\")","sub_path":"P3-Client-Server-Communication/V1-Simplified/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"281813149","text":"# -*- encoding: utf-8 -*-\nfrom openerp.osv import osv\nimport base64\nfrom openerp import models, fields, api\nimport codecs\nimport pprint,string\n\nclass account_sale_register_report_wizard_detallado(osv.TransientModel):\n\t_name='account.sale.register.report.wizard.detallado'\n\tperiod_ini = fields.Many2one('account.period','Periodo Inicial',required=True)\n\tperiod_end = fields.Many2one('account.period','Periodo Final',required=True)\n\tfiscalyear_id = fields.Many2one('account.fiscalyear','Año Fiscal',required=True)\n\n\n\n\t@api.onchange('fiscalyear_id')\n\tdef onchange_fiscalyear(self):\n\t\tif self.fiscalyear_id:\n\t\t\treturn {'domain':{'period_ini':[('fiscalyear_id','=',self.fiscalyear_id.id )], 'period_end':[('fiscalyear_id','=',self.fiscalyear_id.id )]}}\n\t\telse:\n\t\t\treturn {'domain':{'period_ini':[], 'period_end':[]}}\n\n\t@api.onchange('period_ini')\n\tdef _change_periodo_ini(self):\n\t\tif self.period_ini:\n\t\t\tself.period_end= self.period_ini\n\n\n\t@api.multi\n\tdef do_rebuild(self):\n\t\tperiod_ini = self.period_ini\n\t\tperiod_end = self.period_end\n\t\t\n\t\tfiltro = []\n\t\t\n\t\tself.env.cr.execute(\"\"\"\n\t\t\tselect T.periodo,T.fechaemision,T.tipodocumento, T.serie || '-' || T. numero as numero, T.partner, pp.name_template as producto, aml.quantity as cantidad,\npu.name as unidadmedida,abs(aml.debit-aml.credit) / aml.quantity as PrecioUnitario, (-aml.debit+aml.credit) as subtotal,((-aml.debit+aml.credit)) / (coalesce(T.inafecto,0)+ coalesce(T.valorexp,0)+ coalesce(T.baseimp,0) ) *T.igv as igv, \n\n(-aml.debit+aml.credit) + coalesce(((-aml.debit+aml.credit)) / (coalesce(T.inafecto,0)+ coalesce(T.valorexp,0)+ coalesce(T.baseimp,0) ) *T.igv,0) as total \n, am.id,t.tipodecambio,t.divisa\nfrom get_venta_1_1_1(false,periodo_num('\"\"\" + period_ini.code + \"\"\"'),periodo_num('\"\"\" + period_end.code +\"\"\"')) T\ninner join account_move am on am.id = T.am_id\ninner join account_move_line aml on aml.move_id = am.id\nleft join product_product pp on aml.product_id = pp.id\nleft join product_uom pu on pu.id = aml.product_uom_id\ninner join account_account aa on aml.account_id = aa.id and left(aa.code,1) in ('7','2')\n\n\t\t\"\"\")\n\n\t\tcontenido = self.env.cr.fetchall()\n\n\t\tif True:\n\n\t\t\timport io\n\t\t\tfrom xlsxwriter.workbook import Workbook\n\t\t\toutput = io.BytesIO()\n\t\t\t########### PRIMERA HOJA DE LA DATA EN TABLA\n\t\t\t#workbook = Workbook(output, {'in_memory': True})\n\t\t\tdireccion = self.env['main.parameter'].search([])[0].dir_create_file\n\t\t\tworkbook = Workbook( direccion + 'tempo_libroventas.xlsx')\n\t\t\tworksheet = workbook.add_worksheet(\"Registro Ventas\")\n\t\t\tbold = workbook.add_format({'bold': True})\n\t\t\tnormal = workbook.add_format()\n\t\t\tboldbord = workbook.add_format({'bold': True})\n\t\t\tboldbord.set_border(style=2)\n\t\t\tboldbord.set_align('center')\n\t\t\tboldbord.set_align('vcenter')\n\t\t\tboldbord.set_text_wrap()\n\t\t\tboldbord.set_font_size(9)\n\t\t\tboldbord.set_bg_color('#DCE6F1')\n\n\n\t\t\ttitle = workbook.add_format({'bold': True})\n\t\t\ttitle.set_align('center')\n\t\t\ttitle.set_align('vcenter')\n\t\t\ttitle.set_text_wrap()\n\t\t\ttitle.set_font_size(18)\n\t\t\tnumbertres = workbook.add_format({'num_format':'0.000'})\n\t\t\tnumberdos = workbook.add_format({'num_format':'0.00'})\n\t\t\tbord = workbook.add_format()\n\t\t\tbord.set_border(style=1)\n\t\t\tnumberdos.set_border(style=1)\n\t\t\tnumbertres.set_border(style=1)\t\t\t\n\t\t\tx= 5\t\t\t\t\n\t\t\ttam_col = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\t\t\ttam_letra = 1.2\n\t\t\timport sys\n\t\t\treload(sys)\n\t\t\tsys.setdefaultencoding('iso-8859-1')\n\n\n\t\t\tworksheet.merge_range(0,0,0,11,\"REGISTRO DE VENTA\",title)\n\n\t\t\tworksheet.write(1,0, \"Registro Ventas:\", bold)\n\t\t\t\n\t\t\tworksheet.write(1,1, self.period_ini.name, normal)\n\t\t\t\n\t\t\tworksheet.write(1,2, self.period_end.name, normal)\n\t\t\t\n\t\t\tworksheet.write(2,0, \"Fecha:\",bold)\n\t\t\t\n\t\t\timport datetime\n\t\t\tworksheet.write(2,1, str(datetime.datetime.today())[:10], normal)\n\t\t\t\n\n\t\t\tworksheet.write(4,0, \"Periodo\",boldbord)\n\t\t\tworksheet.write(4,1, \"Fecha de Factura\",boldbord)\n\t\t\tworksheet.write(4,2, \"Tipo de Documento\",boldbord)\n\t\t\tworksheet.write(4,3, \"Nro de Factura\",boldbord)\n\t\t\tworksheet.write(4,4, \"Cliente\",boldbord)\n\t\t\tworksheet.write(4,5, \"Producto\",boldbord)\n\t\t\tworksheet.write(4,6, \"Cantidad\",boldbord)\n\t\t\tworksheet.write(4,7, \"Unidad De Medida\",boldbord)\n\t\t\tworksheet.write(4,8, \"Precio Unitario\",boldbord)\n\t\t\tworksheet.write(4,9, \"Subtotal\",boldbord)\n\t\t\tworksheet.write(4,10, \"IGV\",boldbord)\n\t\t\tworksheet.write(4,11, \"Total\",boldbord)\n\t\t\tworksheet.write(4,12, \"Tipo de Cambio\",boldbord)\n\t\t\tworksheet.write(4,13, \"Moneda\",boldbord)\n\n\t\t\tfor line in contenido:\n\t\t\t\ttype_code = line[2] if line[2] else ''\n\t\t\t\tqty = line[6] if line[6] else 0\n\t\t\t\tif type_code=='07':\n\t\t\t\t\tqty*=-1\n\t\t\t\tworksheet.write(x,0,line[0] if line[0] else '' ,bord )\n\t\t\t\tworksheet.write(x,1,line[1] if line[1] else '' ,bord )\n\t\t\t\tworksheet.write(x,2,type_code ,bord )\n\t\t\t\tworksheet.write(x,3,line[3] if line[3] else '' ,bord )\n\t\t\t\tworksheet.write(x,4,line[4] if line[4] else '' ,bord )\n\t\t\t\tworksheet.write(x,5,line[5] if line[5] else '' ,bord )\n\t\t\t\tworksheet.write(x,6,qty,numberdos )\n\t\t\t\tworksheet.write(x,7,line[7] if line[7] else '' ,bord )\n\t\t\t\tworksheet.write(x,8,line[8] ,numberdos )\n\t\t\t\tworksheet.write(x,9,line[9] ,numberdos )\n\t\t\t\tworksheet.write(x,10,line[10] ,numberdos )\n\t\t\t\tworksheet.write(x,11,line[11] ,numberdos )\n\t\t\t\tworksheet.write(x,12,line[13] ,numberdos )\n\t\t\t\tworksheet.write(x,13,line[14] ,numberdos )\n\t\t\t\tx+=1\n\n\t\t\ttam_col = [10,10,10,20,18,11,8,11,11,11,11,11,11,11,11,11,5,8,10,8,9]\n\t\t\tworksheet.set_row(0, 30)\n\t\t\talpha = list(string.ascii_uppercase)\n\t\t\tfor i,item in enumerate(tam_col):\n\t\t\t\tworksheet.set_column(alpha[i]+':'+alpha[i],item)\n\t\t\tworkbook.close()\n\t\t\t\n\t\t\tf = open(direccion + 'tempo_libroventas.xlsx', 'rb')\n\t\t\t\n\t\t\tsfs_obj = self.pool.get('repcontab_base.sunat_file_save')\n\t\t\tvals = {\n\t\t\t\t'output_name': 'RegistroVentas.xlsx',\n\t\t\t\t'output_file': base64.encodestring(''.join(f.readlines())),\t\t\n\t\t\t}\n\n\t\t\tmod_obj = self.env['ir.model.data']\n\t\t\tact_obj = self.env['ir.actions.act_window']\n\t\t\tsfs_id = self.env['export.file.save'].create(vals)\n\t\t\tresult = {}\n\t\t\tview_ref = mod_obj.get_object_reference('account_contable_book_it', 'export_file_save_action')\n\t\t\tview_id = view_ref and view_ref[1] or False\n\t\t\tresult = act_obj.read( [view_id] )\n\t\t\treturn {\n\t\t\t \"type\": \"ir.actions.act_window\",\n\t\t\t \"res_model\": \"export.file.save\",\n\t\t\t \"views\": [[False, \"form\"]],\n\t\t\t \"res_id\": sfs_id.id,\n\t\t\t \"target\": \"new\",\n\t\t\t}\n\n\t\t\n","sub_path":"account_sale_register_it_porproducto/wizard/account_sale_register_report_wizard.py","file_name":"account_sale_register_report_wizard.py","file_ext":"py","file_size_in_byte":6407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"539277843","text":"import csv\nimport datetime\nimport os\n\nimport tensorflow as tf\nfrom tensorflow.keras import optimizers\n\nfrom data_tools import get_data, get_kfold, dats_pipleline\nfrom net import resnet18\n\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\ntf.random.set_seed(666)\nacc_headers = ['step', 'acc']\nloss_headers = ['step', 'loss']\n\n\n# @tf.function\ndef train(train_db, test_db, alpha=0.001, name=None):\n if not os.path.exists(\"logs/\" + name):\n os.makedirs(\"logs/\" + name)\n with open(\"logs/\" + name + '/train_acc.csv', 'w')as f:\n f_csv = csv.writer(f)\n f_csv.writerow(acc_headers)\n with open(\"logs/\" + name + '/train_loss.csv', 'w')as f:\n f_csv = csv.writer(f)\n f_csv.writerow(loss_headers)\n with open(\"logs/\" + name + '/test_acc.csv', 'w')as f:\n f_csv = csv.writer(f)\n f_csv.writerow(acc_headers)\n stamp = datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n log_dir = \"logs/\" + name + '/%s' % stamp\n writer = tf.summary.create_file_writer(log_dir)\n model = resnet18(2, alpha, writer) # ResNet18网络\n model.build(input_shape=(None, 112, 112, 3))\n model.summary() # 统计网络参数\n optimizer = optimizers.Adam(lr=1e-4) # 构建优化器\n max_train_step = 0\n with writer.as_default():\n for epoch in range(50): # 训练epoch\n for step, (x, y) in enumerate(train_db):\n with tf.GradientTape() as tape:\n logits = model(x)\n y_onehot = tf.one_hot(y, depth=2)\n # 计算交叉熵\n prob = tf.nn.softmax(logits, axis=1)\n pred = tf.argmax(prob, axis=1)\n y = tf.cast(y, tf.int32)\n pred = tf.cast(pred, tf.int32)\n correct = tf.cast(tf.equal(y, pred), dtype=tf.float32)\n train_acc = tf.reduce_mean(correct)\n loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)\n loss = tf.reduce_mean(loss)\n # 计算梯度信息\n with open(\"logs/\" + name + '/train_acc.csv', 'a+', newline='')as f:\n f_csv = csv.writer(f)\n f_csv.writerow([max_train_step * epoch + step, float(train_acc)])\n with open(\"logs/\" + name + '/train_loss.csv', 'a+', newline='')as f:\n f_csv = csv.writer(f)\n f_csv.writerow([max_train_step * epoch + step, float(loss)])\n tf.summary.scalar(\"loss\", float(loss), step=max_train_step * epoch + step)\n tf.summary.scalar(\"train_acc\", train_acc, step=max_train_step * epoch + step)\n grads = tape.gradient(loss, model.trainable_variables)\n # 更新网络参数\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\n if step % 50 == 0:\n print(epoch, step, 'loss:', float(loss))\n if max_train_step < step:\n max_train_step = step\n total_num = 0\n total_correct = 0\n\n for x, y in test_db:\n logits = model(x)\n prob_test = tf.nn.softmax(logits, axis=1)\n pred_test = tf.argmax(prob_test, axis=1)\n correct_test = tf.cast(tf.equal(pred_test, y), dtype=tf.int32)\n correct_test = tf.reduce_sum(correct_test)\n total_num += x.shape[0]\n total_correct += int(correct_test)\n test_acc = total_correct / total_num\n tf.summary.scalar(\"test_acc\", test_acc, step=max_train_step * epoch + step)\n print(epoch, 'test_acc:', test_acc)\n with open(\"logs/\" + name + '/test_acc.csv', 'a+', newline='')as f:\n f_csv = csv.writer(f)\n f_csv.writerow([max_train_step * epoch + step, float(test_acc)])\n\n\nif __name__ == '__main__':\n X, Y = get_data(\"data/dataset_kaggledogvscat/train\")\n train_X, train_Y, test_X, test_Y = get_kfold(X, Y)\n alpha_list = [0.001, 0.01, 0.1]\n for alpha in alpha_list:\n for i in range(len(train_X)):\n print(\"-\" * 10, \"第\", i + 1, \"次交叉验证\", \"-\" * 10)\n name = str(alpha) + \"_train_\" + str(i + 1)\n train_db = dats_pipleline(train_X[i], train_Y[i], BATCH_SIZE=64)\n test_db = dats_pipleline(test_X[i], test_Y[i], BATCH_SIZE=64)\n train(train_db, test_db, alpha, name)\n","sub_path":"resnet18_train.py","file_name":"resnet18_train.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93733233","text":"from flask import Flask,render_template,request,session,redirect\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom datetime import datetime\r\nfrom flask_mail import Mail\r\nfrom werkzeug.utils import secure_filename\r\nimport json\r\nimport os\r\nimport math\r\n\r\nwith open('config.json','r') as c:\r\n params=json.load(c)[\"params\"]\r\napp=Flask(__name__)\r\nlocal_server=True\r\napp.config['SECRET_KEY'] = 'secret_key'\r\napp.config['UPLOAD_FOLDER']=params['upload_location']\r\napp.config['my_folder']=params['my_folder']\r\napp.config.update(\r\n MAIL_SERVER = 'smtp.gmail.com',\r\n MAIL_PORT = '465',\r\n MAIL_USE_SSL = True,\r\n MAIL_USERNAME = params['gmail-user'],\r\n MAIL_PASSWORD= params['gmail-password']\r\n)\r\nmail = Mail(app)\r\n\r\nif(local_server):\r\n app.config['SQLALCHEMY_DATABASE_URI'] = params['local_uri']\r\nelse:\r\n app.config['SQLALCHEMY_DATABASE_URI'] = params['prod_uri']\r\n\r\n\r\ndb = SQLAlchemy(app)\r\n\r\n\r\nclass Contects(db.Model):\r\n sno = db.Column(db.Integer, primary_key=True)\r\n name = db.Column(db.String(80),nullable=False)\r\n email = db.Column(db.String(20),nullable=False)\r\n phone_num = db.Column(db.String(12),nullable=False)\r\n date = db.Column(db.String(12),nullable=True)\r\n mes = db.Column(db.String(120), nullable=False)\r\n\r\n\r\nclass Post(db.Model):\r\n sno = db.Column(db.Integer, primary_key=True)\r\n title = db.Column(db.String(80),nullable=False)\r\n content = db.Column(db.String(200),nullable=False)\r\n tagline = db.Column(db.String(200),nullable=False)\r\n date = db.Column(db.String(12),nullable=False)\r\n slug = db.Column(db.String(20),nullable=True)\r\n img_name = db.Column(db.String(30),nullable=True)\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n posts=Post.query.filter_by().all()\r\n last=math.ceil(len(posts)/int(params['no_of_posts']))\r\n page=(request.args.get('page'))\r\n if(not str(page).isnumeric()):\r\n page=1\r\n page=int(page)\r\n posts=posts[(page-1)*int(params['no_of_posts']):(page)*int(params['no_of_posts'])]\r\n if page==1:\r\n prev=\"#\"\r\n next=\"/?page=\"+str(page+1)\r\n\r\n elif page==last:\r\n prev=\"/?page=\"+str(page-1)\r\n next = '#'\r\n else:\r\n prev=\"/?page=\"+str(page-1)\r\n next=\"/?page=\"+str(page+1)\r\n\r\n\r\n return render_template(\"index.html\",params=params,post=posts,prev=prev,next=next)\r\n\r\n@app.route(\"/about\")\r\ndef about():\r\n return render_template(\"about.html\",params=params)\r\n\r\n@app.route(\"/gallery\")\r\ndef gallery():\r\n post = Post.query.all()\r\n return render_template(\"gallery.html\",params=params,post=post)\r\n\r\n\r\n@app.route(\"/contact\",methods=['GET','POST'])\r\ndef contact():\r\n if (request.method==\"POST\"):\r\n name=request.form.get('name')\r\n email=request.form.get('email')\r\n phone=request.form.get('phone')\r\n message=request.form.get('message')\r\n entry=Contects(name=name,email=email,phone_num=phone,date=datetime.now(),mes=message)\r\n db.session.add(entry)\r\n db.session.commit()\r\n mail.send_message('New message from user-' + name,\r\n sender=email,\r\n recipients=[params['gmail-user']],\r\n body=\"Message=\"+message + \"\\nPhone=\" + phone+\"\\nEmail=\"+email\r\n )\r\n return render_template(\"contact.html\",params=params)\r\n\r\n@app.route(\"/post\")\r\ndef post():\r\n return render_template(\"post.html\",params=params)\r\n\r\n@app.route(\"/dashboard\", methods=['GET','POST'])\r\ndef dashboard():\r\n\r\n if 'user' in session and session['user']==params['admin_user']:\r\n post = Post.query.all()\r\n return render_template(\"dashboard.html\", params=params, post=post)\r\n if request.method=='POST':\r\n username=request.form.get('uname')\r\n password=request.form.get('pass')\r\n if username==params['admin_user'] and password==params['admin_password']:\r\n session['user']=username\r\n post=Post.query.all()\r\n return render_template(\"dashboard.html\", params=params,post=post)\r\n\r\n return render_template(\"signin.html\",params=params)\r\n\r\n\r\n@app.route(\"/edit/\", methods=['GET','POST'])\r\ndef edit(sno):\r\n if ('user' in session and session['user'] == params['admin_user']):\r\n if request.method == 'POST':\r\n box_title=request.form.get('title')\r\n tagline=request.form.get('tline')\r\n slug=request.form.get('slug')\r\n content=request.form.get('content')\r\n\r\n post=Post.query.filter_by(sno=sno).first()\r\n post.title=box_title\r\n post.tagline=tagline\r\n post.slug=slug\r\n post.content=content\r\n db.session.commit()\r\n return redirect('/edit/'+sno)\r\n\r\n post = Post.query.filter_by(sno=sno).first()\r\n return render_template('edit.html',params=params,post=post)\r\n\r\n\r\n\r\n@app.route(\"/show/\", methods=['GET','POST'])\r\ndef show(sno):\r\n post = Post.query.filter_by(sno=sno).first()\r\n return render_template('show_image.html', params=params, post=post)\r\n\r\n\r\n\r\n@app.route(\"/add/\", methods=['GET','POST'])\r\ndef add(sno):\r\n if ('user' in session and session['user'] == params['admin_user']):\r\n if request.method == 'POST':\r\n box_title=request.form.get('title')\r\n tagline=request.form.get('tline')\r\n slug=request.form.get('slug')\r\n content=request.form.get('content')\r\n f = request.files['file']\r\n\r\n f.save(os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename)))\r\n post=Post(title=box_title,tagline=tagline,content=content,date=datetime.now(),slug=slug,img_name=f.filename)\r\n db.session.add(post)\r\n db.session.commit()\r\n post = Post.query.filter_by(sno=sno).first()\r\n\r\n return render_template('add.html',params=params,sno=sno,post=post)\r\n\r\n\r\n@app.route(\"/delete/\", methods=['GET','POST'])\r\ndef delete(sno):\r\n if 'user' in session and session['user'] == params['admin_user']:\r\n p = Post.query.filter_by(sno=sno).first()\r\n db.session.delete(p)\r\n db.session.commit()\r\n return redirect('/dashboard')\r\n\r\n\r\n\r\n\r\n\r\n@app.route(\"/post/\", methods=['get'])\r\ndef post_route(post_slug):\r\n post=Post.query.filter_by(slug=post_slug).first()\r\n return render_template(\"post.html\",params=params,post=post)\r\n\r\n@app.route(\"/uploader\",methods=['GET','POST'])\r\ndef upload():\r\n if 'user' in session and session['user'] == params['admin_user']:\r\n if request.method == 'POST':\r\n f=request.files['file']\r\n f.save(os.path.join(app.config['my_folder'],secure_filename(f.filename)))\r\n return redirect('/dashboard')\r\n\r\n\r\n@app.route(\"/logout\")\r\ndef logout():\r\n session.pop('user')\r\n return redirect('/dashboard')\r\n\r\n\r\n\r\napp.run(debug=True)\r\n\r\n","sub_path":"new_website/Website using flask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"193797325","text":"valor_dolar = 724.40\nvalor_uf = 29356.90\nvalor_euro = 854.89\n\n\ndef conversor(opcion, moneda):\n pesos = input(\"¿Cuántos pesos tienes?: \")\n pesos = float(pesos)\n resultado = pesos / moneda\n resultado = round(resultado, 2)\n resultado = str(resultado)\n return resultado\n\n\nmenu = \"\"\"\nBienvenido al conversor de monedas 💰\n\n==== Pesos Chilenos ====\n\n1 - Convertir a Dólares\n2 - Convertir a UF\n3 - Convertir a Euros\n\nElige un opción:\n\n\"\"\"\n\nopcion = int(input(menu))\n\nif opcion == 1:\n resultado = conversor(opcion, valor_dolar)\n print('Tienes $'+resultado+' dólares')\nelif opcion == 2:\n resultado = conversor(opcion, valor_uf)\n print('Tienes '+resultado+' UF')\nelif opcion == 3:\n resultado = conversor(opcion, valor_euro)\n print('Tienes '+resultado+' euros')\nelse:\n print('Ingresa una opción correcta')\n","sub_path":"conversor.py","file_name":"conversor.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410035059","text":"# Copyright BurlyLuo .\n# Date:2019-3-17\n# encoding: utf-8\n\n\nfrom kubernetes import client, config\n\n\ndef get_list_pod():\n\tconfig.load_kube_config()\n\n\tv1 = client.CoreV1Api()\n\tprint(\"Listing pods with their IPs:\")\n\tret = v1.list_pod_for_all_namespaces(watch=False)\n\tfor i in ret.items:\n\t\t#print(i)\n\t print(\"%s\\t%s\\t%s\\t%s\\t%s\" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name, i.spec.node_name, i.metadata.labels))\n\t\n\nif __name__ == '__main__':\n\tget_list_pod()\n","sub_path":"kubernetes-python-clinet/get_list_pod.py","file_name":"get_list_pod.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"93059418","text":"import tensorflow as tf\nimport numpy as np\nimport os\nfrom imutils import paths\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelBinarizer\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\n\n\n#This function loads the images and pre-process them as well using their path provided as arguement and return the Test and Train set respectively\ndef load_images_and_labels(images_path):\n print(\"[INFO] Loading Images......\")\n imagePaths = list(paths.list_images(images_path))\n\n data = []\n labels = []\n\n for imagePath in imagePaths:\n # get class label from folder name\n label = imagePath.split(os.path.sep)[-2]\n # our model requrie (224,224)\n image = load_img(imagePath, target_size=(224, 224))\n image = img_to_array(image)\n\n image = preprocess_input(image)\n\n data.append(image)\n labels.append(label)\n\n\n # convert the data and labels to NumPy arrays\n data = np.array(data, dtype=\"float32\")\n labels = np.array(labels)\n\n\n # perform one-hot encoding on the labels\n lb = LabelBinarizer()\n labels = lb.fit_transform(labels)\n\n labels = tf.keras.utils.to_categorical(labels, 2)\n\n (trainX, testX, trainY, testY) = train_test_split(data, labels,\n test_size=0.20, stratify=labels, random_state=42)\n print(\"[INFO] Loaded\")\n\n return trainX, testX, trainY, testY\n\n\n\n","sub_path":"Files/Data_Loading.py","file_name":"Data_Loading.py","file_ext":"py","file_size_in_byte":1582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"631912202","text":"class Solution:\n def longestPalindrome(self, s: str) -> str:\n List, res_list = [], []\n for i in range(len(s)):\n for j in range(len(s), i, -1):\n if s[i:j] == s[i:j][::-1]:\n List.append(j - i)\n res_list.append(s[i:j])\n if len(res_list) == 0:\n return \"\"\n else:\n m = List.index(max(List))\n return res_list[m]\n","sub_path":"#5.py","file_name":"#5.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"386405301","text":"from flask import Flask, render_template, request, jsonify\nimport sqlite3 as sql\nimport random\napp = Flask(__name__)\n\nDATABASE_FILE = \"database.db\"\nDEFAULT_BUGGY_ID = \"1\"\n\nBUGGY_RACE_SERVER_URL = \"http://rhul.buggyrace.net\"\n\n\n#------------------------------------------------------------\n# the index page\n#------------------------------------------------------------\n@app.route('/')\ndef home():\n return render_template('index.html', server_url=BUGGY_RACE_SERVER_URL)\n\n#------------------------------------------------------------\n# creating a new buggy:\n# if it's a POST request process the submitted data\n# but if it's a GET request, just show the form\n#------------------------------------------------------------\n@app.route('/new', methods = ['POST', 'GET'])\ndef create_buggy():\n if request.method == 'GET':\n return render_template(\"buggy-form.html\", buggy=None)\n elif request.method == 'POST':\n msg=\"\"\n buggy_id = request.form['id']\n flag_color = request.form['flag_color']\n flag_color_secondary = request.form['flag_color_secondary']\n flag_pattern = request.form['flag_pattern']\n qty_wheels = request.form['qty_wheels']\n if not qty_wheels.isdigit():\n msg = f\"This is not a number!:{qty_wheels}\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n elif int(qty_wheels)%2 != 0:\n msg = f\"Wheels need to be an even number!:{qty_wheels}\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n qty_tyres = request.form['qty_tyres']\n if not qty_tyres.isdigit():\n msg = f\"This is not a number!:{qty_tyres}\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n if qty_wheels>qty_tyres:\n msg = f\"Quantity of tyres must be equal to or greater than the number of wheels! : {qty_tyres}\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n tyres = request.form['tyres']\n power_type = request.form['power_type']\n power_units = request.form['power_units']\n if not power_units.isdigit():\n msg = f\"This is not a number!:{power_units}\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n aux_power_type = request.form['aux_power_type']\n aux_power_units = request.form['aux_power_units']\n if not aux_power_units.isdigit():\n msg = f\"This is not a number!:{aux_power_units}\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n if (aux_power_type == \"fusion\" or \\\n aux_power_type == \"thermo\" or \\\n aux_power_type == \"solar\" or \\\n aux_power_type == \"wind\" \\\n and int(aux_power_units)>1) :\n msg = f\"Only one unit of this power type is allowed:{aux_power_type}\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n hamster_booster = request.form['hamster_booster']\n if (power_type != \"hamster\" and \\\n aux_power_type != \"hamster\" \\\n and int(hamster_booster)>0):\n msg = f\"Hamster boosters only available with hamster power!\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n armour = request.form['armour']\n attack = request.form['attack']\n qty_attacks = request.form['qty_attacks']\n if not qty_attacks.isdigit():\n msg = f\"This is not a number!:{qty_attacks}\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n if (attack == \"none\" \\\n and int(qty_attacks)>0):\n msg = f\"You have no offensive capability : Number of attacks in race\"\n return render_template('buggy-form.html', buggy=request.form, msg = msg)\n fireproof = request.form['fireproof']\n insulated = request.form['insulated']\n antibiotic = request.form['antibiotic']\n banging = request.form['banging']\n algo = request.form['algo']\n #msg = f\"flag-color={flag_color}\", #\"flag_color_secondary={flag_color_secondary}\", \"flag_pattern={flag_pattern}\", \"qty_wheels={qty_wheels}\", \"qty_tyres={qty_tyres}\", \"tyres={tyres}\", \"power_type={power_type}\", \"power_units={power_units}\", \"aux_power_type={aux_power_type}\", \"aux_power_units={aux_power_units}\"\n try:\n with sql.connect(DATABASE_FILE) as con:\n cur = con.cursor()\n if buggy_id.isdigit(): \n cur.execute(\"UPDATE buggies set flag_color=?, flag_color_secondary=?, flag_pattern=?, qty_wheels=?, qty_tyres=?, tyres=?, power_type=?, power_units=?, aux_power_type=?, aux_power_units=?, hamster_booster=?, armour=?, attack=?, qty_attacks=?, fireproof=?, insulated=?, antibiotic=?, banging=?, algo=? WHERE id=?\", (flag_color, flag_color_secondary, flag_pattern, qty_wheels, qty_tyres, tyres, power_type, power_units, aux_power_type, aux_power_units, hamster_booster, armour, attack, qty_attacks, fireproof, insulated, antibiotic, banging, algo, buggy_id))\n else:\n cur.execute(\"INSERT INTO buggies (flag_color, flag_color_secondary, flag_pattern, qty_wheels, qty_tyres, tyres, power_type, power_units, aux_power_type, aux_power_units, hamster_booster, armour, attack, qty_attacks, fireproof, insulated, antibiotic, banging, algo) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",(flag_color, flag_color_secondary, flag_pattern, qty_wheels, qty_tyres, tyres, power_type, power_units, aux_power_type, aux_power_units, hamster_booster, armour, attack, qty_attacks, fireproof, insulated, antibiotic, banging, algo))\n con.commit()\n msg = \"Record successfully saved\"\n except Exception as e:\n con.rollback()\n msg = \"error in update operation\" + str(e)\n finally:\n con.close()\n return render_template(\"updated.html\", msg = msg)\n\n#------------------------------------------------------------\n# a page for displaying the buggy\n#------------------------------------------------------------\n@app.route('/buggy')\ndef show_buggies():\n con = sql.connect(DATABASE_FILE)\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"SELECT * FROM buggies\")\n records = cur.fetchall(); \n buggies=[]\n for record in records:\n buggy={}\n for k in record.keys():\n buggy[k]=record[k]\n price_tyres = {\"knobbly\":15, \"slick\":10, \"steelband\":20, \"reactive\":40, \"maglev\":50}\n buggy['cost_tyres'] = price_tyres[record[\"tyres\"]]*int(record[\"qty_tyres\"])\n price_power = {\"petrol\":4, \"fusion\":400, \"steam\":3, \"bio\":5, \"electric\":20, \"rocket\":16, \"hamster\":3, \"thermo\":300, \"solar\":40, \"wind\":20}\n buggy['cost_primary_power'] = price_power[record[\"power_type\"]]*int(record[\"power_units\"])\n buggy['cost_backup_power'] = price_power[record[\"aux_power_type\"]]*int(record[\"aux_power_units\"])\n price_hamster_booster = 5\n buggy['cost_hamster_booster'] = price_hamster_booster*int(record[\"hamster_booster\"])\n price_armour = {\"none\":0, \"wood\":40, \"aluminium\":200, \"thinsteel\":100, \"thicksteel\":200, \"titanium\":290}\n wheel_value = int(record[\"qty_wheels\"])-4\n if wheel_value>0:\n buggy['cost_armour'] = price_armour[record[\"armour\"]]+(price_armour[record[\"armour\"]]*(wheel_value*0.1))\n else:\n buggy['cost_armour'] = price_armour[record[\"armour\"]]\n price_offence = {\"none\":0, \"spike\":5, \"flame\":20, \"charge\":28, \"biohazard\":30}\n buggy['cost_offence'] = price_offence[record[\"attack\"]]*int(record[\"qty_attacks\"])\n price_fireproof = {\"yes\":70, \"no\":0}\n buggy['cost_fireproof'] = price_fireproof[record[\"fireproof\"]]\n price_insulated = {\"yes\":100, \"no\":0}\n buggy['cost_insulated'] = price_insulated[record[\"insulated\"]]\n price_antibiotic = {\"yes\":90, \"no\":0}\n buggy['cost_antibiotic'] = price_antibiotic[record[\"antibiotic\"]]\n price_banging = {\"yes\":42, \"no\":0}\n buggy['cost_banging'] = price_banging[record[\"banging\"]]\n buggy['total_cost'] = buggy['cost_tyres']+buggy['cost_primary_power']+buggy['cost_backup_power']+buggy['cost_hamster_booster']+buggy['cost_armour']+buggy['cost_offence']+buggy['cost_fireproof']+buggy['cost_insulated']+buggy['cost_antibiotic']+buggy['cost_banging']\n buggies.append(buggy)\n return render_template(\"buggy.html\", buggies = buggies)\n\n#------------------------------------------------------------\n# a page for displaying the buggy\n#------------------------------------------------------------\n\n\n@app.route('/edit/')\ndef edit_buggy(buggy_id):\n con = sql.connect(DATABASE_FILE)\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"SELECT * FROM buggies WHERE id=?\", (buggy_id,))\n record = cur.fetchone(); \n return render_template(\"buggy-form.html\", buggy=record)\n\n@app.route('/autofill', methods = ['POST'])\ndef autofill():\n if request.method == 'POST':\n msg=\"\"\n buggy_id = request.form['id']\n colour=[\"red\",\"orange\",\"yellow\",\"green\",\"blue\",\"black\",\"white\"]\n flag_color = random.choice(colour)\n flag_color_secondary = random.choice(colour)\n flag=[\"plain\",\"vstripe\",\"hstripe\",\"dstripe\",\"checker\",\"spot\"]\n flag_pattern = random.choice(flag)\n number=[\"0\",\"2\",\"4\",\"6\",\"8\",\"10\"]\n qty_wheels = random.choice(number)\n qty_tyres = int(qty_wheels) + random.randint(0,10)\n typetyres=[\"knobbly\",\"slick\",\"steelband\",\"reactive\",\"maglev\"]\n tyres = random.choice(typetyres)\n power=[\"petrol\",\"fusion\",\"steam\",\"bio\",\"electric\",\"rocket\",\"hamster\",\"thermo\",\"solar\",\"wind\"]\n power_type = random.choice(power)\n power_units = random.randint(0,10)\n aux_power_type = random.choice(power)\n aux_power_units = random.randint(0,10)\n if (aux_power_type == \"fusion\" or \\\n aux_power_type == \"thermo\" or \\\n aux_power_type == \"solar\" or \\\n aux_power_type == \"wind\"):\n aux_power_units=1\n hamster_booster = random.randint(0,10)\n if (power_type != \"hamster\" and \\\n aux_power_type != \"hamster\"):\n hamster_booster=0\n typearmour=[\"none\",\"wood\",\"aluminium\",\"thinsteel\",\"thicksteel\",\"titanium\"]\n armour = random.choice(typearmour)\n typeattack=[\"none\",\"spike\",\"flame\",\"biohazard\",\"charge\"]\n attack = random.choice(typeattack)\n qty_attacks = random.randint(0, 10)\n boolean=[\"yes\", \"no\"]\n fireproof = random.choice(boolean)\n insulated = random.choice(boolean)\n antibiotic = random.choice(boolean)\n banging = random.choice(boolean)\n typealgo=[\"defensive\",\"steady\",\"offensive\",\"titfortat\",\"random\"]\n algo = random.choice(typealgo)\n try:\n with sql.connect(DATABASE_FILE) as con:\n cur = con.cursor()\n if buggy_id.isdigit(): \n cur.execute(\"UPDATE buggies set flag_color=?, flag_color_secondary=?, flag_pattern=?, qty_wheels=?, qty_tyres=?, tyres=?, power_type=?, power_units=?, aux_power_type=?, aux_power_units=?, hamster_booster=?, armour=?, attack=?, qty_attacks=?, fireproof=?, insulated=?, antibiotic=?, banging=?, algo=? WHERE id=?\", (flag_color, flag_color_secondary, flag_pattern, qty_wheels, qty_tyres, tyres, power_type, power_units, aux_power_type, aux_power_units, hamster_booster, armour, attack, qty_attacks, fireproof, insulated, antibiotic, banging, algo, buggy_id))\n else:\n cur.execute(\"INSERT INTO buggies (flag_color, flag_color_secondary, flag_pattern, qty_wheels, qty_tyres, tyres, power_type, power_units, aux_power_type, aux_power_units, hamster_booster, armour, attack, qty_attacks, fireproof, insulated, antibiotic, banging, algo) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)\",(flag_color, flag_color_secondary, flag_pattern, qty_wheels, qty_tyres, tyres, power_type, power_units, aux_power_type, aux_power_units, hamster_booster, armour, attack, qty_attacks, fireproof, insulated, antibiotic, banging, algo))\n con.commit()\n msg = \"Record successfully saved\"\n except Exception as e:\n con.rollback()\n msg = \"error in update operation\" + str(e)\n finally:\n con.close()\n return render_template(\"updated.html\", msg = msg)\n#------------------------------------------------------------\n# get JSON from current record\n# this is still probably right, but we won't be\n# using it because we'll be dipping diectly into the\n# database\n#------------------------------------------------------------\n@app.route('/json')\ndef summary():\n con = sql.connect(DATABASE_FILE)\n con.row_factory = sql.Row\n cur = con.cursor()\n cur.execute(\"SELECT * FROM buggies WHERE id=? LIMIT 1\", (DEFAULT_BUGGY_ID))\n return jsonify(\n {k: v for k, v in dict(zip(\n [column[0] for column in cur.description], cur.fetchone())).items()\n if (v != \"\" and v is not None)\n }\n )\n\n#------------------------------------------------------------\n# delete the buggy\n# don't want DELETE here, because we're anticipating\n# there always being a record to update (because the\n# student needs to change that!)\n#------------------------------------------------------------\n@app.route('/delete/', methods = ['POST'])\ndef delete_buggy(buggy_id):\n try:\n msg = \"deleting buggy\"\n with sql.connect(DATABASE_FILE) as con:\n cur = con.cursor()\n cur.execute(\"DELETE FROM buggies WHERE id=?\", (buggy_id))\n con.commit()\n msg = \"Buggy deleted\"\n except:\n con.rollback()\n msg = \"error in delete operation\"\n finally:\n con.close()\n return render_template(\"updated.html\", msg = msg)\n\n@app.route('/poster')\ndef poster():\n return render_template(\"poster.html\")\n\nif __name__ == '__main__':\n print(\"start\")\n app.run(debug = True, host=\"0.0.0.0\")\n print(\"finish\")\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"36860854","text":"import os\r\n\r\ndef gets(prompt=None):\r\n\tprompt = \"%s \" % (prompt or \"%\")\r\n\tif hasattr(__builtins__, \"raw_input\"):\r\n\t\treturn raw_input(prompt)\r\n\telif hasattr(__builtins__, \"input\"):\r\n\t\treturn input(prompt)\r\n\telse:\r\n\t\traise NotImplementedError\r\n\r\nclass ParserError(Exception):\r\n\tpass\r\n\r\nclass Stack(list):\r\n\tdef push(self, *items):\r\n\t\treturn self.extend(items)\r\n\r\n\t@property\r\n\tdef last(self):\r\n\t\treturn self[-1]\r\n\r\n\t@last.setter\r\n\tdef last(self, value):\r\n\t\tself[-1] = value\r\n\r\n\tdef prev(self, n=1):\r\n\t\treturn self[-1-n]\r\n\r\nclass Parser(object):\r\n\tescapes = {\r\n\t\t\"e\": \"\\033\",\r\n\t\t\"n\": \"\\n\",\r\n\t\t\"t\": \"\\t\",\r\n\t}\r\n\r\n\tparse_bquoted = True\r\n\r\n\tdef __init__(self):\r\n\t\tself.reset()\r\n\r\n\tdef reset(self):\r\n\t\tself.state = Stack([\"raw\"])\r\n\t\tself.cur = \"\"\r\n\t\tself.words = []\r\n\t\tself.append = False\r\n\t\treturn True\r\n\r\n\tdef feed(self, line, multiline=True):\r\n\t\ti = 0\r\n\t\tappend = False\r\n\t\tdone = True\r\n\t\tvariables = os.environ\r\n\r\n\t\twhile i <= len(line):\r\n\t\t\tchar = line[i] if i < len(line) else None\r\n\t\t\t#print(\"%r %r %r\" % (self.words, char, self.state))\r\n\t\t\tif self.state.last == \"raw\":\r\n\t\t\t\tif not char or char.isspace():\r\n\t\t\t\t\tif self.cur or append:\r\n\t\t\t\t\t\tself.words.append(self.cur)\r\n\t\t\t\t\t\tself.cur = \"\"\r\n\t\t\t\t\t\tappend = False\r\n\t\t\t\telif char == \"\\\"\":\r\n\t\t\t\t\tself.state.push(\"dquoted\")\r\n\t\t\t\telif char == \"'\":\r\n\t\t\t\t\tself.state.push(\"squoted\")\r\n\t\t\t\telif char == \"{\" and self.parse_bquoted:\r\n\t\t\t\t\tself.state.push(\"bquoted\")\r\n\t\t\t\telif char == \"\\\\\":\r\n\t\t\t\t\tself.state.push(\"escape\")\r\n\t\t\t\telif char == \"$\" and variables is not None:\r\n\t\t\t\t\ttoken = \"\"\r\n\t\t\t\t\tself.state.push(\"variable\")\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.cur += char\r\n\t\t\telif self.state.last == \"escape\":\r\n\t\t\t\tif not char:\r\n\t\t\t\t\tdone = False\r\n\t\t\t\t\ti -= 1\r\n\t\t\t\t\tself.state.pop()\r\n\t\t\t\telif char == \"x\":\r\n\t\t\t\t\ttoken = \"\"\r\n\t\t\t\t\tself.state.last = \"escape hex\"\r\n\t\t\t\telif char in \"0123\":\r\n\t\t\t\t\ttoken = char\r\n\t\t\t\t\tself.state.last = \"escape oct\"\r\n\t\t\t\telif char in self.escapes:\r\n\t\t\t\t\tself.cur += self.escapes[char]\r\n\t\t\t\t\tappend = True\r\n\t\t\t\t\tself.state.pop()\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.cur += char\r\n\t\t\t\t\tself.state.pop()\r\n\t\t\telif self.state.last == \"escape hex\":\r\n\t\t\t\tif char and char in \"0123456789abcdefABCDEF\":\r\n\t\t\t\t\ttoken += char\r\n\t\t\t\t\tif len(token) == 2:\r\n\t\t\t\t\t\tself.cur += chr(int(token, 16))\r\n\t\t\t\t\t\tself.state.pop()\r\n\t\t\t\telse:\r\n\t\t\t\t\traise ParserError(\"invalid hex character %r\" % char)\r\n\t\t\telif self.state.last == \"escape oct\":\r\n\t\t\t\tif char and char in \"01234567\" and len(token) < 3:\r\n\t\t\t\t\ttoken += char\r\n\t\t\t\telse:\r\n\t\t\t\t\tself.cur += chr(int(token, 8))\r\n\t\t\t\t\ti -= 1\r\n\t\t\t\t\tself.state.pop()\r\n\t\t\telif self.state.last == \"dquoted\":\r\n\t\t\t\tif char == \"\\\"\":\r\n\t\t\t\t\tappend = True\r\n\t\t\t\t\tself.state.pop()\r\n\t\t\t\telif char == \"\\\\\":\r\n\t\t\t\t\tself.state.push(\"escape\")\r\n\t\t\t\telif char == \"$\" and variables is not None:\r\n\t\t\t\t\ttoken = \"\"\r\n\t\t\t\t\tself.state.push(\"variable\")\r\n\t\t\t\telif char:\r\n\t\t\t\t\tself.cur += char\r\n\t\t\t\telif multiline:\r\n\t\t\t\t\tdone = False\r\n\t\t\t\t\tbreak\r\n\t\t\t\telse:\r\n\t\t\t\t\traise ParserError(\"missing closing \\\"\")\r\n\t\t\telif self.state.last == \"squoted\":\r\n\t\t\t\tif char == \"'\":\r\n\t\t\t\t\tappend = True\r\n\t\t\t\t\tself.state.pop()\r\n\t\t\t\telif char:\r\n\t\t\t\t\tself.cur += char\r\n\t\t\t\telif multiline:\r\n\t\t\t\t\tdone = False\r\n\t\t\t\t\tbreak\r\n\t\t\t\telse:\r\n\t\t\t\t\traise ParserError(\"missing closing '\")\r\n\t\t\telif self.state.last == \"bquoted\":\r\n\t\t\t\tif char == \"}\":\r\n\t\t\t\t\tif self.state.prev(1) == \"bquoted\":\r\n\t\t\t\t\t\tself.cur += char\r\n\t\t\t\t\tappend = True\r\n\t\t\t\t\tself.state.pop()\r\n\t\t\t\telif char == \"{\":\r\n\t\t\t\t\tself.cur += char\r\n\t\t\t\t\tstate.push(\"bquoted\")\r\n\t\t\t\telif char == \"\\\\\":\r\n\t\t\t\t\tstate.push(\"escape\")\r\n\t\t\t\telif char:\r\n\t\t\t\t\tself.cur += char\r\n\t\t\t\telse:\r\n\t\t\t\t\tdone = False\r\n\t\t\t\t\tbreak\r\n\t\t\telif self.state.last == \"variable\":\r\n\t\t\t\tvar = None\r\n\r\n\t\t\t\tif char and char in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\\\r\n\t\t\t\t\t\t\t\"abcdefghijklmnopqrstuvwxyz\"\\\r\n\t\t\t\t\t\t\t\"0123456789_\":\r\n\t\t\t\t\ttoken += char\r\n\t\t\t\telif char == \"$\" and not token:\r\n\t\t\t\t\tvar = str(os.getpid())\r\n\t\t\t\telif char == \"{\" and not token:\r\n\t\t\t\t\ttoken += char\r\n\t\t\t\telif token and token[0] == \"{\":\r\n\t\t\t\t\tif char == \"}\":\r\n\t\t\t\t\t\tvar = variables.get(token[1:], \"\")\r\n\t\t\t\t\telif multiline:\r\n\t\t\t\t\t\tdone = False\r\n\t\t\t\t\t\tbreak\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\traise ParserError(\"missing closing }\")\r\n\t\t\t\telse:\r\n\t\t\t\t\ti -= 1\r\n\t\t\t\t\tvar = variables.get(token, \"\")\r\n\r\n\t\t\t\tif var is not None:\r\n\t\t\t\t\tif self.state.prev() == \"raw\":\r\n\t\t\t\t\t\tvar = (self.cur+var).split()\r\n\t\t\t\t\t\tif var:\r\n\t\t\t\t\t\t\tself.cur = var.pop()\r\n\t\t\t\t\t\t\tfor token in var:\r\n\t\t\t\t\t\t\t\tif token or append:\r\n\t\t\t\t\t\t\t\t\tself.words.append(token)\r\n\t\t\t\t\t\t\t\t\tappend = False\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tself.cur += var\r\n\t\t\t\t\tself.state.pop()\r\n\t\t\ti += 1\r\n\r\n\t\tif not multiline:\r\n\t\t\tdone = True\r\n\r\n\t\tif not done:\r\n\t\t\terr = None\r\n\t\telif not self.state or self.state.last == \"raw\":\r\n\t\t\terr = None\r\n\t\telif self.state.last in (\"bquoted\", \"variable\"):\r\n\t\t\traise ParserError(\"missing closing }\")\r\n\t\telif self.state.last == \"escape\":\r\n\t\t\traise ParserError(\"extra backslash\")\r\n\t\telif self.state.last == \"escape hex\":\r\n\t\t\traise ParserError(\"truncated hex escape\")\r\n\t\telif self.state.last == \"escape oct\":\r\n\t\t\traise ParserError(\"truncated oct escape\")\r\n\t\telse:\r\n\t\t\traise ParserError(\"foo\")\r\n\t\t\r\n\t\tif done:\r\n\t\t\treturn self.words, self.reset()\r\n\t\telse:\r\n\t\t\treturn self.words, False\r\n\r\nline = \"\"\r\ndone = True\r\n\r\nparser = Parser()\r\n\r\nwhile True:\r\n\tif done:\r\n\t\tline = gets(\"%\")\r\n\telse:\r\n\t\tline = \"\\n\" + gets(\"...\")\r\n\r\n\ttry:\r\n\t\twords, done = parser.feed(line)\r\n\texcept ParserError as e:\r\n\t\tprint(\"syntax error:\", e)\r\n\telse:\r\n\t\tprint(words, done)","sub_path":"Text/bash-parser.py","file_name":"bash-parser.py","file_ext":"py","file_size_in_byte":5330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"323246280","text":"\r\nimport math\r\n\r\ndef fibon_sequence(n): # This is the defintion of the function\r\n x = 1\r\n y = 1\r\n\r\n cont = 1\r\n while cont <= n: # n is the parameter of the function, that should be given\r\n # when the function is called\r\n print('A new Fibon number is: ', x + y)\r\n temp = x\r\n x = y\r\n y = y + temp\r\n\r\n cont = cont + 1\r\n\r\ndef swap(a, b):\r\n temp = a\r\n a = b\r\n b = temp\r\n return print(a, b)\r\n\r\n","sub_path":"mylibformulas.py","file_name":"mylibformulas.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"500391397","text":"# KVM-based Discoverable Cloudlet (KD-Cloudlet) \n# Copyright (c) 2015 Carnegie Mellon University.\n# All Rights Reserved.\n# \n# THIS SOFTWARE IS PROVIDED \"AS IS,\" WITH NO WARRANTIES WHATSOEVER. CARNEGIE MELLON UNIVERSITY EXPRESSLY DISCLAIMS TO THE FULLEST EXTENT PERMITTEDBY LAW ALL EXPRESS, IMPLIED, AND STATUTORY WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT OF PROPRIETARY RIGHTS.\n# \n# Released under a modified BSD license, please see license.txt for full terms.\n# DM-0002138\n# \n# KD-Cloudlet includes and/or makes use of the following Third-Party Software subject to their own licenses:\n# MiniMongo\n# Copyright (c) 2010-2014, Steve Lacy \n# All rights reserved. Released under BSD license.\n# https://github.com/MiniMongo/minimongo/blob/master/LICENSE\n# \n# Bootstrap\n# Copyright (c) 2011-2015 Twitter, Inc.\n# Released under the MIT License\n# https://github.com/twbs/bootstrap/blob/master/LICENSE\n# \n# jQuery JavaScript Library v1.11.0\n# http://jquery.com/\n# Includes Sizzle.js\n# http://sizzlejs.com/\n# Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors\n# Released under the MIT license\n# http://jquery.org/license\n\n__author__ = 'jdroot'\n\nfrom collection import MongoCollection\n\n\nclass MetaInfo(object):\n\n collection = None\n external = None\n mapping = None\n\n def __init__(self, meta):\n self.__dict__.update(meta.__dict__)\n\n\nclass MetaObject(type):\n\n def __new__(mcs, name, bases, attrs):\n new_class = super(MetaObject, mcs).__new__(mcs, name, bases, attrs)\n\n try:\n meta = getattr(new_class, 'Meta')\n delattr(new_class, 'Meta')\n except:\n meta = None\n\n # Will be none for Model\n if meta is not None:\n info = MetaInfo(meta)\n info.collection = info.collection or name.lower()\n\n # Create the collection and add it to the new class\n import pycloud.pycloud.cloudlet as cloudlet\n coll = MongoCollection(cloudlet.get_cloudlet_instance().db, info.collection, obj_class=new_class)\n new_class._collection = coll\n\n # Create the external attributes list and add it to the new class\n if isinstance(info.external, list):\n #print 'Mapping _external attributes for \"%s\"' % str(new_class)\n #print info.external\n new_class._external = info.external\n else:\n new_class._external = None\n\n if isinstance(info.mapping, dict):\n new_class.variable_mapping = info.mapping\n else:\n new_class.variable_mapping = None\n\n # Setup find and find one static methods\n new_class.find = new_class._collection.find\n new_class.find_one = new_class._collection.find_one\n new_class.find_and_modify = new_class._collection.find_and_modify\n new_class.external = external\n\n return new_class\n\ndef external(obj):\n ret = obj\n if hasattr(ret, '_external'):\n if isinstance(ret._external, list):\n ret = {}\n for key in obj._external:\n tmp = obj[key]\n if hasattr(tmp, 'external'):\n if hasattr(tmp.external, '__call__'):\n tmp = tmp.external()\n ret[key] = tmp\n return ret","sub_path":"pycloud/pycloud/mongo/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"320250864","text":"#!/usr/bin/env python3\n\n# stdlib\nimport _pickle as pickle\nimport traceback\n\n# Third party lib\nfrom plinkio import plinkfile\nimport numpy as np\nimport h5py\nimport json\n\n\nclass NumpyEncoder(json.JSONEncoder):\n \"\"\" Special json encoder for numpy types \"\"\"\n def default(self, obj):\n # print(obj.keys())\n if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16,\n np.uint32, np.uint64)):\n return int(obj)\n elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)):\n return float(obj)\n elif isinstance(obj, (np.ndarray,)): # This is the fix\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\ndef encode(message, client_name=None):\n return pickle.dumps(message)\n try:\n if client_name is not None:\n message['client_name'] = client_name\n j = json.dumps(message, cls=NumpyEncoder).encode('utf-8')\n return j\n except Exception: # srsly E722?\n print('oh nodes!')\n print(traceback.format_exc())\n\n\ndef decode(message):\n return pickle.loads(message)\n return json.loads(message)\n\n\ndef write_or_replace(group, name, val, dtype=None):\n if name in group:\n del group[name]\n if not isinstance(val, np.ndarray):\n val = np.array(val)\n if dtype is None:\n dtype = val.dtype\n else:\n val = val.astype(dtype)\n group.create_dataset(name, dtype=dtype, data=val)\n\n\ndef add_pheno(plink_in, multigenecity, out, h=0.85, p_cases=0.5):\n plink_file = plinkfile.open(plink_in)\n if not plink_file.one_locus_per_row():\n print(\"This script requires that snps are rows and samples columns.\")\n exit(1)\n sample_list = plink_file.get_samples()\n locus_list = plink_file.get_loci()\n n = len(sample_list)\n p = len(locus_list)\n fids = np.array([item.fid for item in sample_list])\n iids = np.array([item.iid for item in sample_list])\n edge_offset = 100\n causal_mut_index = np.linspace(\n edge_offset, p-edge_offset, multigenecity, dtype=int)\n gen_effect_size_unnormalized = {\n item: np.random.normal(loc=0, scale=float(h)/np.sqrt(multigenecity))\n for item in causal_mut_index}\n prs = np.zeros(n)\n for i, variant in enumerate(locus_list):\n row = plink_file.next()\n if i in causal_mut_index:\n genotypes = np.fromiter(row, dtype=float)\n genotypes[genotypes == 3] = np.mean(genotypes[genotypes != 3])\n prs += genotypes * gen_effect_size_unnormalized[i]\n plink_file.close()\n del causal_mut_index, gen_effect_size_unnormalized\n # Draw random environmental effects\n env_rs_unnormalized = np.random.normal(\n loc=0, scale=np.sqrt(1-h**2), size=n)\n gen_effect_size = h * (prs - np.mean(prs)) / np.std(prs)\n env_effect_size = (np.sqrt(1-h**2)\n * (env_rs_unnormalized - np.mean(env_rs_unnormalized)) / np.std(env_rs_unnormalized))\n burden = gen_effect_size + env_effect_size\n sorted_i = np.argsort(burden)[::-1]\n ncases = int(n * p_cases)\n cases_i = sorted_i[:ncases]\n affection = np.zeros(n, dtype=np.int8)\n affection[cases_i] = 2\n affection[affection == 0] = 1\n towrite = np.column_stack((fids, iids, affection))\n np.savetxt(out, towrite, delimiter='\\t', fmt=['%s', '%s', '%s'], header='FID\\tID\\tpheno',)\n\n\ndef snps_match(plinkName, store_name, position_dset=None):\n # WARNING: this only works if positions are unique.\n with h5py.File(store_name, 'r', libver='latest') as store:\n # check the plink file\n plink_file = plinkfile.open(plinkName)\n locus_list = plink_file.get_loci()\n plink_file.close()\n plinkSet = set((l.chromosome, l.bp_position) for l in locus_list)\n del locus_list\n len_plink = len(plinkSet)\n if position_dset is None:\n position_dset = 'positions'\n for key in store:\n if key == 'meta':\n continue\n positions = store[\"{}/{}\".format(key, position_dset)].value\n ikey = int(key)\n hset = set((ikey, int(pos)) for pos in positions)\n len_plink -= len(hset)\n plinkSet -= hset\n if len(plinkSet) == 0 and len_plink == 0:\n return True\n return False\n\n\ndef compare_pca(plinkPCA, store_name, dsets_list):\n with h5py.File(store_name, 'r') as store:\n sigmas = store['meta/Sigmas'].value\n with open(plinkPCA+'.eigenval', 'r') as vals_file:\n plinkSigmas = vals_file.read().split()\n plinkSigmas = np.array(plinkSigmas, dtype=float)\n k = len(sigmas)\n sigmasMatch = np.isclose(sigmas, plinkSigmas, rtol=1e-4, atol=1e-6).all()\n del plinkSigmas, sigmas\n plinkVals = np.loadtxt(plinkPCA+'.eigenvec', usecols=range(2, 2+k))\n valsMatch = True\n index_new, index_old = 0, 0\n for dset in dsets_list:\n with h5py.File(dset, 'r') as store:\n vals = store['meta/pca_u'].value\n index_new += vals.shape[0]\n valsMatch * np.isclose(plinkVals[index_old:index_new, :], vals, rtol=1e-4, atol=1e-6).all()\n index_old = index_new\n return valsMatch * sigmasMatch\n\n\ndef compare_regression(plinkRegression, store_name, dset_name=\"results\"):\n converter = lambda x: np.nan if x == b'NA' else float(x)\n plinkResults = np.loadtxt(plinkRegression, usecols=[0, 6, 7, 8], skiprows=1,\n converters={6: converter, 7: converter, 8: converter})\n with h5py.File(store_name, 'r') as store:\n for key in store:\n if key != \"meta\":\n results = store[key+\"/{}\".format(dset_name)].value\n res = np.array([i for subset in results for i in subset])\n plinkSubset_ind = plinkResults[:, 0] == int(key)\n plinkSubset = plinkResults[plinkSubset_ind, :]\n del plinkSubset_ind\n\n pass\n\n\nif __name__ == '__main__':\n np.random.seed(123)\n add_pheno('testData/subsampled', 10, 'testData/subsampled.pheno')\n","sub_path":"src/lib/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"600043581","text":"#!/usr/bin/python\n#\n# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"This example creates a ProductPartition tree.\n\nThe LoadFromStorage method is pulling credentials and properties from a\n\"googleads.yaml\" file. By default, it looks for this file in your home\ndirectory. For more information, see the \"Caching authentication information\"\nsection of our README.\n\n\"\"\"\n\n\n# Import appropriate modules from the client library.\nfrom googleads import adwords\n\nADGROUP_ID = 'INSERT_AD_GROUP_ID_HERE'\n\n\nclass ProductPartitionHelper(object):\n \"\"\"A helper for creating ProductPartition trees.\"\"\"\n\n # The next temporary criterion ID to be used.\n # When creating our tree we need to specify the parent-child relationships\n # between nodes. However, until a criterion has been created on the server we\n # do not have a criterion ID with which to refer to it.\n # Instead we can specify temporary IDs that are specific to a single mutate\n # request. Once the criteria have been created they are assigned an ID as\n # normal and the temporary ID will no longer refer to it.\n # A valid temporary ID is any negative integer.\n next_id = -1\n\n # The set of mutate operations needed to create the current tree.\n operations = []\n\n def __init__(self, adgroup_id):\n \"\"\"Initializer.\n\n Args:\n adgroup_id: The ID of the AdGroup that we wish to attach the partition\n tree to.\n \"\"\"\n self.adgroup_id = adgroup_id\n\n def CreateSubdivision(self, parent=None, value=None):\n \"\"\"Creates a subdivision node.\n\n Args:\n parent: The node that should be this node's parent.\n value: The value being partitioned on.\n Returns:\n A new subdivision node.\n \"\"\"\n division = {\n 'xsi_type': 'ProductPartition',\n 'partitionType': 'SUBDIVISION',\n 'id': str(self.next_id)\n }\n\n # The root has neither a parent nor a value.\n if parent is not None:\n division['parentCriterionId'] = parent['id']\n division['caseValue'] = value\n\n adgroup_criterion = {\n 'xsi_type': 'BiddableAdGroupCriterion',\n 'adGroupId': self.adgroup_id,\n 'criterion': division\n }\n\n self.CreateAddOperation(adgroup_criterion)\n self.next_id -= 1\n\n return division\n\n def CreateUnit(self, parent=None, value=None, bid_amount=None):\n \"\"\"Creates a unit node.\n\n Args:\n parent: The node that should be this node's parent.\n value: The value being partitioned on.\n bid_amount: The amount to bid for matching products, in micros.\n Returns:\n A new unit node.\n \"\"\"\n unit = {\n 'xsi_type': 'ProductPartition',\n 'partitionType': 'UNIT'\n }\n\n # The root node has neither a parent nor a value.\n if parent is not None:\n unit['parentCriterionId'] = parent['id']\n unit['caseValue'] = value\n\n if bid_amount is not None and bid_amount > 0:\n bidding_strategy_configuration = {\n 'bids': [{\n 'xsi_type': 'CpcBid',\n 'bid': {\n 'xsi_type': 'Money',\n 'microAmount': str(bid_amount)\n }\n }]\n }\n\n adgroup_criterion = {\n 'xsi_type': 'BiddableAdGroupCriterion',\n 'biddingStrategyConfiguration': bidding_strategy_configuration\n }\n else:\n adgroup_criterion = {\n 'xsi_type': 'NegativeAdGroupCriterion'\n }\n\n adgroup_criterion['adGroupId'] = self.adgroup_id\n adgroup_criterion['criterion'] = unit\n\n self.CreateAddOperation(adgroup_criterion)\n\n return unit\n\n def GetOperations(self):\n \"\"\"Returns the set of mutate operations needed to create the current tree.\n\n Returns:\n The set of operations\n \"\"\"\n return self.operations\n\n def CreateAddOperation(self, criterion):\n \"\"\"Creates an AdGroupCriterionOperation for the given criterion.\n\n Args:\n criterion: The criterion we want to add.\n \"\"\"\n operation = {\n 'operator': 'ADD',\n 'operand': criterion\n }\n\n self.operations.append(operation)\n\n\ndef main(client, adgroup_id):\n \"\"\"Runs the example.\"\"\"\n adgroup_criterion_service = client.GetService(\n 'AdGroupCriterionService', version='v201509')\n\n helper = ProductPartitionHelper(adgroup_id)\n\n # The most trivial partition tree has only a unit node as the root, e.g.:\n # helper.CreateUnit(bid_amount=100000)\n\n root = helper.CreateSubdivision()\n\n new_product_canonical_condition = {\n 'xsi_type': 'ProductCanonicalCondition',\n 'condition': 'NEW'\n }\n\n used_product_canonical_condition = {\n 'xsi_type': 'ProductCanonicalCondition',\n 'condition': 'USED'\n }\n\n other_product_canonical_condition = {\n 'xsi_type': 'ProductCanonicalCondition',\n }\n\n helper.CreateUnit(root, new_product_canonical_condition, 200000)\n helper.CreateUnit(root, used_product_canonical_condition, 100000)\n other_condition = helper.CreateSubdivision(\n root, other_product_canonical_condition)\n\n cool_product_brand = {\n 'xsi_type': 'ProductBrand',\n 'value': 'CoolBrand'\n }\n\n cheap_product_brand = {\n 'xsi_type': 'ProductBrand',\n 'value': 'CheapBrand'\n }\n\n other_product_brand = {\n 'xsi_type': 'ProductBrand',\n }\n\n helper.CreateUnit(other_condition, cool_product_brand, 900000)\n helper.CreateUnit(other_condition, cheap_product_brand, 10000)\n other_brand = helper.CreateSubdivision(other_condition, other_product_brand)\n\n # The value for the bidding category is a fixed ID for the 'Luggage & Bags'\n # category. You can retrieve IDs for categories from the ConstantDataService.\n # See the 'GetProductTaxonomy' example for more details.\n luggage_category = {\n 'xsi_type': 'ProductBiddingCategory',\n 'type': 'BIDDING_CATEGORY_L1',\n 'value': '-5914235892932915235'\n }\n\n generic_category = {\n 'xsi_type': 'ProductBiddingCategory',\n 'type': 'BIDDING_CATEGORY_L1',\n }\n\n helper.CreateUnit(other_brand, luggage_category, 750000)\n helper.CreateUnit(other_brand, generic_category, 110000)\n\n # Make the mutate request\n result = adgroup_criterion_service.mutate(helper.GetOperations())\n\n children = {}\n\n root_node = None\n\n # For each criterion, make an array containing each of its children.\n # We always create the parent before the child, so we can rely on that here.\n for adgroup_criterion in result['value']:\n children[adgroup_criterion['criterion']['id']] = []\n\n if 'parentCriterionId' in adgroup_criterion['criterion']:\n children[adgroup_criterion['criterion']['parentCriterionId']].append(\n adgroup_criterion['criterion'])\n else:\n root_node = adgroup_criterion['criterion']\n\n # Show the tree\n DisplayTree(root_node, children)\n\n\ndef DisplayTree(node, children, level=0):\n \"\"\"Recursively display a node and each of its children.\n\n Args:\n node: The node we're displaying the children of.\n children: Children of the parent node.\n level: How deep in the tree we are.\n \"\"\"\n value = ''\n node_type = ''\n\n if 'caseValue' in node:\n case_value = node['caseValue']\n node_type = case_value['ProductDimension.Type']\n\n if node_type == 'ProductCanonicalCondition':\n value = (case_value['condition'] if 'condition' in case_value\n else 'OTHER')\n elif node_type == 'ProductBiddingCategory':\n value = '%s(%s)' % (case_value['type'], case_value['value']\n if 'value' in case_value else 'OTHER')\n else:\n value = (case_value['value'] if 'value' in case_value else 'OTHER')\n\n print ('%sid: %s, node_type: %s, value: %s\\n'\n % (' ' * level, node['id'], node_type, value))\n\n for child_node in children[node['id']]:\n DisplayTree(child_node, children, level + 1)\n\n\nif __name__ == '__main__':\n # Initialize client object.\n adwords_client = adwords.AdWordsClient.LoadFromStorage()\n\n main(adwords_client, ADGROUP_ID)\n\n","sub_path":"adwords api/googleads-python-lib-master/examples/adwords/v201509/shopping/add_product_partition_tree.py","file_name":"add_product_partition_tree.py","file_ext":"py","file_size_in_byte":8347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"434251794","text":"import tensorflow as tf\nfrom tensorflow.keras.callbacks import Callback # noqa\nfrom tensorflow.keras.models import Model # noqa\nfrom keyboard._3_scoring import Metrics, ValidationData\nfrom trainer.trainer import TrainerExtension\nfrom trainer.extensions.GenerateData import _unmemoized_generateDataTrainerExtension_compute_validation_data\nfrom utilities import override\n\n\nclass ValidationDataScoringExtensions(TrainerExtension): \n def __init__(self,\n monitor_namespace: str = \"\",\n print_loss=False,\n print_misinterpretation_examples=False,\n ):\n self._kw = {\n \"monitor_namespace\": monitor_namespace,\n \"print_loss\": print_loss,\n \"print_misinterpretation_examples\": print_misinterpretation_examples,\n }\n\n def initialize(self):\n # reserve a spot in the fit_args.callbacks (order is relevant)\n # only later fill it with the actual callback, which needs more information than is available at this point (the data)\n self.placeholder = CallbackPlaceholder()\n self.params.fit_args.callbacks.append(self.placeholder)\n\n def _get_data(self) -> ValidationData:\n return self.params.validation_data\n\n def after_compile(self, model: Model) -> None:\n callback = Metrics(\n validation_data=self._get_data(), \n write_scalar=self.params.write_scalar,\n **self._kw\n )\n assert hasattr(self, \"placeholder\"), \"You didn't call super().initialize()\"\n self.placeholder.replace(self.params, callback)\n\n def _tf_summary_writer(self, i) -> tf.summary.SummaryWriter:\n return self.params.get_resource_writer(self.params.run_log_dir, i)\n\n\n\n\nclass TotalValidationDataScoringExtensions(ValidationDataScoringExtensions): \n\n @property\n def _name(self):\n return \"_total_validation_data\" + self._kw[\"monitor_namespace\"]\n\n\n def initialize(self):\n super().initialize()\n if self.is_first_stage:\n # we duplicate the cached version, because it's going to be modified\n validation_data = _unmemoized_generateDataTrainerExtension_compute_validation_data(self.params.data(), self.params.preprocessor)\n setattr(self.params, self._name, validation_data)\n else:\n validation_data = getattr(self.prev_params, self._name)\n validation_data.add(self.params.data(), self.params.preprocessor)\n setattr(self.params, self._name, validation_data)\n\n @override\n def _get_data(self):\n return getattr(self.params, self._name)\n\n\nclass CallbackPlaceholder(Callback):\n def __init__(self):\n super().__init__()\n self._replaced = False\n\n def replace(self, params, callback: Callback):\n assert not self._replaced, \"Placeholder already replaced\"\n self._replaced = True\n i = params.fit_args.callbacks.index(self)\n params.fit_args.callbacks[i] = callback\n\n def on_train_begin(self, batch, logs={}):\n raise ValueError(\"The placeholder should have been replaced\")\n","sub_path":"python/trainer/extensions/MetricExtension.py","file_name":"MetricExtension.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"318249957","text":"import base64\nimport datetime\nimport hashlib\nimport hmac\nimport json\nimport logging\n\nimport requests\n\nimport blast.celery # Need for correct worker run\n\nfrom django.conf import settings\n\nfrom celery import shared_task\n\nfrom smsconfirmation.models import PhoneConfirmation\n\n\ndef sinch_request(resource, data, method):\n headers = {\n 'X-Timestamp': datetime.datetime.utcnow().isoformat(),\n 'Content-Type': 'application/json',\n }\n\n URL = 'https://api.sinch.com{}'.format(resource)\n \n scheme = 'Application'\n\n canonicalized_headers = '{}:{}'.format('x-timestamp', headers['X-Timestamp'])\n canonicalized_resource = resource\n\n data_str = json.dumps(data)\n content_md5 = hashlib.md5(data_str.encode('utf-8')).digest()\n content_md5 = base64.b64encode(content_md5)\n # assert content_md5 != 'jANzQ+rgAHyf1MWQFSwvYw==', 'Wrong md5'\n\n string_to_sign = '{}\\n{}\\n{}\\n{}\\n{}'.format(method,\n content_md5.decode('utf-8'),\n headers['Content-Type'],\n canonicalized_headers,\n canonicalized_resource)\n\n secret = base64.b64decode(settings.SINCH['APP_SECRET'])\n signature = hmac.new(secret,\n string_to_sign.encode('utf-8'),\n hashlib.sha256).digest()\n signature = base64.b64encode(signature)\n\n authorization = '{} {}:{}'.format(scheme, settings.SINCH['APP_KEY'], signature.decode('utf-8'))\n headers['Authorization'] = authorization\n\n if method == 'POST':\n return requests.post(URL, json=data, headers=headers)\n elif method == 'PUT':\n return requests.put(URL, data=data_str, headers=headers)\n\n\ndef send_code_confirmation_request(code, phone):\n response = sinch_request('/verification/v1/verifications/number/{}'.format(phone), data={\n \"sms\": {\"code\": str(code)},\n \"method\": \"sms\",\n }, method='PUT')\n\n data = response.json()\n\n if data.get('status') == 'SUCCESSFUL':\n confirm = PhoneConfirmation.objects.get_actual(phone=phone)\n confirm.is_confirmed = True\n confirm.save()\n\n return data\n\n\n@shared_task(bind=False)\ndef send_code_confirmation_request_async(code, phone):\n send_code_confirmation_request(code, phone)\n\n\n@shared_task(bind=False)\ndef send_verification_request(phone):\n logging.info('verifying phone {}'.format(phone))\n\n response = sinch_request('/verification/v1/verifications', data={\n \"identity\": {\"type\": \"number\", \"endpoint\": str(phone)},\n \"method\": \"sms\",\n \"metadata\": {\n \"os\": \"rest\",\n \"platform\": \"N/A\"\n }\n }, method='POST')\n\n logging.info('send_verification_request {} {}'.format(phone, response.content))\n","sub_path":"blast/smsconfirmation/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"419922084","text":"import os\n\nfrom src.DataUtils.Dataset import Dataset\n\nclass TwitterDataset(Dataset):\n\n def __init__(self):\n super(TwitterDataset, self).__init__('twitter')\n\n self.retrieve_data()\n self.preprocessed_data()\n\n\n def retrieve_data(self):\n dir = os.path.dirname(os.path.realpath(__file__))\n data_path = os.path.join(dir, '../', '../', 'Data')\n data_file = os.path.join(data_path, self.filename)\n\n with open(data_file, 'r') as f:\n self._raw_data = f.read()\n\n\n def preprocessed_data(self):\n self._preprocessed_data = self._raw_data.split('\\n')\n\n","sub_path":"src/DataUtils/TwitterDataset.py","file_name":"TwitterDataset.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"622702970","text":"import discord\r\nimport os\r\nimport time\r\nimport random\r\nimport sys\r\nimport giphy_client\r\nfrom discord.ext import commands\r\nfrom discord.ext import tasks\r\nfrom itertools import cycle\r\nfrom giphy_client.rest import ApiException\r\n\r\nclient = commands.Bot(command_prefix= \"-\")\r\n\r\nstatus = cycle(['-help for help.', 'discord.gg/vgMqZ7A <- Covex Bot Server'])\r\ndef clear():\r\n os.system( 'clear' ) #for windows change to 'cls', for mac and linux change to 'clear'\r\n\r\n#on startup:\r\n@client.event\r\nasync def on_ready():\r\n change_status.start()\r\n server_list.start()\r\n\r\n\r\n#loads cogs:\r\nfor filename in os.listdir('./cogs'):\r\n if filename.endswith('.py'):\r\n client.load_extension(f'cogs.{filename[:-3]}')\r\n\r\n\r\n#general ping command:\r\n@client.command(name='ping',\r\n Description=\"This command will show you your ping.\",\r\n Brief=\"Test your ping\")\r\nasync def ping(ctx):\r\n await ctx.send(f'Pong! {round(client.latency * 1000)}ms')\r\n\r\n\r\n#Show list of connected servers in console\r\n@tasks.loop(minutes=15)\r\nasync def server_list():\r\n servers = list(client.guilds)\r\n clear()\r\n print(\"---------------------------------------------------------------------\")\r\n print(\"Covex bot is online in\", str(len(servers)), 'servers:')\r\n for server in client.guilds:\r\n print(server.name)\r\n else:\r\n print(\"---------------------------------------------------------------------\")\r\n localtime = time.asctime(time.localtime(time.time()))\r\n print(\"Last updated at:\",localtime)\r\n print(\"---------------------------------------------------------------------\")\r\n print(f'The ping is: {round(client.latency * 1000)}ms')\r\n print(\"---------------------------------------------------------------------\")\r\n\r\n\r\n@tasks.loop(seconds=15)\r\nasync def change_status():\r\n await client.change_presence(activity=discord.Game(next(status)))\r\nclient.run('TOKEN')\r\n","sub_path":"covex_bot.py","file_name":"covex_bot.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"50153237","text":"import serial\nimport time\nser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0)\n\nwhile True:\n data=ser.readline()\n if data:\n print(data)\n f = open('/client/public_key.pem','a')\n data=str(data)\n f.write(data)\n f.close()\n time.sleep(1)","sub_path":"receive_file.py","file_name":"receive_file.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"11187272","text":"#\n# Vince Charming (c) 2019\n#\n\n\"\"\"\nUtilities specific to gathering data regarding vehicle utilization\n\"\"\"\n\nimport logging\nimport uuid\n\nfrom dateutil import parser\nfrom general_utils import is_valid_uuid\n\n__author__ = 'vcharming'\n\n\nclass VehicleUtilization(object):\n def __init__(self):\n self.num_of_transitions = 0\n # a for autonomous\n # m for manual\n # p for parked\n # u for unknown\n # Time is in seconds\n self.total_length_s = {'a': 0, 'm': 0, 'p': 0, 'u': 0}\n\n def reset_stats(self):\n self.num_of_transitions = 0\n for state in self.total_length_s:\n self.total_length_s[state] = 0\n return\n\n def get_length_all_states_s(self):\n result = 0\n for length in self.total_length_s.itervalues():\n result += length\n return result\n\n\n def print_stats(self):\n print('\\tNumber of Transitions: {}'.format(self.num_of_transitions))\n print('\\tTotal Length in:')\n print('\\t\\tAuto: {}'.format(self.total_length_s['a']))\n print('\\t\\tManual: {}'.format(self.total_length_s['m']))\n print('\\t\\tParked: {}'.format(self.total_length_s['p']))\n print('\\t\\tUnknown: {}'.format(self.total_length_s['u']))\n return\n\n\nclass User(object):\n def __init__(self, first_name, last_name=None, input_uuid=None):\n '''\n Initializes the dictionaries for the respective test\n '''\n self.first_name = first_name.lower()\n self.last_name = None\n\n if last_name is not None:\n self.last_name = last_name.lower()\n\n if input_uuid is None or not is_valid_uuid(input_uuid):\n self.user_uuid = uuid.uuid4()\n else:\n self.user_uuid = input_uuid\n\n self.vehicle_utilization = VehicleUtilization()\n\n def get_full_name(self, last_name_first=False):\n if self.last_name is None:\n full_name = self.first_name.title()\n elif last_name_first:\n full_name = \"{}, {}\".format(self.last_name.title(), self.first_name.title())\n else:\n full_name = \"{} {}\".format(self.first_name.title(), self.last_name.title())\n return full_name\n\n def print_user(self):\n print(self.get_full_name(last_name_first=True))\n self.vehicle_utilization.print_stats()\n return\n\n\nclass Team(object):\n def __init__(self, id):\n self.id = id\n # An array of Users()\n self.members = []\n self.vehicle_utilization = VehicleUtilization()\n\n def add_member(self, user_obj):\n for member in self.members:\n if user_obj.user_uuid == member.user_uuid:\n return\n self.members.append(user_obj)\n return\n\n def update_members_stats(self):\n self.vehicle_utilization.reset_stats()\n for member in self.members:\n self.vehicle_utilization.num_of_transitions += member.vehicle_utilization.num_of_transitions\n for state in self.vehicle_utilization.total_length_s:\n self.vehicle_utilization.total_length_s[state] += member.vehicle_utilization.total_length_s[state]\n return\n\n def print_members(self):\n for member in self.members:\n print('\\t{}'.format(member.get_full_name(last_name_first=True)))\n return\n\n def print_team(self):\n print('Team {}'.format(self.id.title()))\n self.print_members()\n self.update_members_stats()\n self.vehicle_utilization.print_stats()\n return\n\n\nclass Vehicle(object):\n def __init__(self, alias):\n self.alias = alias\n self.vehicle_utilization = VehicleUtilization()\n\n def print_vehicle(self):\n print('VEHICLE{}'.format(self.alias.upper()))\n self.vehicle_utilization.print_stats()\n return\n\n\ndef is_valid_row(row):\n \"\"\"\n Ensures the data in the given row matches its format requirements for that column\n :param row: An array of data. Each element within the row relates to a column\n :return: A boolean; True if all of the columns passed their respective data validation\n \"\"\"\n\n valid_flag = True\n\n if len(row[0]) != 11 or row[0][:7].lower() != 'vehicle':\n error_message = 'Vehicle alias must be formated as \\'VEHICLEXXXX\\'.'\n valid_flag = False\n elif len(row[1]) < 1 or not (\n row[1][:1].lower() == 'a' or row[1][:1].lower() == 'm' or row[1][:1].lower() == 'p' or row[1][:1].lower() == 'u'):\n error_message = ('Vehicle activity must start with \\'a\\' for autonomous, '\n '\\'m\\' for manual, \\'p\\' for parked, or \\'u\\' for unknown.')\n valid_flag = False\n elif row[2] == '' or row[3] == '':\n error_message = 'Start and End time are required.'\n valid_flag = False\n elif row[4] == '':\n error_message = 'User name required.'\n valid_flag = False\n elif len(row[5]) != 6 and row[5][:5].lower() != 'team ':\n error_message = 'Team Name must be formated as \\'Team X\\'.'\n valid_flag = False\n\n if valid_flag:\n try:\n start_time = parser.parse(row[2])\n end_time = parser.parse(row[3])\n if start_time >= end_time:\n error_message = 'End time must be later than the Start time.'\n valid_flag = False\n except ValueError:\n error_message = 'Start and End time must be in a valid datetime format.'\n valid_flag = False\n\n if not valid_flag:\n logging.error('{}'.format(error_message))\n return valid_flag\n\n\ndef get_avg_transition_per_min(users):\n \"\"\"\n Gets the average tranistions per minute across all users\n :param users: A dictionary of User()'s\n :return: The avgerage number of tranistions per minute\n \"\"\"\n # The aggregate averages. Division by 60 turns it from seconds to minutes\n agg_avg = 0\n for user in users.itervalues():\n agg_avg += user.vehicle_utilization.num_of_transitions / (user.vehicle_utilization.get_length_all_states_s() / 60)\n\n return agg_avg/len(users)\n","sub_path":"python/utils/vehicle_utilization_utils.py","file_name":"vehicle_utilization_utils.py","file_ext":"py","file_size_in_byte":6034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"26086863","text":"# -*- coding: utf-8 -*-\n\"\"\"some helper functions for project 1.\"\"\"\nimport csv\nimport numpy as np\n\n\ndef load_csv_data(data_path, step=None):\n \"\"\"Loads data and returns y (class labels), tX (features) and ids (event ids)\"\"\"\n y = np.genfromtxt(data_path, delimiter=\",\", skip_header=1, dtype=str, usecols=1)\n x = np.genfromtxt(data_path, delimiter=\",\", skip_header=1)\n features = np.genfromtxt(data_path, delimiter=\",\", dtype=str, max_rows=1)\n features = features[2:]\n ids = x[:, 0].astype(np.int)\n input_data = x[:, 2:]\n\n # convert class labels from strings to binary (-1,1)\n yb = np.ones(len(y))\n yb[np.where(y=='b')] = -1\n \n # sub-sample\n if step:\n yb = yb[::step]\n input_data = input_data[::step]\n ids = ids[::step]\n\n return yb, input_data, ids, features\n\ndef predict_labels(weights, data):\n \"\"\"Generates class predictions given weights, and a test data matrix\"\"\"\n y_pred = np.dot(data, weights)\n y_pred[np.where(y_pred <= 0)] = -1\n y_pred[np.where(y_pred > 0)] = 1\n return y_pred\n\ndef model_predictions(tx, ws, pri_jet_num_idx, clean_features, parameters, degree):\n \"\"\" Generates predictions for the given weights applied to the given samples.\n Arguments:\n tx: matrix form sample data to predict\n ws: weights used to predict\n pri_jet_num_idx: the index of the pri_jet_num feature in tx, for splitting\n clean_features: features that do not contained undefined values\n parameters: (mean, std) of features prior to standardization\n \"\"\"\n cond_null = tx[:, pri_jet_num_idx] == 0\n cond_one = tx[:, pri_jet_num_idx] == 1\n cond_plural = tx[:, pri_jet_num_idx] >= 2\n conditions = (cond_null, cond_one, cond_plural)\n\n N = tx.shape[0]\n model_predictions = np.zeros(N)\n for pri_jet_num, cond in enumerate(conditions):\n weight = ws[pri_jet_num]\n select_features = clean_features[pri_jet_num]\n reduced_dset = tx[cond][:,select_features]\n poly_dset = build_poly(reduced_dset, degree)\n mean, std = parameters[pri_jet_num]\n extended_dset, _, _ = extend_and_standardize(poly_dset[:,1:], mean, std)\n sub_prediction = predict_labels(weight, extended_dset)\n model_predictions[cond] = sub_prediction\n \n return model_predictions\n\ndef create_csv_submission(ids, y_pred, name):\n \"\"\"\n Creates an output file in csv format for submission to kaggle\n Arguments: ids (event ids associated with each prediction)\n y_pred (predicted class labels)\n name (string name of .csv output file to be created)\n \"\"\"\n with open(name, 'w') as csvfile:\n fieldnames = ['Id', 'Prediction']\n writer = csv.DictWriter(csvfile, delimiter=\",\", fieldnames=fieldnames)\n writer.writeheader()\n for r1, r2 in zip(ids, y_pred):\n writer.writerow({'Id':int(r1),'Prediction':int(r2)})\n \ndef standardize(x):\n \"\"\"Standardize the original data set.\"\"\"\n mean_x = np.mean(x, axis = 0)\n x = x - mean_x\n std_x = np.std(x, axis = 0)\n x = x / std_x\n return x, mean_x, std_x\n\ndef build_model_data(x):\n \"\"\" Form (y, tX) to get regression data in matrix form.\"\"\"\n num_samples = x.shape[0]\n tx = np.c_[np.ones(num_samples), x]\n return tx\n\ndef build_poly(x, degree):\n \"\"\" Polynomial basis functions for input data x, for j=0 up to j=degree.\"\"\"\n poly = np.ones((len(x), 1))\n for deg in range(1, degree+1):\n poly = np.c_[poly, np.power(x, deg)]\n return poly\n\ndef extend_and_standardize(input_data, mean=None, std=None):\n \"\"\"\n This method extends the input_data to matrix form and computes the means and stds.\n If mean and std are provided, it does not recompute those statistics and uses them instead.\n \"\"\" \n if mean is not None and std is not None:\n mean_x = mean\n std_x = std\n tx = (input_data - mean) / std\n num_samples = input_data.shape[0]\n tx = np.c_[np.ones(num_samples), tx]\n else: \n x, mean_x, std_x = standardize(input_data)\n tx = build_model_data(x)\n return tx, mean_x, std_x\n\ndef batch_iter(y, tx, batch_size, num_batches=1, shuffle=True):\n \"\"\" Generates a minibatch iterator for a dataset. \"\"\"\n data_size = len(y)\n\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_y = y[shuffle_indices]\n shuffled_tx = tx[shuffle_indices]\n else:\n shuffled_y = y\n shuffled_tx = tx\n for batch_num in range(num_batches):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n if start_index != end_index:\n yield shuffled_y[start_index:end_index], shuffled_tx[start_index:end_index]\n \ndef split_data(x, y, ratio, myseed=1):\n \"\"\" Splits the dataset based on the split ratio, uses myseed for the random selection of indices \"\"\" \n # set seed\n np.random.seed(myseed)\n # generate random indices\n num_row = len(y)\n indices = np.random.permutation(num_row)\n index_split = int(np.floor(ratio * num_row))\n index_tr = indices[: index_split]\n index_te = indices[index_split:]\n # create split\n x_tr = x[index_tr]\n x_te = x[index_te]\n y_tr = y[index_tr]\n y_te = y[index_te]\n return x_tr, x_te, y_tr, y_te\n\ndef build_k_indices(y, k_fold, seed):\n \"\"\"\n Builds k indices for k-fold.\n This is explained further under cross-validation for hyperparameters in the report pdf.\n \"\"\"\n num_row = y.shape[0]\n interval = int(num_row / k_fold)\n np.random.seed(seed)\n indices = np.random.permutation(num_row)\n k_indices = [indices[k * interval: (k + 1) * interval]\n for k in range(k_fold)]\n return np.array(k_indices)\n","sub_path":"projects/project1/scripts/proj1_helpers.py","file_name":"proj1_helpers.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"487043263","text":"def feedback_6042(filename):\n from CRLS_APCSP_autograder.app.python_labs.filename_test import filename_test\n from CRLS_APCSP_autograder.app.python_labs.find_items import find_function, find_loop, find_dictionary, function_called\n from CRLS_APCSP_autograder.app.python_labs.function_test import extract_all_functions, create_testing_file, run_unit_test, \\\n extract_single_function\n from CRLS_APCSP_autograder.app.python_labs.helps import helps\n from CRLS_APCSP_autograder.app.python_labs.pep8 import pep8\n from CRLS_APCSP_autograder.app.python_labs.python_6_041 import five_loop\n from CRLS_APCSP_autograder.app.python_labs.read_file_contents import read_file_contents\n\n tests = list()\n test_filename = filename_test(filename, '6.042')\n tests.append(test_filename)\n if not test_filename['pass']:\n return tests\n else:\n filename_data = read_file_contents(filename)\n\n # Check for function add with 1 inputs\n test_find_function = find_function(filename, 'worst_hit', 1, points=5)\n tests.append(test_find_function)\n if test_find_function['pass'] is False:\n return tests\n else:\n # extract functions and create python test file\n extract_all_functions(filename)\n create_testing_file(filename)\n # unit tests\n test_function_1 = run_unit_test('6.042', 1, 5)\n tests.append(test_function_1)\n test_function_2 = run_unit_test('6.042', 2, 5)\n tests.append(test_function_2)\n\n # Check for function 2 inputs\n test_find_function_2 = find_function(filename, 'top_hits', 1, points=5)\n tests.append(test_find_function_2)\n\n run_simulation_function = extract_single_function(filename, 'top_hits')\n test_run_sim = find_loop(run_simulation_function, 5)\n test_run_sim['name'] = \"Looking for loop in the run_simulation function (5 points).
    \"\n tests.append(test_run_sim)\n\n # unit tests\n test_function_3 = run_unit_test('6.042', 3, 5)\n tests.append(test_function_3)\n test_function_4 = run_unit_test('6.042', 4, 5)\n tests.append(test_function_4)\n\n test_dictionary = find_dictionary(filename_data, num_items=6, points=5)\n tests.append(test_dictionary)\n test_function_run = function_called(filename, 'worst_hit', 3, points=5)\n tests.append(test_function_run)\n test_function_run = function_called(filename, 'top_hits', 3, points=5)\n tests.append(test_function_run)\n\n # Find number of PEP8 errors and helps\n test_pep8 = pep8(filename, 14)\n tests.append(test_pep8)\n test_help = helps(filename, 5)\n tests.append(test_help)\n return tests\n \n","sub_path":"CRLS_APCSP_autograder/app/python_6042.py","file_name":"python_6042.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"321415137","text":"import numpy as np\n\ndef sigmoid(t):\n \"\"\"apply sigmoid function on t.\"\"\"\n # ***************************************************\n # print('Shape of t is', np.shape(t))\n # logfn = np.divide(np.exp(t),1+np.exp(t))\n logfn = np.divide(1,1+np.exp(-t)) \n return logfn\n\ndef calculate_loss(y, tx, w):\n \"\"\"compute the cost by negative log likelihood.\"\"\"\n y = np.reshape(y,(len(y),)) # Make sure the sizes are (n,) and not (n,1)\n\t\n\t# IMPORTANT: The loss function has been change to account for very large values of tx,w \n vec_tx_w = np.dot(tx,w)\n\t# Separate the tx dot w vector into components that are < 100 and those that are much > 100\n vec_tx_w_normal = vec_tx_w[vec_tx_w < 100]\n vec_tx_w_large = vec_tx_w[vec_tx_w >= 100] # For very large values, log (1 + e^x) ~= log(e^x) = x\n loss_2 = np.sum(np.log(1+np.exp(vec_tx_w_normal))) + np.sum(vec_tx_w_large) \n loss = -np.dot(np.transpose(y),np.dot(tx,w)) + loss_2\n # loss = -np.dot(np.transpose(y),np.dot(tx,w)) + np.sum(np.log(1+np.exp(np.dot(tx,w))))\n return loss\n \ndef calculate_gradient(y, tx, w):\n \"\"\"compute the gradient of loss.\"\"\"\n # Reshape all vectors\n y = np.reshape(y,(len(y),))\n w = np.reshape(w,(len(w),))\n # print('tx,w is : ', np.dot(tx,w))\n # print('norm of the original tx,w is : ', np.linalg.norm(np.dot(tx,w)))\t\n # Get the sigmoid function and reshape it just in case\n logfn = sigmoid(np.dot(tx,w))\n # print('Sigmoid function in calculate_gradient is:', logfn)\n logfn = np.reshape(logfn,(len(logfn),))\n # print('Sigmoid function after reshape in calculate_gradient is:', logfn)\n\t# print('shape of logfn is : ', np.shape(logfn))\n # print('norm of logfn w is : ', np.linalg.norm(logfn))\t\n # Obtain the gradient : delta = X'(sigma - y)\n gradient = np.dot(np.transpose(tx), logfn-y)\n return gradient\n \ndef learning_by_gradient_descent(y, tx, w, gamma):\n # ************ Peforms one iteration of the gradient descent ****************\n \n # Get the loss function\n loss = calculate_loss(y,tx,w) \n \n # Get the gradient of the loss function at the current point\n gradient = calculate_gradient(y,tx,w) \n # print('shape of the original w is : ', np.shape(w))\n # print('norm of the original w is : ', np.linalg.norm(w))\t\n # print('the shape of the gradient is: ', np.shape(gradient))\n # print('norm of the gradient is : ', np.linalg.norm(gradient))\t\n # Update the weight vector using a step size gamma and the direction provided by the gradient\n w = w - gamma*gradient \n # print('gamma*gradient is : ', gamma*gradient)\n # print('norm of the final w is : ', np.linalg.norm(w))\t\n return loss, w\n\ndef calculate_hessian(y, tx, w):\n \"\"\".Return the Hessian of the given function \"\"\"\n # Get the sigmoid function for each sample\n logfn = sigmoid(np.dot(tx,w))\n \n # Get the diagonal vector containing (sigma_n * (1-sigma_n)) for each n\n # S = np.diag(np.multiply(logfn,1-logfn))\n S_vector = np.transpose(np.array([np.multiply(logfn,1-logfn)]))\n \n # Compute the Hessian using X'SX to get a DxD matrix\n # hessian = np.dot(np.transpose(tx), np.dot(S,tx))\n hessian = np.dot(np.transpose(tx), S_vector*tx)\t\n return hessian\n \ndef learning_by_newton_method(y, tx, w,gamma, lambda_):\n \"\"\" Perform one iteration of Newton's method \"\"\"\n \n # Get the loss, gradient and hessian at the current point w\n loss = calculate_loss(y,tx,w)\n gradient = calculate_gradient(y,tx,w)\n hessian = calculate_hessian(y,tx,w)\n print('Gradient before regularization is', np.linalg.norm(gradient))\n if lambda_ > 0:\n loss += lambda_ * np.squeeze(w.T.dot(w))\n gradient += 2 * lambda_ * w\n hessian += lambda_*2 \t\n print('Gradient after regularization is', np.linalg.norm(gradient))\n print('The loss is', loss)\n # print('size of the gradient is', np.shape(gradient))\n # print('size of the hessian is', np.shape(hessian))\n \"\"\" Note that instead of computing the inverse of the hessian and then multiplying by the gradient,\n I solve a linear system -> lambda = inv(H)*gradient => H*lambda = gradient.\n Hence I can calculate lambda and use it for the update : w = w - lambda \"\"\"\n \n lam_ = np.linalg.solve(hessian,gradient)\n # print('size of the lambda_ is', np.shape(lambda_))\n # w = w - gamma*lambda_ \n w = w - gamma*lam_ \n return loss, w\n\ndef logistic_regression(y,tx,isNewton,stepSize,max_iter, lambda_ = 0):\n # First convert the data to a 0-1 scale\n y[np.where(y == -1)] = 0\n\t# init parameters\n # max_iter = 500\n threshold = 1e-6\n# lambda_ = 0.1\n losses = []\n gamma = stepSize\n\n # Initialize guess weights\n w = np.zeros((tx.shape[1], ))\n\n # Start the logistic regression\n for iter in range(max_iter):\n print('ITERATION NUMBER:',iter)\n if(isNewton): # Get the updated w using the Newton's method\n loss, w = learning_by_newton_method(y, tx, w,gamma, lambda_)\n else: # Otherwise, use the Gradient Descent method \n loss, w = learning_by_gradient_descent(y, tx, w, gamma)\n print('The loss is:', loss)\n losses.append(loss) \n if len(losses) > 1 and (np.abs(losses[-1] - losses[-2]))/np.abs(losses[-1]) < threshold:\n break\n \n w_star = w \n return w_star","sub_path":"logistic_regression.py","file_name":"logistic_regression.py","file_ext":"py","file_size_in_byte":5353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"91260036","text":"from mappable import MappableObject\nfrom mappers import *\n\nclass TrainStop(MappableObject):\n _mappings = {\n 'Station' : string_mapper('station'),\n 'Order' : int_mapper('order'),\n 'ArrTime' : string_mapper('arrival_time'),\n 'DepTime' : string_mapper('departure_time')\n }\n\nclass Train(MappableObject):\n _mappings = {\n 'Train' : string_mapper('number'),\n 'BreastFeed': boolean_mapper('has_breastfeeding_rooms'),\n 'Package' : boolean_mapper('carries_packages'),\n 'Dining' : boolean_mapper('has_dining_rooms'),\n 'Cripple' : boolean_mapper('is_accessible'),\n 'Bike' : boolean_mapper('has_bike_stands'),\n 'CarClass' : string_mapper('train_class'),\n 'LineDir': string_mapper('direction'),\n 'TimeInfos': object_list_mapper('stops', TrainStop, 'order')\n }\n\n def __init__(self, json_data):\n for json_key, handler in self.__class__.mappings.items():\n handler(self, json_data, json_key)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"80514016","text":"import schedule\nimport time\nimport os\n'''\nNow supports multiple tasks\nYou could save as a pyc file if having the command line show up is unplesant (I believe)\n'''\n# Still trying to understand ordered dicts so until then\n# working with multiple lists\n\ntime_in_between = 5\n\n'''\ndirectory = 'C:/Users/Steven/GitProjects/PyCron/testfile.py'\nname = 'testfile.py'\n# by default it's set up for running other python files\ncom = 'py'\n'''\n\nname = ''\n\n\n# opens up the cron file to get each commands from it.\ndef choose(file_name):\n with open(file_name) as command_file:\n for line in command_file:\n try:\n global name\n cron_coms = line.split(' ')\n frequency = cron_coms[0]\n number = cron_coms[1]\n command = cron_coms[2]\n path = cron_coms[3]\n name = cron_coms[4]\n set_schedule(frequency, number, command, path)\n # In case someone screws up their commands (didn't put muh thought into it yet)\n except Exception as e:\n print('There was an Error: \\n {}'.format(e))\n\n\n# Checks what command the user inputed and sets up the command accordingly\ndef set_schedule(frequency, number, command, path):\n try:\n int_number = int(number)\n\n if frequency == 'daily':\n schedule.every().day.at(int_number).do(job(command, path))\n elif frequency == 'hourly':\n schedule.every(int_number).hours.do(job(command, path))\n elif frequency == 'minute':\n schedule.every(int_number).minutes.do(job(command, path))\n elif frequency == 'weekly':\n schedule.every(int_number).weeks.do(job(command, path))\n else:\n print('{} is not a valid command'.format(frequency))\n except ValueError:\n print('Could not convert {} into an integer'.format(number))\n except Exception as e:\n print('There was an Error: \\n {}'.format(e))\n\n\ndef job(command, path):\n os.system('cd ' + path)\n os.system(command + ' ' + name)\n print('Job went through.')\n\n\ndef main():\n choose('commands.txt')\n while True:\n schedule.run_pending()\n time.sleep(time_in_between)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pycron.py","file_name":"pycron.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"568264925","text":"import load_data\nimport keras\n\nfrom keras.layers import Conv1D, MaxPooling1D, Embedding, Dense, Dropout, Flatten\nfrom keras.initializers import Constant\n\n\nclass ConvModel(keras.Model):\n def __init__(self, embedding, max_input_length, num_words, embedding_dim, regularization=0.0001, dropout=0.2):\n super(ConvModel, self).__init__()\n\n self.emb = Embedding(\n input_dim=num_words,\n output_dim=embedding_dim,\n input_length = max_input_length,\n embeddings_initializer=Constant(embedding),\n trainable=False)\n\n self.dropout1 = Dropout(dropout)\n\n self.conv1 = Conv1D(\n filters=128,\n kernel_size=3,\n padding='same',\n activation='relu',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n self.maxpooling1 = MaxPooling1D(\n pool_size=2,\n strides=2,\n padding='same')\n\n self.conv2 = Conv1D(\n filters=128,\n kernel_size=3,\n padding='same',\n activation='relu',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n self.maxpooling2 = MaxPooling1D(\n pool_size=2,\n strides=2,\n padding='same')\n\n self.conv3 = Conv1D(\n filters=128,\n kernel_size=3,\n padding='same',\n activation='relu',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n self.maxpooling3 = MaxPooling1D(\n pool_size=2,\n strides=2,\n padding='same')\n\n self.conv4 = Conv1D(\n filters=128,\n kernel_size=3,\n padding='same',\n activation='relu',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n self.maxpooling4 = MaxPooling1D(\n pool_size=2,\n strides=2,\n padding='same')\n\n self.conv5 = Conv1D(\n filters=128,\n kernel_size=3,\n padding='same',\n activation='relu',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n self.maxpooling5 = MaxPooling1D(\n pool_size=2,\n strides=2,\n padding='same')\n\n self.conv6 = Conv1D(\n filters=128,\n kernel_size=3,\n padding='same',\n activation='relu',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n self.maxpooling6 = MaxPooling1D(\n pool_size=2,\n strides=2,\n padding='same')\n\n self.conv7 = Conv1D(\n filters=128,\n kernel_size=3,\n padding='same',\n activation='relu',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n self.maxpooling7 = MaxPooling1D(\n pool_size=2,\n strides=2,\n padding='same')\n\n self.conv8 = Conv1D(\n filters=128,\n kernel_size=3,\n padding='same',\n activation='relu',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n self.maxpooling8 = MaxPooling1D(\n pool_size=2,\n strides=2,\n padding='same')\n\n self.flatten = Flatten()\n\n self.dropout2 = Dropout(dropout)\n\n self.dense = Dense(\n units=3,\n activation='softmax',\n kernel_regularizer=keras.regularizers.l1_l2(l1=regularization, l2=regularization))\n\n\n self.model = keras.Sequential()\n\n self.model.add(self.emb)\n self.model.add(self.dropout1)\n self.model.add(self.conv1)\n self.model.add(self.maxpooling1)\n self.model.add(self.conv2)\n self.model.add(self.maxpooling2)\n self.model.add(self.conv3)\n self.model.add(self.maxpooling3)\n self.model.add(self.conv4)\n self.model.add(self.maxpooling4)\n self.model.add(self.conv5)\n self.model.add(self.maxpooling5)\n self.model.add(self.conv6)\n self.model.add(self.maxpooling6)\n self.model.add(self.conv7)\n self.model.add(self.maxpooling7)\n self.model.add(self.conv8)\n self.model.add(self.maxpooling8)\n self.model.add(self.flatten)\n self.model.add(self.dropout2)\n self.model.add(self.dense)\n","sub_path":"models/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":4535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"386060714","text":"\nimport Queue\nimport argparse\nimport logging\nimport thread\nimport threading\nimport time\n\n#ndn\nclass P2PNode(threading.Thread):\n def __init__(self, n, node_id):\n threading.Thread.__init__(self) \n\n self._n = n\n self._peers = [] \n self._proceed = True \n\n self.id = node_id\n self.message_queue = Queue.Queue() \n\n def _find_peers(self):\n while self._need_peers():\n for i in xrange(self._n):\n peer = nodes[self.id ^ (1 << i)]\n if peer is not None and peer not in self._peers:\n self._peers.append(peer)\n if self._need_peers():\n time.sleep(1) \n\n def _get_message(self):\n message = None\n\n try:\n message = self.message_queue.get(timeout=1) \n logging.debug(\"{s} got message: {m}\".format(s=self, m=message))\n except Queue.Empty:\n pass\n\n return message\n\n def _need_peers(self):\n return len(self._peers) < self._n\n\n def _process_message(self, message):\n message_text = message[0]\n if message_text == \"die\":\n self._proceed = False\n elif message_text == \"report\":\n logging.info(\"{} peers: {}\".format(self, self._peers))\n else:\n logging.warning(\"in {}: unknown message: {}\".format(self, message))\n\n def run(self):\n self._find_peers() \n\n while self._proceed:\n message = self._get_message()\n while self._proceed and message:\n try:\n self._process_message(message)\n self.message_queue.task_done()\n except Exception as e:\n error_message_template = \"In {s}: {t}: {e}; invalid message: {m}\"\n logging.error(error_message_template.format(e=e, m=message, s=self, t=e.__class__.__name__))\n message = self._get_message()\n\ndef init_nodes(n):\n global nodes\n\n nodes = [None] * (2**n) \n\n try:\n for node_id in xrange(2**n):\n node = P2PNode(n, node_id)\n node.setName(\"id={i:0{n}b}\".format(i=node_id, n=n))\n node.start()\n nodes[node_id] = node\n logging.info(\"{} nodes started\".format(len(nodes)))\n except thread.error:\n logging.critical(\"can't create more threads; current amount of nodes is {}\".format(len(filter(None, nodes))))\n kill_all_nodes()\n\n\ndef kill_all_nodes():\n for node in filter(None, nodes):\n node.message_queue.put((\"die\",))\n\n\ndef print_report():\n\n for node in filter(None, nodes):\n node.message_queue.put((\"report\",))\n\n\ndef wait_stop():\n\n try:\n while True:\n pass\n except KeyboardInterrupt:\n logging.info(\"Requesting reports, print Ctrl+C again to terminate...\")\n print_report()\n try:\n while True:\n pass\n except KeyboardInterrupt:\n logging.info(\"Terminating the nodes...\")\n kill_all_nodes()\n\nif __name__ == \"__main__\":\n\n log_level_choices = ['DEBUG', 'INFO']\n args_parser = argparse.ArgumentParser(description=\"Hypercube P2P system\")\n args_parser.add_argument(\"-l\", \"--log-level\", choices=log_level_choices, type=str.upper, help=\"set logging level\")\n args_parser.add_argument(\"-n\", default=2, metavar=\"INTEGER\", type=int, help=\"set number of hypercube dimensions\")\n args = args_parser.parse_args()\n if args.n < 2:\n args_parser.error(\"argument -n: invalid value: {}; must be 2 or more\".format(args.n))\n\n if args.log_level:\n logging.basicConfig(level=args.log_level)\n\n init_nodes(args.n)\n wait_stop()\n","sub_path":"goal1.py","file_name":"goal1.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"180264762","text":"import time\n\nclass LogWatcher(object):\n\n path = \"\"\n interval = 100\n def __init__(self, path, interval):\n self.path = path\n self.interval = int(interval)\n\n def follow(self):\n file = open(self.path)\n file.seek(0,2)\n while True:\n line = file.readline()\n if not line:\n time.sleep(self.interval/1000)\n continue\n yield line\n","sub_path":"threatdetect/backend/LogWatcher.py","file_name":"LogWatcher.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"285504838","text":"from flask import Flask, jsonify\nfrom flasgger import Swagger\nimport flask_sqlalchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/pyswagger_db'\napp.config['SWAGGER'] = {\n 'title': 'Authors API',\n 'uiversion': 2\n}\nSwagger(app)\ndb = flask_sqlalchemy.SQLAlchemy(app)\n","sub_path":"swagger-profile/web/bootstrap.py","file_name":"bootstrap.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"550986132","text":"import sys\nfrom pexpect import spawn\n\n\nclass ExpectValidationError(ValueError):\n pass\n\n\nIP4_ADDR_REGEX = (\n r'^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.'\n r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.'\n r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.'\n r'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'\n)\n\n\nclass MySpawn(spawn):\n def __init__(self, *args, **kwargs):\n super(MySpawn, self).__init__(encoding='utf-8', *args, **kwargs)\n self.logfile = sys.stdout\n\n def do_cmd(self, c, prompt):\n self.sendline(c)\n return self.expect_exact(prompt)\n\n def get_lines(self):\n return self.buffer.split('\\r\\n')\n\n def get_lines_before(self):\n return self.before.split('\\r\\n')\n","sub_path":"devices/device_config/expect_util.py","file_name":"expect_util.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"225485140","text":"from django.conf.urls import url\r\n \r\nfrom . import view, ipTableModel, SearchLayer\r\n\r\nurlpatterns = [\r\n url('hello/', view.hello),\r\n url('login/', view.Login),\r\n url('index/', view.Index, name='index'),\r\n url('welcome/', view.Welcome, name='welcome'),\r\n #管理员路由\r\n url('admin_add/', view.admin_add, name='admin_add'),\r\n url('admin_cate/', view.admin_cate, name='admin_cate'),\r\n url('admin_edit/', view.admin_edit, name='admin_edit'),\r\n url('admin_list/', view.admin_list, name='admin_list'),\r\n url('admin_role/', view.admin_role, name='admin_role'),\r\n url('admin_rule/', view.admin_rule, name='admin_rule'),\r\n #城市\r\n url('cate/', view.cate, name='cate'),\r\n url('city/', view.city, name='city'),\r\n #t图表\r\n url('echart1/', view.echart1, name='echart1'),\r\n url('echart2/', view.echart2, name='echart2'),\r\n url('echart3/', view.echart3, name='echart3'),\r\n url('echart4/', view.echart4, name='echart4'),\r\n url('echart5/', view.echart5, name='echart5'),\r\n url('echart6/', view.echart6, name='echart6'),\r\n url('echart7/', view.echart7, name='echart7'),\r\n url('echart8/', view.echart8, name='echart8'),\r\n #会员管理\r\n url('member_add/', view.member_add, name='member_add'),\r\n url('member_del/', view.member_del, name='member_del'),\r\n url('member_edit/', view.member_edit, name='member_edit'),\r\n url('member_list/', view.member_list, name='member_list'),\r\n url('member_password/', view.member_password, name='member_password'),\r\n #订单管理\r\n url('order_add/', view.order_add, name='order_add'),\r\n url('order_list/', view.order_list, name='order_list'),\r\n url('role_add/', view.role_add, name='role_add'),\r\n url('unicode/', view.unicode, name='unicode'),\r\n #ip池功能\r\n url('ipMain/', view.ipMain, name='ipMain'),\r\n url('SearchIp/', SearchLayer.search_routers, name='SearchIp'),\r\n]","sub_path":"ipPool/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"89333021","text":"import sys\nprint(sys.path)\n# import the necessary packages\nimport argparse\nimport datetime\nimport time\nimport cv2\nimport numpy as np\nfrom classifyCar import classify\nfrom findObjects import findByMovement\nfrom findObjects import findByShapeAndColor\nfrom getCar import get\nimport queue\nimport colorsys\ndef showClassification(kind, desiredKind):\n if desiredKind == \"all\":\n return True\n elif kind == desiredKind:\n return True\n else:\n return False\n\ndef loopContours(cnts, desiredKind):\n global text\n # loop over the contours\n for c in cnts:\n car, rect, height, width, isCar = get(c, args[\"min_area\"], 15, 25)\n if isCar is None:\n continue\n\n classification, kind = classify(c, width, height)\n if showClassification(kind, desiredKind):\n cv2.drawContours(frame, [car], 0, classification, 2)\n printX(car, kind)\n text = \"Occupied\"\n\ndef printX(c, x):\n M = cv2.moments(c)\n cX = int((M[\"m10\"] / M[\"m00\"]))\n cY = int((M[\"m01\"] / M[\"m00\"]))\n cv2.putText(frame, x, (cX+5, cY+5), cv2.FONT_HERSHEY_SIMPLEX,\n 0.5, (255, 255, 255), 2)\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-v\", \"--video\", help=\"path to the video file\")\n# TODO: determine minimum area from height\nap.add_argument(\"-a\", \"--min-area\", type=int, default=100, help=\"minimum area size\")\nap.add_argument(\"-c\", \"--color\", help=\"vehicle color to detect\")\nap.add_argument(\"-b\", \"--brand\", help=\"vehicle kind to detect\")\nargs = vars(ap.parse_args())\nprint(\"video\")\nprint(args[\"video\"])\nprint(\"color\")\nprint(args[\"color\"])\nprint(\"brand\")\nprint(args[\"brand\"])\n# if the video argument is None, then we are reading from webcam\nif args.get(\"video\", None) is None:\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/intersect/DJI_0002_240meters.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/intersect/DJI_0003_240meters.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/matz/DJI_0003.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/matz/DJI_0004.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/matz/DJI_0005.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/matz/DJI_0006.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/matz/DJI_0007.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/matz/DJI_0008.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/accident/DJI_0012.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/accident/DJI_0013.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/accident/DJI_0014.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/2017-05-15_Gadera_200m/DJI_0003.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/2017-05-15_Gadera_200m/DJI_0004.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/2017-05-15_Gadera_200m/DJI_0005.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/2017-05-15_Gadera_200m/DJI_0006.MOV\")\n camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/2017-06-01_Parking_junction_180m/DJI_0001.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/2017-06-01_Parking_junction_180m/DJI_0002.MOV\")\n #camera = cv2.VideoCapture(\"C:/Users/royshahaf/Desktop/hacknprotect/video/2017-06-01_Parking_junction_180m/DJI_0003.MOV\")\n\n# otherwise, we are reading from a video file\nelse:\n camera = cv2.VideoCapture(args[\"video\"])\n\nif args.get(\"brand\", None) is None:\n desiredKind = \"all\"\nelse:\n desiredKind = args[\"brand\"]\nif args.get(\"color\", None) is None:\n color = \"all\"\nelse:\n color = args[\"color\"]\n# initialize the first frame in the video stream\nprevGray = None\n# loop over the frames of the video\nq = queue.Queue()\n\n\ndef getMask(color):\n global mask\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n if color == \"red\":\n # lower mask (0-10)\n lower_red = np.array([0, 130, 60])\n upper_red = np.array([20, 255, 255])\n mask0 = cv2.inRange(hsv, lower_red, upper_red)\n # upper mask (160-180)\n lower_red = np.array([150, 130, 60])\n upper_red = np.array([180, 255, 255])\n mask1 = cv2.inRange(hsv, lower_red, upper_red)\n # join my masks\n mask = mask0 + mask1\n elif color == \"white\":\n # lower = np.array([0, 0, 200])\n #upper = np.array([180, 255, 255])\n lower = np.array([0, 0, 230])\n upper = np.array([180, 30, 255])\n mask = cv2.inRange(hsv, lower, upper)\n elif color == \"blue\":\n lower = np.array([85, 130, 60])\n upper = np.array([120, 255, 255])\n mask = cv2.inRange(hsv, lower, upper)\n elif color == \"black\":\n lower = np.array([0, 0, 0])\n upper = np.array([180, 255, 50])\n mask1 = cv2.inRange(hsv, lower, upper)\n lower_black = np.array([70, 139, 51])\n upper_black = np.array([90, 255, 80])\n mask0 = cv2.inRange(hsv, lower_black, upper_black)\n mask = mask0 + mask1\n elif color == \"green\":\n lower = np.array([50, 130, 60])\n upper = np.array([70, 255, 255])\n mask = cv2.inRange(hsv, lower, upper)\n else:\n lower = np.array([0, 0, 0])\n upper = np.array([255, 255, 255])\n mask = cv2.inRange(hsv, lower, upper)\n img = hsv.copy()\n img[np.where(mask==0)] = 0\n #cv2.imshow ('mask', img)\n\nhistory = 3\n\n\ndef modifyHistory():\n global history\n if history > 2 and len(cnts) > 50:\n print(\"decreasing history\")\n history = history - 1\n print(history)\n elif history < 50 and len(cnts) < 200:\n print(\"increasing history\")\n history = history + 1\n print(history)\n\n\nwhile True:\n # grab the current frame and initialize the occupied/unoccupied\n # text\n (grabbed, frame) = camera.read()\n text = \"Unoccupied\"\n\n # if the frame could not be grabbed, then we have reached the end\n # of the video\n if not grabbed:\n break\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (3, 3), 0)\n q.put(gray)\n\n if q.qsize() < history:\n continue\n\n prevGray = q.get()\n getMask(color)\n #cnts = findByShapeAndColor(frame, mask)\n useColor = True\n if color is \"all\":\n useColor = False\n cnts = findByMovement(frame, gray, prevGray, mask, useColor)\n #modifyHistory()\n loopContours(cnts, desiredKind)\n cv2.putText(frame, \"Tracking Status: {}\".format(text), (10, 20),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n cv2.putText(frame, datetime.datetime.now().strftime(\"%A %d %B %Y %I:%M:%S%p\"),\n (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)\n # show the frame and record if the user presses a key\n cv2.imshow(\"Camera Feed\", frame)\n key = cv2.waitKey(1) & 0xFF\n\n # if the `q` key is pressed, break from the lop\n if key == ord(\"q\"):\n break\n\n# cleanup the camera and close any open windows\ncamera.release()\ncv2.destroyAllWindows()","sub_path":"project/mainWithColor.py","file_name":"mainWithColor.py","file_ext":"py","file_size_in_byte":7406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"506930698","text":"from typing import List\n\n\nclass Solution:\n def sortColors(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n 16 ms\t13.9 M\n \"\"\"\n if len(nums) <= 1:\n return\n\n last_non_zero = 0\n for i in range(len(nums)):\n if nums[i] == 0:\n swap(nums, last_non_zero, i)\n last_non_zero += 1\n\n last_non_one = last_non_zero\n for i in range(last_non_zero, len(nums)):\n if nums[i] == 1:\n swap(nums, last_non_one, i)\n last_non_one += 1\n\n\ndef swap(nums: List[int], i: int, j: int):\n tmp = nums[i]\n nums[i] = nums[j]\n nums[j] = tmp\n\n\nif __name__ == '__main__':\n s = Solution()\n l = [2, 0, 2, 1, 1, 0]\n l = [1, 1, 1, 1, 1]\n l = [0, 0, 0, 0]\n l = [2, 2, 2, 2, 2]\n s.sortColors(l)\n print(l)\n","sub_path":"python/075.py","file_name":"075.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"165803017","text":"from app import Session\r\n\r\nfrom app.model.contacts import Contacts\r\n\r\n\r\ndef insert(data):\r\n conn = Session()\r\n conn.add(data)\r\n conn.commit()\r\n conn.close()\r\n\r\ndef readall():\r\n conn = Session()\r\n query = conn.query(Contacts).order_by(Contacts.name).all()\r\n result = [(row.name,row.fone) for row in query]\r\n conn.close()\r\n return result\r\n\r\nif __name__ == '__main__':\r\n insert(Contacts('data1','1111'))\r\n insert(Contacts('data2','2222'))\r\n insert(Contacts('data3','3333'))\r\n [print(f'Name: {row[0][:10]:10} - Fone: {row[1]}') for row in readall()]\r\n","sub_path":"SQLAlchemy/Source/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"147972770","text":"import sys\nimport random\n\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as func\nfrom torch.nn.utils.spectral_norm import spectral_norm\nfrom torchsupport.training.gan import RothGANTraining\nfrom torchsupport.optim.diffmod import DiffMod\n\nfrom torchsupport.modules.basic import MLP\nfrom torchsupport.data.io import to_device, make_differentiable\nfrom torchsupport.modules.generative import StyleGANBlock\nfrom torchsupport.structured import PackedTensor, ConstantStructure, SubgraphStructure\nfrom torchsupport.structured import DataParallel as SDP\nfrom torchsupport.structured import scatter\n\nfrom protsupport.data.proteinnet import ProteinNet, ProteinNetKNN\nfrom protsupport.utils.geometry import orientation\nfrom protsupport.modules.structures import RelativeStructure\nfrom protsupport.modules.distance_graph_gan import DistanceGenerator, DistanceDiscriminator\nfrom protsupport.modules.anglespace import PositionLookup\nfrom protsupport.modules.backrub import Backrub\nfrom protsupport.modules.transformer import attention_connected, linear_connected, assignment_connected\n\nAA_CODE = \"ACDEFGHIKLMNPQRSTVWY\"\n\nclass GANNet(ProteinNetKNN):\n def __init__(self, path, num_neighbours=20, N=256, n_jobs=1, cache=True):\n ProteinNetKNN.__init__(\n self, path,\n num_neighbours=num_neighbours,\n n_jobs=n_jobs, cache=cache\n )\n self.N = N\n self.valid_indices = [\n index\n for index in range(len(self.index) - 1)\n if self.index[index + 1] - self.index[index] >= N\n ]\n self.backrub = Backrub(n_moves=0)\n self.ors = torch.tensor(\n orientation(self.ters[1].numpy() / 100).transpose(2, 0, 1),\n dtype=torch.float\n )\n\n def __getitem__(self, index):\n N = self.N\n index = self.valid_indices[index]\n window = slice(self.index[index], min(self.index[index + 1], self.index[index] + N))\n inds = self.inds[window]\n primary = self.pris[window] - 1\n\n # add noise:\n n_positions = random.randrange(max(1, primary.size(0) // 100))\n primary[torch.randint(0, primary.size(0), (n_positions,))] = torch.randint(0, 20, (n_positions,))\n\n tertiary = self.ters[:, :, window]\n tertiary, angles = self.backrub(tertiary[[0, 1, 3]].permute(2, 0, 1))\n\n left = torch.repeat_interleave(torch.arange(3), 3 * torch.ones(3, dtype=torch.long))\n right = torch.arange(9) - 3 * left\n tertiary = tertiary / 100\n\n protein = SubgraphStructure(torch.zeros(tertiary.size(0), dtype=torch.long))\n #neighbours = ConstantStructure(0, 0, (inds - self.index[index]).to(torch.long))\n #distances, _ = scatter.pairwise_no_pad(lambda x, y: (x - y).norm(dim=1), tertiary, protein.indices)\n distances = (tertiary[None, :, right, :] - tertiary[:, None, left, :]).norm(dim=-1)\n distances = distances.permute(2, 0, 1).contiguous()\n #distances = distances.unsqueeze(0)\n\n mask = torch.arange(N)\n mask = (mask[:, None] - mask[None, :]) > 0\n mask = mask.float()\n \n distances = mask * distances + (1 - mask) * distances.permute(0, 2, 1)\n #distances[1:] = distances[1:] - distances[:1]\n\n primary_onehot = torch.zeros(primary.size(0), 20, dtype=torch.float)\n primary_onehot[torch.arange(primary.size(0)), primary] = 1\n primary_onehot = primary_onehot.clamp(0, 1)\n\n return (distances / 100,)\n\n def __len__(self):\n return len(self.valid_indices)\n\nclass AngleGANTraining(RothGANTraining):\n def mixing_key(self, data):\n return data[0]\n\n def each_generate(self, data, generated, sample):\n with torch.no_grad():\n distances, *_ = generated\n real, *_ = data\n rdist = real.cpu()\n dist = distances.cpu()\n\n dist = dist.numpy()\n fig, ax = plt.subplots()\n ax.matshow(dist[0, 0])\n self.writer.add_figure(\"dist\", fig, self.step_id)\n\n fig, ax = plt.subplots()\n ax.matshow(dist[0, 1])\n self.writer.add_figure(\"dist 01\", fig, self.step_id)\n\n rdist = rdist.numpy()\n fig, ax = plt.subplots()\n ax.matshow(rdist[0, 0])\n self.writer.add_figure(\"real dist\", fig, self.step_id)\n\nclass DDP(nn.Module):\n def __init__(self, net):\n super().__init__()\n self.net = net\n\n def sample(self, *args, **kwargs):\n return self.net.sample(*args, **kwargs)\n\n def forward(self, *args):\n inputs = []\n print(args)\n for arg in args:\n print(type(arg))\n if isinstance(arg, PackedTensor):\n print(\"yay\")\n inputs.append(arg.tensor)\n else:\n inputs.append(arg)\n return self.net(*inputs)\n\nclass Generator(nn.Module):\n def __init__(self):\n super().__init__()\n self.preprocess = nn.Linear(512, 128 * 4 * 4)\n self.blocks = nn.ModuleList([\n nn.Sequential(\n nn.Conv2d(128, 64, 3, padding=1),\n nn.InstanceNorm2d(64),\n nn.Conv2d(64, 128, 3, padding=1),\n nn.InstanceNorm2d(128),\n nn.ReLU()\n )\n for idx in range(6)\n ])\n self.postprocess = nn.Sequential(\n nn.Conv2d(128, 64, 3, padding=1),\n nn.InstanceNorm2d(64),\n nn.Conv2d(64, 1, 3, padding=1)\n )\n\n def sample(self, batch_size):\n return torch.randn(batch_size, 512)\n\n def forward(self, sample):\n out = self.preprocess(sample).view(-1, 128, 4, 4)\n for block in self.blocks:\n out = out + block(out)\n out = func.interpolate(out, scale_factor=2, mode=\"bilinear\")\n #out = out + 0.1 * torch.randn_like(out)\n out = func.softplus(self.postprocess(out))\n out = (out + out.permute(0, 1, 3, 2)) / 2\n out[:, :, torch.arange(256), torch.arange(256)] = 0\n return (out,)\n\nclass StyleGenerator(nn.Module):\n def __init__(self):\n super().__init__()\n self.mapping = MLP(512, 512, hidden_size=128, depth=8, batch_norm=False)\n start_features = 512\n self.blocks = nn.ModuleList([\n StyleGANBlock(\n start_features,\n 128,\n start_features,\n size=(4, 4),\n activation=func.relu_\n )\n ] + [\n StyleGANBlock(\n 128,\n 128,\n start_features,\n activation=func.relu_\n )\n for idx in range(6)\n ])\n self.postprocess = nn.Conv2d(128, 1, 3, padding=1)\n\n def sample(self, batch_size):\n return torch.randn(batch_size, 512)\n\n def forward(self, sample):\n cond = self.mapping(sample)\n out = cond\n for block in self.blocks:\n out = block(out, cond)\n out = func.softplus(self.postprocess(out))\n out = (out + out.permute(0, 1, 3, 2)) / 2\n out[:, :, torch.arange(256), torch.arange(256)] = 0\n return (out,)\n\nclass StupidGenerator(nn.Module):\n def __init__(self, depth=4):\n super().__init__()\n self.preprocess = nn.Linear(512, 128 * 4 * 4, bias=True)\n self.blocks = nn.ModuleList([\n nn.Sequential(\n nn.Conv2d(128, 128, 3, padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU()\n )\n for idx in range(depth)\n ])\n self.postprocess = nn.Conv2d(128, 9, 3, padding=1)\n\n def sample(self, batch_size):\n return torch.randn(batch_size, 512)\n\n def forward(self, sample):\n out = self.preprocess(sample).view(-1, 128, 4, 4)\n for idx, block in enumerate(self.blocks):\n out = block(out)\n out = func.interpolate(out, scale_factor=2)\n out = func.softplus(self.postprocess(out))\n out = (out + out.permute(0, 1, 3, 2)) / 2\n size = out.size(-1)\n out[:, 0, torch.arange(size), torch.arange(size)] = 0\n return (out,)\n\nclass MaskedGenerator(nn.Module):\n def __init__(self, data, depth=6):\n super().__init__()\n self.data = data\n self.masked_process = nn.Conv2d(4, 64, 3, padding=1)\n self.encoder_blocks = nn.ModuleList([\n nn.Sequential(\n nn.Conv2d(64, 64, 3, padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU()\n )\n for idx in range(depth)\n ])\n\n self.preprocess = nn.Linear(512, 128 * 4 * 4, bias=False)\n self.blocks = nn.ModuleList([\n nn.Sequential(\n nn.Conv2d(128 + 64, 128, 3, padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU()\n )\n for idx in range(depth)\n ])\n self.postprocess = nn.Conv2d(128, 1, 3, padding=1)\n\n def sample(self, batch_size):\n assembled, given, g_mask, r_mask, range_mask = random.choice(self.data)\n return torch.randn(batch_size, 512), given, g_mask, r_mask, range_mask\n\n def forward(self, sample):\n latent, given, g_mask, r_mask, range_mask = sample\n mask = torch.cat((given, g_mask, r_mask, range_mask), dim=1)\n shortcut = []\n out = self.masked_process(mask)\n shortcut.append(out)\n for block in self.blocks:\n out = func.avg_pool2d(out, 2)\n out = block(out)\n shortcut.append(out)\n\n out = self.preprocess(latent).view(-1, 128, 4, 4)\n for idx, block in enumerate(self.blocks):\n combined = torch.cat((out, shortcut[-idx]), dim=1)\n out = block(combined)\n out = func.interpolate(out, scale_factor=2)\n combined = torch.cat((out, shortcut[0]), dim=1)\n out = func.softplus(self.postprocess(out))\n out = (out + out.permute(0, 1, 3, 2)) / 2\n size = out.size(-1)\n out[:, :, torch.arange(size), torch.arange(size)] = 0\n out = r_mask * out + g_mask * given\n return (out, given, g_mask, r_mask, range_mask)\n\nclass Discriminator(nn.Module):\n def __init__(self, depth=4):\n super().__init__()\n self.preprocess = nn.Conv2d(9, 128, 5, padding=2)\n self.blocks = nn.ModuleList([\n nn.Sequential(\n nn.Conv2d(128, 128, 3, padding=1),\n nn.InstanceNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 128, 3, dilation=2, padding=2),\n nn.InstanceNorm2d(128),\n nn.ReLU()\n )\n for idx in range(depth)\n ])\n self.predict = nn.Linear(128, 1)\n\n def forward(self, inputs):\n inputs, *_ = inputs\n out = self.preprocess(inputs)\n for block in self.blocks:\n out = out + block(out)\n out = func.avg_pool2d(out, 2)\n out = func.adaptive_avg_pool2d(out, 1).view(-1, 128)\n out = self.predict(func.dropout(out, 0.5))\n return out\n\nclass MaskedDiscriminator(nn.Module):\n def __init__(self):\n super().__init__()\n self.preprocess = nn.Conv2d(5, 128, 5, padding=2)\n self.blocks = nn.ModuleList([\n nn.Sequential(\n nn.Conv2d(128, 128, 3, padding=1),\n nn.InstanceNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 128, 3, dilation=2, padding=2),\n nn.InstanceNorm2d(128),\n nn.ReLU()\n )\n for idx in range(6)\n ])\n self.predict = nn.Linear(128, 1)\n\n def forward(self, inputs):\n inputs = torch.cat(inputs, dim=1)\n out = self.preprocess(inputs)\n for block in self.blocks:\n out = out + block(out)\n out = func.avg_pool2d(out, 2)\n out = func.adaptive_avg_pool2d(out, 1).view(-1, 128)\n out = self.predict(func.dropout(out, 0.5))\n return out\n\nif __name__ == \"__main__\":\n data = GANNet(sys.argv[1], num_neighbours=15, N=64)\n gen = SDP(\n StupidGenerator()\n )\n disc = SDP(\n Discriminator()\n )\n training = AngleGANTraining(\n gen, disc, data,\n batch_size=20,\n max_epochs=1000,\n #optimizer=DiffMod,\n device=\"cuda:0\",\n network_name=\"distance-gan/alldist-fml-noneg-bias\",\n verbose=True,\n report_interval=10\n )\n final_net = training.train()\n","sub_path":"protsupport/training/train_simple_alldist_gan.py","file_name":"train_simple_alldist_gan.py","file_ext":"py","file_size_in_byte":11150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"324896684","text":"\"\"\"\nLibrary Features:\n\nName: Lib_Model_RainFarm_Apps\nAuthor(s): Fabio Delogu (fabio.delogu@cimafoundation.org)\n Nicola Rebora (nicola.rebora@cimafoundation.org)\n Mirko D'Andrea (mirko.dandrea@cimafoundation.org)\n Lorenzo Campo (lcampo@gmail.com)\nDate: '20171114'\nVersion: '3.0.1'\n\"\"\"\n\nfrom __future__ import division\nimport numpy as np\nimport numpy.fft as fft\n\n# import matplotlib.pylab as plt\n\nif 'nanmean' not in dir(np):\n import scipy.stats\n np.nanmean = scipy.stats.nanmean\n\n\ndef fft3d(z):\n '''Calcola i parametri di slope'''\n \n ns, ns, nt = z.shape\n\n zf = np.abs(fft.fftn(z)/(ns*ns*nt))**2\n\n zf0 = zf\n\n ns_int = int(ns / 2)\n zf[ns_int, :, :] = zf0[ns_int, :, :]/2\n zf[:, ns_int, :] = zf0[:, ns_int, :]/2\n nt_int = int(nt / 2)\n zf[:, :, nt_int] = zf0[:, :, nt_int]/2\n\n fs = np.reshape(np.sum(zf,2), (ns,ns), order='F')\n ft = np.reshape(np.sum(np.sum(zf, 0), 0), (nt,1), order='F')\n\n fs = fft.fftshift(fs)\n \n #import scipy.io as sio\n #oMat = sio.loadmat('fs.mat')\n \n #fs = oMat['fs']\n \n #plt.figure(1)\n #plt.imshow(fs, interpolation='none'); plt.colorbar()\n #plt.show()\n\n nn = np.zeros((ns, 1))\n fx = np.zeros((ns, 1))\n \n #storemat = np.zeros([100,8]);\n #f = 0\n for j in np.arange(-ns/2, ns/2):\n for i in np.arange(-ns/2, ns/2):\n k2 = np.sqrt(i*i+j*j)\n ik2 = int(np.floor(k2 + 1.5)) # Fabio: index issue in python\n if ik2 > 1:\n \n ii = int(i + ns/2 + 1)\n jj = int(j + ns/2 + 1)\n value_fs = fs[ii-1, jj-1]\n value_fx = fx[ik2-1]\n value_nn = nn[ik2-1] + 1\n \n value_fx_tot = value_fx + value_fs\n \n #### DEBUG START\n #print( str(i) + ' ' + str(j) + ' ' + str(f))\n #storemat[f,0] = k2;\n #storemat[f,1] = ik2;\n #storemat[f,2] = ii;\n #storemat[f,3] = jj;\n #storemat[f,4] = value_fs;\n #storemat[f,5] = value_fx;\n #storemat[f,6] = value_nn;\n #storemat[f,7] = value_fx_tot;\n #f = f+1\n #### DEBUG END\n \n fx[ik2-1] = value_fx_tot\n nn[ik2-1] = value_nn\n\n \n #sio.savemat('storemat_python.mat', mdict={'storemat': storemat})\n\n ns_int = int(ns / 2)\n nt_int = int(nt / 2)\n\n ft = ft[1:nt_int + 1]\n fx = fx[1:ns_int + 1]/nn[1:ns_int + 1]\n fy = fx.copy()\n\n return fx, fy, ft\n\n\ndef fitallslopes(fx, fy, ft, xr, tr):\n '''\n ''' \n #ns = len(fx)\n #nt = len(ft)\n # ns=20 nt=20\n sx = fitslope(fx, xr)\n sy = fitslope(fy, xr)\n st = fitslope(ft, tr)\n sx = np.abs(sx)\n st = np.abs(st)\n sy = np.abs(sy)\n # sx=(sx+sy)*0.5\n sx = sx-1\n #print(' -----> Slopes: sx=%f sy=%f st=%f'%(sx, sy, st))\n return sx, sy, st\n\n\ndef fitslope(fx, ii):\n '''\n '''\n nr, nc = fx.shape\n s = np.zeros((nc,))\n\n for i in range(0, nc):\n ss = np.polyfit(np.log(ii+1), np.log(fx[ii, i]), 1)\n s[i] = ss[0]\n\n return s\n\n\ndef agg_xyt(zi, nax, nay, nat):\n\n nax = int(nax)\n nay = int(nay)\n nat = int(nat)\n\n nx, ny, nt = zi.shape\n if (nay == nax) and (nat == nt):\n sf = nx/nax\n xa = np.squeeze(np.nanmean(np.reshape(zi, (int(sf), int(nx*ny*nt/sf)),\n order='F'), 0))\n xz = np.reshape(np.nanmean(np.reshape(xa.T, (int(nx/sf), int(sf), int(ny/sf), nt),\n order='F'), 1), (nax, nay, nt), order='F')\n else:\n\n xdim = int(nx / nax)\n ydim = int(ny / nay)\n tdim = int(nt / nat)\n rx = np.arange(0, nx, xdim)\n ry = np.arange(0, ny, ydim)\n rt = np.arange(0, nt, tdim)\n xz = np.zeros((nax, nay, nat))\n\n rx_len = rx.__len__()\n ry_len = ry.__len__()\n rt_len = rt.__len__()\n\n if rx_len > 1 and ry_len > 1 and rt_len > 1:\n\n for i in range(0, xdim):\n for j in range(0, ydim):\n for k in range(0, tdim):\n xz = xz + zi[np.ix_(i + rx, j + ry, k + rt)]\n\n elif rx_len == 1 and ry_len == 1 and rt_len == 1:\n\n xz = np.nansum(zi)\n\n else:\n raise NotImplementedError('Aggregation XYT case not implemented yet')\n\n xz = xz / (xdim * ydim * tdim)\n\n return xz\n\n\ndef initmetagauss(sx,st,ns,nt):\n '''\n kx = initmetagauss(sx,st,nso,nto)\n \n Generates the amplitudes f for a metagaussian field of size nso x nso x nto\n with slopes sx and st, no padding\n '''\n\n sx = np.abs(sx)\n st = np.abs(st)\n\n kx = np.concatenate((np.arange(0, ns/2+1), np.arange(-ns/2+1, 0))).T\n kx = kx.reshape((ns,1)).dot(np.ones((1,ns)))\n kx = np.expand_dims(kx, 2)\n kx = np.tile(kx, (1, 1, nt))\n kx = kx**2 + kx.transpose((1, 0, 2))**2\n kx[0,0,:]=0.000001\n\n kt = np.concatenate((np.arange(0, nt/2+1), np.arange(-nt/2+1, 0))).T\n kt = kt.reshape((nt,1)).dot(np.ones((1,ns)))\n \n kt = np.expand_dims(kt, 2)\n kt = np.tile(kt, (1, 1, ns))\n kt = kt.transpose((2, 1, 0))**2\n kt[:,:,0]=0.000001\n\n kx = (kx**(-(sx+1)/4)) * kt**(-st/4)\n\n kx[0, 0, 0] = 0\n kx[0, 0, :] = 0 \n kx[:,:,0] = 0\n\n kx = kx/np.sqrt(np.sum(np.abs(kx.flat)**2)) * ns * ns * nt\n \n return kx\n\n\ndef metagauss(f):\n ''' \n g=metagauss(sx,st,nso,nto)\n Generates a metagaussian field of size ns x ns x nt with slopes sx and st\n this version creates an output in fourier space and does not use padding\n '''\n ns,ns,nt = f.shape\n\n # phases as fft of a gaussian noise random field\n \n ph = np.random.randn(ns,ns,nt)\n\n ph = fft.fftn(ph)\n ph = ph/np.abs(ph)\n ph[0,0,0] = 0\n ph = f*ph\n\n ph = fft.ifftn(ph).real\n return ph\n\n\ndef interpola_xyt(z, nx, ny, nt):\n '''\n '''\n nax,nay,nat = z.shape\n\n xdim = int(nx/nax)\n ydim = int(ny/nay)\n tdim = int(nt/nat)\n # # ir=1:xdim jr=ydim kr=1:tdim\n rx = np.arange(0, nx, xdim).astype('int32')\n ry = np.arange(0, ny, ydim).astype('int32')\n rt = np.arange(0, nt, tdim).astype('int32')\n\n zi = np.zeros((nx,ny,nt))\n\n for i in range(0, xdim):\n for j in range(0, ydim):\n for k in range(0, tdim):\n zi[np.ix_(i+rx, j+ry, k+rt)] = z\n return zi\n","sub_path":"src/hyde/model/rfarm/lib_rfarm_apps.py","file_name":"lib_rfarm_apps.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"566642457","text":"\"\"\"\r\n Gridworld environment \r\n\r\n Custom Environment for the GridWorld Problem\r\n example based on the book Deep Reinforcement Learning\r\n\r\n Author: Ivan Dewerpe\r\n\"\"\"\r\n\r\nclass GridWorldEnv():\r\n \"\"\"\r\n GridWorldEnv encapsulates the environment for the GridWorld\r\n Problem with custom functions for a reinforcement learning\r\n using agent.\r\n \"\"\"\r\n\r\n def __init__(self, grid_dimension=7, start_state='00', terminal_state=['64'], ditches=['52'],\r\n ditch_penalty=-10, turn_penalty=-1, win_reward=100, mode=\"PROD\"):\r\n \"\"\"\r\n Construct a new GridWorldEnv object\r\n\r\n :param grid_dimension: n value for a grid size nxn\r\n :param start_state: Entry point value of the grid cell\r\n :param terminal_state: List of grid cell values for which there exists a terminal state\r\n :param ditches: List of grid cell values for which there exists a ditch\r\n :param ditch_penalty: Penalty if you hit a ditch\r\n :param turn_penalty: Negative reward for every turn to ensure that agent completes the \r\n episode in minimum number of turns.\r\n :param win_reward: Reward gained for reaching the goal/terminate state.\r\n :param mode: (PROD/DEBUG) indicating the run mode. Verbosity of messages\r\n :return: returns nothing\r\n\r\n \"\"\"\r\n self.grid_dimension = min(grid_dimension, 9)\r\n self.start_state = start_state\r\n self.terminal_state = terminal_state\r\n self.ditches = ditches\r\n self.ditch_penalty = ditch_penalty\r\n self.turn_penalty = turn_penalty\r\n self.win_reward = win_reward\r\n self.mode = mode\r\n\r\n self.create_statespace()\r\n self.actionspace = [0,1,2,3]\r\n self.action_dict = {0:'UP', 1:'DOWN', 2:'LEFT', 3:'RIGHT'}\r\n self.state_count = self.get_statespace_len()\r\n self.action_count = self.get_actionspace_len()\r\n self.state_dict = {k:v for k,v in zip(self.statespace, range(self.state_count))}\r\n self.current_state = self.start_state\r\n\r\n if self.mode == \"debug\":\r\n #Debug code\r\n print(\"DUBGGING\")\r\n \r\n def create_statespace(self):\r\n \"\"\"\r\n Create Statespace\r\n\r\n Makes the GridWorld space with desired dimensions.\r\n \"\"\"\r\n self.statespace = []\r\n # A state is a string \"xy\" x - row, y - column\r\n for row in range(self.grid_dimension):\r\n for column in range(self.grid_dimension):\r\n self.statespace.append(str(row) + str(column))\r\n \r\n def get_statespace(self):\r\n return self.statespace\r\n\r\n def get_statespace_len(self):\r\n return len(self.statespace)\r\n\r\n def set_mode(self, mode):\r\n self.mode = mode\r\n \r\n def get_actionspace(self):\r\n return self.actionspace\r\n \r\n def get_actionspace_len(self):\r\n return len(self.actionspace)\r\n\r\n def get_action_dict(self):\r\n return self.action_dict\r\n \r\n ###############################################################################################\r\n def next_state(self, current_state, action):\r\n \"\"\"\r\n Next State\r\n\r\n Returns the next state given an action taken in the environment\r\n :param current_state: The current state at which the agent takes the action \r\n :param action: Action taken by the agent\r\n :return: returns next state\r\n \r\n \"\"\"\r\n current_row = int(current_state[0])\r\n current_column = int(current_state[1])\r\n\r\n next_row = current_row\r\n next_column = current_column\r\n\r\n max_cell_value = self.grid_dimension\r\n current_action = self.action_dict[action]\r\n\r\n if 'UP' == current_action: next_row = max(0, current_row - 1)\r\n elif 'DOWN' == current_action: next_row = min(max_cell_value - 1, current_row + 1)\r\n elif 'LEFT' == current_action: next_column = max(0, current_column - 1)\r\n elif 'RIGHT' == current_action: next_column = min(max_cell_value - 1, current_column + 1)\r\n\r\n next_state = str(next_row) + str(next_column)\r\n\r\n if next_state in self.statespace:\r\n if next_state in self.terminal_state: self.is_game_end = True\r\n if self.mode == 'DEBUG':\r\n print(\"Curent State:{}, Action:{}, NextState:{}\"\r\n .format(current_state, current_action, next_state))\r\n return next_state\r\n else:\r\n return current_state\r\n \r\n ###############################################################################################\r\n def compute_reward(self, state):\r\n \"\"\"\r\n Compute Reward\r\n\r\n Computes the reward for arriving at a given state based on ditches and the end goal\r\n :param state: State we have arrived in as cell co-ordinate\r\n :return: returns the reward corresponding to the state\r\n \"\"\"\r\n reward = 0\r\n reward += self.turn_penalty\r\n if state in self.ditches: reward += self.ditch_penalty\r\n if state in self.terminal_state: reward += self.win_reward\r\n \r\n return reward\r\n \r\n ###############################################################################################\r\n def reset(self):\r\n \"\"\"\r\n Reset\r\n\r\n Resets map, reward, states to original settings.\r\n :return: returns fresh entry state for agent\r\n \"\"\"\r\n self.accumulated_reward = 0\r\n self.current_state = self.start_state\r\n self.total_turns = 0\r\n self.is_game_end = False\r\n \r\n return self.current_state \r\n\r\n def step(self, action):\r\n \"\"\"\r\n Step\r\n\r\n Makes the agent take the suggested action\r\n\r\n :param action: Action to be taken by the agent\r\n :return: returns a tuple of (next_state, instant_reward, done_flag, info) \r\n \"\"\"\r\n if self.is_game_end:\r\n raise('Game is Over Exception')\r\n if action not in self.actionspace:\r\n raise('Invalid Action Exception')\r\n \r\n self.current_state = self.next_state(self.current_state, action)\r\n observed_state = self.current_state\r\n reward = self.compute_reward(observed_state)\r\n self.total_turns += 1\r\n \r\n if self.mode == 'DEBUG':\r\n print(\"Obs:{}, Reward:{}, Done:{}, Total Turns:{}\"\r\n .format(observed_state, reward, self.is_game_end, self.total_turns))\r\n \r\n return observed_state, reward, self.is_game_end, self.total_turns\r\n\r\nif __name__ == '__main__':\r\n \"\"\"\r\n Main Function to test the code\r\n \"\"\"\r\n env = GridWorldEnv(mode='DEBUG')\r\n env.reset()\r\n env.step(1)\r\n env.step(3)\r\n env.step(2)","sub_path":"gridworld/environment/gridworld.py","file_name":"gridworld.py","file_ext":"py","file_size_in_byte":6740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"59818216","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport keras\r\nimport os\r\nimport tensorflow.examples.tutorials.mnist.input_data as input_data\r\nfrom keras.utils import np_utils\r\nfrom keras.datasets import mnist\r\nimport matplotlib.pyplot as plt\r\n(x_train_image,y_train_lable),\\\r\n(x_test_image,y_test_lable) = mnist.load_data('mnist.npz')\r\n#定义函数来展示图片\r\ndef plot_images_lables_prediction(images,lables,prediction,idx,num=10):\r\n fig = plt.gcf()\r\n fig.set_size_inches(12,14)\r\n if num>25: num=25\r\n for i in range(0,num):\r\n ax = plt.subplot(5,5,1+i)\r\n ax.imshow(images[idx], cmap = 'binary')\r\n title = \"lable=\"+str(lables[idx])\r\n if len(prediction)>0:\r\n title+=\",prediction=\"+str(prediction[idx])\r\n ax.set_title(title,fontsize=10)\r\n ax.set_xticks([]);ax.set_yticks([])\r\n idx+=1\r\n plt.show()\r\nplot_images_lables_prediction(x_test_image,y_test_lable,[],0,10)\r\n\r\nx_Train =x_train_image.reshape(60000,784).astype('float32')\r\nx_Test =x_test_image.reshape(10000,784).astype('float32')\r\nprint('x_train',x_Train)\r\nprint('x_test',x_Test)\r\n\r\nx_Train_normalize =x_Train/255\r\nx_Test_normalize =x_Test/255\r\nprint('x_train_normalize',x_Train_normalize)\r\nprint('x_test_normalize',x_Test_normalize)\r\n\r\n\r\nprint('train data',len(x_train_image))\r\nprint('test data',len(x_test_image))\r\nprint('x_train_image',x_train_image.shape)\r\nprint('x_test_image',x_test_image.shape)","sub_path":"mnist-test/show-imagelable.py","file_name":"show-imagelable.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"248541932","text":"# encoding: utf-8\n\nimport search\nimport XmindCopilot\nimport os\nfrom typing import Dict\nimport typing as typing\nimport sys\n\nimport glob\n\n\ndef WalkTopic(dictXmind: Dict, resultDict: Dict):\n strTitle: typing.AnyStr = dictXmind['title']\n if 'topics' in dictXmind:\n pass\n # print(dictXmind['topics'])\n\n listTopics : typing.List = dictXmind['topics']\n\n if(listTopics.__len__() > 0):\n resultDict[strTitle] = {}\n for topic in listTopics:\n WalkTopic(topic, resultDict[strTitle])\n else:\n resultDict[strTitle] = strTitle\n\ndef Print2MDList(dictOri: typing.Dict) -> typing.AnyStr:\n levelOri = 0\n listStr = []\n\n def Print2MDListInternal(dictContent: typing.Dict, level):\n if type(dictContent).__name__ != 'dict':\n return\n level = level + 1\n for topic, topicDict in dictContent.items():\n listStr.append(' ' * (level - 1))\n listStr.append('- ')\n if topic:\n listStr.append(topic.replace('\\n', '\\t'))\n else:\n listStr.append('*FIG*')\n listStr.append('\\n')\n Print2MDListInternal(topicDict, level)\n\n Print2MDListInternal(dictOri, levelOri)\n\n return ''.join(listStr)\n\ndef xmindfiles_cvt(paths):\n\n for path in paths:\n pathSource = path\n pathSource = pathSource.replace('\\\\', '/')\n # pathOutput = pathSource.split('/')[-1].split('.')[0] + '.xmind.md'\n #输出到原文件目录\n pathOutput = pathSource + '.md'\n strResult = ''\n\n # 有待更新链接算法!\n wikilinkpaths = glob.glob(os.path.dirname(pathSource).replace('\\\\', '/')+'/**/*.xmind',recursive=False)\n for file_path in wikilinkpaths:\n file_path = os.path.splitext(file_path)[0].replace('\\\\', '/')\n file_name = file_path.split('/')[-1]\n # print(file_name)\n strResult += '[['+file_name+'.xmind]]\\n'\n\n workbook = XmindCopilot.load(pathSource)\n sheets = workbook.getSheets()\n for sheet in sheets:\n dictSheet = sheet.getData()\n dictResult: Dict = {}\n WalkTopic(dictSheet['topic'], dictResult)\n\n strResult += Print2MDList(dictResult)\n\n with open(pathOutput, 'w', encoding='utf-8') as f:\n f.write(strResult)\n print('Successfully wrote result into file: ' + pathOutput)\n\ndef test():\n print('sys.argv: ', sys.argv, \"\\n\")\n\n pathSource = None\n pathOutput = None\n\n for i, val in enumerate(sys.argv):\n if(val == '-source'):\n pathSource = sys.argv[i + 1]\n if(val == '-output'):\n pathOutput = sys.argv[i + 1]\n\n pathSource = pathSource.replace('\\\\', '/')\n\n if pathOutput == None:\n # pathOutput = pathSource.split('/')[-1].split('.')[0] + '.xmind.md'\n #输出到原文件目录\n # pathOutput = pathSource.split('.xmind')[0] + '.xmind.md'\n pathOutput = pathSource + '.md'\n\n workbook = XmindCopilot.load(pathSource)\n sheet = workbook.getPrimarySheet()\n dictSheet = sheet.getData()\n dictResult: Dict = {}\n WalkTopic(dictSheet['topic'], dictResult)\n\n strResult = Print2MDList(dictResult)\n\n with open(pathOutput, 'w', encoding='utf-8') as f:\n f.write(strResult)\n print('Successfully wrote result into file: ' + pathOutput)\n\n # print(strResult)\n # print(dictSheet)\n\nif __name__ == \"__main__\":\n # test()\n paths = search.getXmindPath()\n\n # paths = glob.glob('../**/*.xmind',recursive=True)\n print(paths)\n xmindfiles_cvt(paths)\n\n","sub_path":"XmindCopilot/fmt_cvt/xmind2md.py","file_name":"xmind2md.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"20157071","text":"from __future__ import division\nimport time\nimport Adafruit_PCA9685\n\nservo_increment = 5\n\nclass RPiServo:\n def __init__(self, channel, minTicks, maxTicks, resetTicks, waitTime):\n self.channel = channel\n self.minTicks = minTicks\n self.maxTicks = maxTicks\n self.resetTicks = resetTicks\n self.waitTime = waitTime\n self.on = 0\n self.off = resetTicks - 50\n\n self.pwm = Adafruit_PCA9685.PCA9685()\n self.pwm.set_pwm_freq(60)\n\n def move_servo(self, off):\n if off < self.minTicks:\n self.off = self.minTicks\n elif off > self.maxTicks:\n self.off = self.maxTicks\n else:\n self.off = off\n self.pwm.set_pwm(self.channel, self.on, self.off)\n\n def get_position(self):\n return self.off\n\n def gentle_move(self, newPos):\n if newPos < self.minTicks:\n newPos = self.minTicks\n elif newPos > self.maxTicks:\n newPos = self.maxTicks\n\n if newPos < self.off:\n while(self.off > newPos):\n self.off -= servo_increment\n self.pwm.set_pwm(self.channel, self.on, self.off)\n time.sleep(self.waitTime)\n elif newPos > self.off:\n while(self.off < newPos):\n self.off += servo_increment\n self.pwm.set_pwm(self.channel, self.on, self.off)\n time.sleep(self.waitTime)\n\n def reset_servo(self):\n self.gentle_move(self.resetTicks)\n","sub_path":"movement/RPiServo.py","file_name":"RPiServo.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"628674011","text":"# CSE 512 Lab 4\n# This lab will be to solve the standard 8-puzzle. \n# Will need to represent of an 8-puzzle state. \n# Testing of whether a given puzzle state is in the goal state.\n# Test all possible successor states to the given puzzle state.\n# Evaluate the numeric \"goodness\" score for a given puzzle\nfrom random import randint\n\n#Blank space in the puzzle\nB = \"B\"\n\n# Dictionary of the form (row,col):\npuzzle = { (1,1):1, (1,2):2, (1,3):5, (2,1):7, (2,2):B, (2,3):6, (3,1):3, (3,2):4, (3,3):8 }\nd = dict(puzzle)\n\n# Global position names for easier readability.\nzero = puzzle[(1,1)]\none = puzzle[(1,2)]\ntwo = puzzle[(1,3)]\nthree = puzzle[(2,1)]\nfour = puzzle[(2,2)]\nfive = puzzle[(2,3)]\nsix = puzzle[(3,1)]\nseven = puzzle[(3,2)]\neight = puzzle[(3,3)]\n\n'''\nfor item in puzzle.keys():\n\tprint(item,puzzle[item])\n\tif (puzzle[item] == B):\n\t\tprint(\"Found a blank space.\")\n\t'''\n\n# Prints out the index positions of the game board.\ndef printExampleGameBoard():\n\tprint(\"Example game board:\")\n\tprint(\"*---------*\")\n\tprint(0,1,2)\n\tprint(3,4,5)\n\tprint(6,7,8)\n\tprint(\"*---------*\")\n\n# Prints out the current puzzle as is.\ndef printPuzzle():\n\tprint(\"\\n\")\n\tprint(\"Current game board:\")\n\tprint(\"*---------*\")\n\tprint(zero,one,two)\n\tprint(three,four,five)\n\tprint(six,seven,eight)\n\tprint(\"*---------*\")\n\tprint(\"\\n\")\n\n'''\nfor key,value in puzzle:\n\tprint(key,value)\n\n'''\n# Function to swap two places on the game board.\ndef swap(entry_A, entry_B):\n\tglobal puzzle\n\tprint(\"Swapping values\", entry_A, entry_B)\n\ttempA = entry_A\n\ttempB = entry_B\n\ttempA_key = \"\"\n\ttempB_key = \"\"\n\n\tfor item in puzzle.keys():\n\t\t#print(item,puzzle[item])\n\t\tif (puzzle[item] == tempA):\n\t\t\ttempA_key = item\n\t\tif (puzzle[item] == tempB):\n\t\t\ttempB_key = item\n\n\ttempA_value = puzzle[tempA_key]\n\tpuzzle[tempA_key] = puzzle[tempB_key]\n\tpuzzle[tempB_key] = tempA_value\n\n\n# Returns a list of puzzle positions that are not in the goal game state.\ndef evaluationFunction(mapValue):\n\teval = list()\n\n\tif (mapValue[(1,1)] != 1): \n\t\teval.append('zero')\n\n\tif (mapValue[(1,2)] != 2):\n\t\teval.append('one')\n\n\tif (mapValue[(1,3)] != 3):\n\t\teval.append('two')\n\n\tif (mapValue[(2,1)] != 4):\n\t\teval.append('three')\n\n\tif (mapValue[(2,2)] != 'B'):\n\t\teval.append('four')\n\n\tif (mapValue[(2,3)] != 5):\n\t\teval.append('five')\n\n\tif (mapValue[(3,1)] != 6):\n\t\teval.append('six')\n\n\tif (mapValue[(3,2)] != 7):\n\t\teval.append('seven')\n\n\tif (mapValue[(3,3)] != 8):\t\n\t\teval.append('eight')\n\n\treturn eval\n\n\n\t\n# Will allow moving of games pieces using the swap function after the evaluation function.\ndef Move(mapValue, start_position, end_position, possible_positions, open_positions):\n\t\n\n\t'''\n\tfor item in mapValue.keys():\n\t\t#print(item,puzzle[item])\n\t\tif (mapValue[item] == B):\n\t\t\tprint(\"Found a blank space.\")\n\t\t\tprint(item)\n\t'''\n\n\n\n\n# Checks for the hardcoded goal game state.\ndef testForGoalState(mapValue):\n\tif (mapValue[(1,1)] == 1 and mapValue[(1,2)] == 2 and mapValue[(1,3)] == 3/\n\t\tmapValue[(2,1)] == 4 and mapValue[(2,2)] == 'B' and mapValue[(2,3)] == 5/\n\t\tmapValue[(3,1)] == 6 and mapValue[(3,2)] == 7 and mapValue[(3,3)] == 8):\n\t\treturn True\n\telse:\n\t\treturn False\n\n# Identifies all possible moves on the game board from the perspectice of the blank space.\ndef possibleMoves(mapValue):\n\tnorthernMove = 0\n\tsouthernMove = 0\n\teasternMove = 0\n\twesternMove = 0\n\tpossibleMove = list()\n\n\tif (zero == \"B\"):\n\t\tsouthernMove = 1\n\t\teasternMove = 1\n\t\tprint(\"zero\")\n\telif (one == \"B\"):\n\t\tsouthernMove = 1\n\t\teasternMove = 1\n\t\twesternMove = 1\n\t\tprint(\"Current blank space: one\")\n\telif (two == \"B\"):\n\t\teasternMove = 1\n\t\tsouthernMove = 1\n\t\tprint(\"Current blank space: two\")\n\telif (three == \"B\"):\n\t\tnorthernMove = 1\n\t\teasternMove = 1\n\t\tsouthernMove = 1\n\t\tprint(\"Current blank space: three\")\n\telif (four == \"B\"):\n\t\teasternMove = 1\n\t\twesternMove = 1\n\t\tsouthernMove = 1\n\t\tnorthernMove = 1\n\t\tprint(\"Current blank space: four\")\n\telif (five == \"B\"):\n\t\twesternMove = 1\n\t\tnorthernMove = 1\n\t\tsouthernMove = 1\n\t\tprint(\"Current blank space: five\")\n\telif (six == \"B\"):\n\t\tnorthernMove = 1\n\t\teasternMove = 1\n\t\tprint(\"Current blank space: six\")\n\telif (seven == \"B\"):\n\t\teasternMove = 1\n\t\tnorthernMove = 1 \n\t\twesternMove = 1\n\t\tprint(\"Current blank space: seven\")\n\telif (eight == \"B\"):\n\t\tnorthernMove = 1\n\t\twesternMove = 1\n\t\tprint(\"Current blank space: eight\")\n\n\t\tpossibleMove.append(northernMove)\n\t\tpossibleMove.append(southernMove)\n\t\tpossibleMove.append(easternMove)\n\t\tpossibleMove.append(westernMove)\n\n\treturn(northernMove,southernMove,easternMove,westernMove)\n\n\ndef makeDecision(puzzle):\n\tTheMap = puzzle\n\t# Test for incorrect positions\n\tincorrectPositions = evaluationFunction(TheMap)\n\tprint(\"Incorrect Positions: \", incorrectPositions)\n\n\t# Possible places to move to\n\tdirections = possibleMoves(TheMap)\n\n\tprint(\"Can move to: (north,south,east,west): \", directions)\n\n\trandomMove = randint(1,4)\n\tprint(\"Random move: \", randomMove)\n\n\tif (incorrectPositions == 'two'):\n\t\tprint(\"two\")\n\t\tpass\n\n\n\n\ndef main():\n\n\tprintExampleGameBoard()\n\n\n\tfor _ in range(5):\n\t\tprintPuzzle()\n\n\t\t'''\n\t\t\n\t\tprint(\"Pieces not in the correct place: \")\n\t\tprint(\"Positions: \", evaluationFunction(puzzle))\n\t\tprint(\"\\n\")\n\n\t\tprint(\"Possible Moves: \")\n\t\tprint(\"Directions: \", possibleMoves(puzzle))\n\t\tprint(\"\\n\")\n\n\t\t'''\n\n\t\tif(testForGoalState(puzzle) == False):\n\t\t\tmakeDecision(puzzle)\n\t\t\tprint(\"Need to move\")\n\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"Lab4/graphsearch.py","file_name":"graphsearch.py","file_ext":"py","file_size_in_byte":5321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"410753968","text":"import asyncio\nfrom datetime import date, datetime, timedelta\nimport os\nimport random\nimport traceback\n\nimport psycopg2\nfrom psycopg2.extras import DictCursor\nfrom pytz import timezone\nimport redis\n\nimport discord # discord.pyをインポート\nfrom discord.ext import commands # Bot Commands Frameworkのインポート\n\n\ndsn = os.environ['DATABASE_URL']\n# dsn = \"postgres://discord:password@postgres:5432/discord\"\njst = timezone('Asia/Tokyo')\n\nversion=\"2.0.0\"\n\nclass Theme(commands.Cog):\n three_topics_table = {\n 'ジャンル': 'genres',\n 'トピック': 'topics',\n }\n\n drawing_table = {\n 'キャラクター': 'character',\n '種族': 'race',\n '性別': 'sex',\n '年齢': 'age',\n '髪型': 'hair_style',\n '髪色': 'hair_color',\n '瞳の色': 'eye_color',\n '体型': 'body',\n '性格': 'personality',\n '職業': 'job',\n '口癖': 'catch_phrase',\n '好きなもの': 'favorite',\n '嫌いなもの': 'dislike',\n '将来の夢': 'dream',\n '特技': 'skill',\n '服装': 'style',\n '特徴': 'characteristics',\n 'モチーフ': 'motif',\n 'ポーズ': 'pose',\n 'シチュエーション': 'situation',\n }\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def info(self, ctx):\n \"\"\"Show Bot informations.\"\"\"\n embed = discord.Embed(title=\"Botくん2号\", description='This is Botくん2号. This bot suggest a theme of creation.\\nSend \"&help\", you can show commands.', color=0x74e6bc)\n embed.add_field(name=\"Version\", value=version)\n # give info about you here\n embed.add_field(name=\"Author\", value=\"雅猫\")\n # Shows the number of servers the bot is member of.\n embed.add_field(name=\"Server count\", value=f\"{len(bot.guilds)}\")\n # give users a link to invite thsi bot to their server\n embed.add_field(name=\"Invite\", value=\"https://discordapp.com/api/oauth2/authorize?client_id=493926028620857364&permissions=27712&scope=bot\")\n await ctx.send(embed=embed)\n\n # 三題噺の関数\n def get_three_topics(self, message):\n command = message.content.split()\n user = command[1] if 1 < len(command) else None\n if user is not None:\n random.seed(date.today().strftime('%Y%m%d')+user)\n genre = random.sample(self.fetchall(self.__class__.three_topics_table['ジャンル']), 1)\n topics = random.sample(self.fetchall(self.__class__.three_topics_table['トピック']), 3)\n\n title = \"今日の{0}さんのお題\".format(user) if user is not None else \"お題\"\n description = \"今日の{0}さんのお題はこちら!\\n\".format(user) if user is not None else \"\"\n description += \"面白いお話期待してるよ!\"\n embed = discord.Embed(title=title, description=description, color=0x74e6bc)\n embed.add_field(name=\"ジャンル\", value=genre[0]['value'], inline=False)\n embed.add_field(name=\"1つ目のお題\", value=topics[0]['value'])\n embed.add_field(name=\"2つ目のお題\", value=topics[1]['value'])\n embed.add_field(name=\"3つ目のお題\", value=topics[2]['value'])\n return embed\n\n # お絵かきの関数\n def get_drawing(self, message):\n command = message.content.split()\n user = command[1] if 1 < len(command) else None\n if user is not None:\n random.seed(date.today().strftime('%Y%m%d')+user)\n \n title = \"今日の{0}さんのお題\".format(user) if user is not None else \"お題\"\n description = \"今日の{0}さんのお題はこちら!\\n\".format(user) if user is not None else \"\"\n description += \"素敵なイラストを楽しみにしてるよ!\"\n embed = discord.Embed(title=title, description=description, color=0x74e6bc)\n \n tables = {}\n drawing_table = self.__class__.drawing_table.copy()\n if (random.randrange(len(drawing_table)) == 0):\n tables['キャラクター'] = drawing_table['キャラクター']\n del drawing_table['種族']\n del drawing_table['性別']\n del drawing_table['髪色']\n del drawing_table['瞳の色']\n del drawing_table['性格']\n del drawing_table['口癖']\n del drawing_table['好きなもの']\n del drawing_table['嫌いなもの']\n del drawing_table['将来の夢']\n del drawing_table['キャラクター']\n \n PICKUP_NUM = 5\n tables.update({k:v for k, v in random.sample(drawing_table.items(), PICKUP_NUM-len(tables))})\n for name, table in tables.items():\n embed.add_field(name=name, value=random.choice(self.fetchall(table))['value'])\n return embed\n \n # 汎用関数\n def get_list(self, table, limit=0):\n values = self.fetchall(table)\n result = f\"```table: {table}\" + \"\"\"\nID VALUE\n————————————————————————————————————————————\n\"\"\"\n for i, value in enumerate(values[-limit:]):\n result += str(i).ljust(8) + value['value'] + '\\n'\n result += \"```\"\n return result\n\n def show_values(self, table, message):\n command = message.content.split()\n limit = int(command[1]) if 1 < len(command) else 0\n return self.get_list(table, limit)\n\n def add_record(self, table, values):\n result = []\n with psycopg2.connect(dsn) as conn:\n with conn.cursor() as cur:\n # テーブルが存在するかチェック\n cur.execute(\"SELECT * FROM pg_tables where tablename='{0}'\".format(table))\n if cur.fetchone() is None:\n cur.execute(\"create table {0} (id serial, value varchar(50) unique)\".format(table))\n conn.commit()\n result.append(\"create table '{0}'.\".format(table))\n for value in values:\n # レコードが存在するかチェックして追加\n cur.execute(\"SELECT * FROM {0} WHERE value = '{1}'\".format(table, value))\n if cur.fetchone() is None:\n cur.execute(\"INSERT INTO {0} (value) VALUES ('{1}')\".format(table, value))\n conn.commit()\n result.append(\"add value '{1}' to '{0}'.\".format(table, value))\n else:\n result.append(\"value '{1}' is already exist in '{0}'.\".format(table, value))\n\n return '```'+\"\\n\".join(result)+'```'\n\n def del_record(self, table, values):\n result = []\n with psycopg2.connect(dsn) as conn:\n with conn.cursor() as cur:\n # テーブルが存在するかチェック\n cur.execute(\"SELECT * FROM pg_tables where tablename='{0}'\".format(table))\n if cur.fetchone() is None:\n result.append(\"table '{0}' is not exist.\".format(table))\n return '```'+\"\\n\".join(result)+'```'\n for value in values:\n # レコードが存在するかチェックして追加\n cur.execute(\"SELECT * FROM {0} WHERE value = '{1}'\".format(table, value))\n if cur.fetchone() is None:\n result.append(\"value '{1}' is not exist in '{0}'.\".format(table, value))\n else:\n cur.execute(\"DELETE FROM {0} WHERE value = '{1}'\".format(table, value))\n conn.commit()\n result.append(\"delete value '{1}' from '{0}'.\".format(table, value))\n\n return '```'+\"\\n\".join(result)+'```'\n \n def fetchall(self, table):\n with psycopg2.connect(dsn) as conn:\n with conn.cursor(cursor_factory=DictCursor) as cur:\n cur.execute('SELECT * FROM {0}'.format(table))\n return cur.fetchall()\n\n @commands.Cog.listener()\n async def on_guild_join(self, guild):\n await guild.system_channel.send('初めましてBotくん2号だよ\\nヘルプを見る場合は*「@Botくん2号 ヘルプ」*って書き込んでね!\\n**コマンドを使用するときは一時チャットかDMを使いましょう**')\n\n\n def add_help_three_topics(self, embed):\n embed.add_field(name=\"@Botくん2号 三題噺\",\n value=\"*「@Botくん2号 三題噺 お題」*であなたの今日のお題を出すよ!\\n \\\n *「@Botくん2号 三題噺 ジャンル」*で登録されてる**ジャンル**を確認できるよ!\\n \\\n *「@Botくん2号 三題噺 ジャンル 追加」*の後に「 」半角スペース区切りでジャンルを書き込むとジャンルを登録できるよ!\\n \\\n *「@Botくん2号 三題噺 ジャンル 削除」*の後に「 」半角スペース区切りでジャンルを書き込むと指定したジャンルを消せるよ!\\n \\\n 例えば、*「@Botくん2号 三題噺 ジャンル 追加 シリアス ほのぼの」*みたいな感じだよ!\\n \\\n 「ジャンル」を「トピック」に変えて書き込むと三題噺のお題である**トピック**について扱うことができるよ!\\n\\n \\\n いろんな言葉を追加していってね!\",\n inline=False)\n\n def add_help_drawing(self, embed):\n embed.add_field(name=\"@Botくん2号 お絵かき\",\n value=\"*「@Botくん2号 お絵かき お題」*であなたの今日のお題を出すよ!\\n \\\n お絵かきのお題ではキャラクターの設定の中から5つの設定をお題として出すよ!\\n \\\n *「@Botくん2号 お絵かき [設定]」*で登録されてるキャラクターの設定を確認できるよ!\\n \\\n 設定の種類は下の方に書いてあるからそれを参考に[設定]の部分を置き換えてね\\n \\\n *「@Botくん2号 お絵かき [設定] 追加」*の後に「 」半角スペース区切りで設定を書き込むと設定を登録できるよ!\\n \\\n *「@Botくん2号 お絵かき [設定] 削除」*の後に「 」半角スペース区切りで設定を書き込むと指定した設定を消せるよ!\\n \\\n 例えば、*「@Botくん2号 お絵かき 特徴 追加 狐耳 エルフ耳」*みたいな感じだよ!\\n\\n \\\n いろんな設定を追加していってね!\",\n inline=False)\n self.add_help_tables(embed)\n\n def add_help_tables(self, embed):\n embed.add_field(name=\"お絵かき 設定項目一覧\",\n value=\"、\".join(self.__class__.drawing_table.keys()),\n inline=False)\n\n @commands.command(name=\"ヘルプ\")\n async def help_mention(self, ctx):\n embed = discord.Embed(title=\"Botくん2号\", description='Bot2号くんです!(1号も一応いる)\\n話しかけると創作のためのお題を出すよ!\\n**コマンドを使用するときは一時チャットかDMを使いましょう!**', color=0x74e6bc)\n embed.add_field(name=\"コマンドの紹介\",\n value=\"コマンドをいくつか紹介するよ!\\nまずメンション*「@Botくん2号」*で話しかけよう!\\n\\n\",\n inline=False)\n embed.add_field(name=\"ヘルプ\", value=\"*「@Botくん2号 ヘルプ」*って書き込むと、このヘルプが見られるよ!\", inline=False)\n embed.add_field(name=\"三題噺\", value=\"三題噺関連は*「@Botくん2号 三題噺」*から始まるよ!\", inline=False)\n embed.add_field(name=\"お絵かき\", value=\"お絵かき関連は*「@Botくん2号 お絵かき」*から始まるよ!\", inline=False)\n self.add_help_three_topics(embed)\n self.add_help_drawing(embed)\n embed.add_field(name=\"Version\", value=version)\n # give info about you here\n embed.add_field(name=\"Author\", value=\"雅猫\")\n # Shows the number of servers the bot is member of.\n embed.add_field(name=\"Server count\", value=f\"{len(self.bot.guilds)}\")\n # give users a link to invite thsi bot to their server\n embed.add_field(name=\"Invite\", value=\"https://discordapp.com/api/oauth2/authorize?client_id=493926028620857364&permissions=27712&scope=bot\")\n await ctx.message.channel.send(embed=embed)\n\n async def manage_table(self, message, commands, table):\n if not 2 < len(commands):\n await message.channel.send(self.get_list(table))\n elif commands[2] == \"追加\":\n await message.channel.send(self.add_record(table, commands[3:]))\n elif commands[2] == \"削除\":\n await message.channel.send(self.del_record(table, commands[3:]))\n\n # サブコマンド内容\n @commands.command(name=\"三題噺\")\n async def mention_three_topics(self, ctx):\n message = ctx.message\n arg = message.content.split()\n commands = arg[1:]\n\n if commands[1] == \"お題\":\n message.content = f'three_topics {message.author.name}'\n await message.channel.send(f'{message.author.mention}', embed=self.get_three_topics(message))\n elif commands[1] == \"ヘルプ\":\n embed = discord.Embed(title=\"コマンドの使い方、三題噺編!\", description='三題噺のお題に関するコマンドの使い方について説明するよ!', color=0x74e6bc)\n self.add_help_three_topics(embed)\n await message.channel.send(embed=embed)\n for key, table in self.__class__.three_topics_table.items():\n if commands[1] == key:\n await self.manage_table(message, commands, table)\n\n @commands.command(name=\"お絵かき\")\n async def mention_drawing(self, ctx):\n message = ctx.message\n arg = message.content.split()\n commands = arg[1:]\n \n if commands[1] == \"お題\":\n message.content = f'drawing {message.author.name}'\n await message.channel.send(f'{message.author.mention}', embed=self.get_drawing(message))\n elif commands[1] == \"ヘルプ\":\n embed = discord.Embed(title=\"コマンドの使い方、お絵かき編!\", description='お絵かきのお題に関するコマンドの使い方について説明するよ!', color=0x74e6bc)\n self.add_help_drawing(embed)\n await message.channel.send(embed=embed)\n elif commands[1] == \"設定項目\":\n embed = discord.Embed(title=\"コマンドの使い方、お絵かきの設定項目\", description='お絵かきの設定項目はこちら!', color=0x74e6bc)\n self.add_help_tables(embed)\n await message.channel.send(embed=embed)\n for key, table in self.__class__.drawing_table.items():\n if commands[1] == key:\n await self.manage_table(message, commands, table)\n\n\n# Bot本体側からコグを読み込む際に呼び出される関数。\ndef setup(bot):\n bot.add_cog(Theme(bot))","sub_path":"bot2/cogs/theme.py","file_name":"theme.py","file_ext":"py","file_size_in_byte":15402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"233101531","text":"def _number_format(tensor):\n min_sz = 2\n tensor = torch.DoubleTensor(tensor.nelement()).copy_(tensor).abs_()\n pos_inf_mask = tensor.eq(float('inf'))\n neg_inf_mask = tensor.eq(float('-inf'))\n nan_mask = tensor.ne(tensor)\n invalid_value_mask = ((pos_inf_mask + neg_inf_mask) + nan_mask)\n if invalid_value_mask.all():\n tensor = torch.zeros(1)\n example_value = tensor[invalid_value_mask.eq(0)][0]\n tensor[invalid_value_mask] = example_value\n if invalid_value_mask.any():\n min_sz = 3\n int_mode = True\n for value in tensor:\n if (value != math.ceil(value)):\n int_mode = False\n break\n exp_min = tensor.min()\n if (exp_min != 0):\n exp_min = (math.floor(math.log10(exp_min)) + 1)\n else:\n exp_min = 1\n exp_max = tensor.max()\n if (exp_max != 0):\n exp_max = (math.floor(math.log10(exp_max)) + 1)\n else:\n exp_max = 1\n scale = 1\n exp_max = int(exp_max)\n if int_mode:\n if (exp_max > 9):\n format = '{:11.4e}'\n sz = max(min_sz, 11)\n else:\n sz = max(min_sz, (exp_max + 1))\n format = (('{:' + str(sz)) + '.0f}')\n elif ((exp_max - exp_min) > 4):\n sz = 11\n if ((abs(exp_max) > 99) or (abs(exp_min) > 99)):\n sz = (sz + 1)\n sz = max(min_sz, sz)\n format = (('{:' + str(sz)) + '.4e}')\n else:\n if ((exp_max > 5) or (exp_max < 0)):\n sz = max(min_sz, 7)\n scale = math.pow(10, (exp_max - 1))\n else:\n if (exp_max == 0):\n sz = 7\n else:\n sz = (exp_max + 6)\n sz = max(min_sz, sz)\n format = (('{:' + str(sz)) + '.4f}')\n return (format, scale, sz)","sub_path":"Data Set/bug-fixing-5/deebc1383e5429be506caa17b61cb6c72e6ed815-<_number_format>-fix.py","file_name":"deebc1383e5429be506caa17b61cb6c72e6ed815-<_number_format>-fix.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"125814979","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/8/19 13:37\n# @File : p9_event.py\n\n# 事件:定义一个flag,set设置flag为True,clear设置flag为False\nimport threading\n\n\ndef func(e, i):\n print(i)\n e.wait() # 检查当前event是什么状态,如果是红灯,则阻塞,如果是绿灯则继续往下执行。默认是红灯\n print(i + 100)\n\n\nevent = threading.Event()\nfor i in range(10):\n t = threading.Thread(target=func, args=(event, i))\n t.start()\n\nevent.clear() # 主动将状态设置为红灯\ninp = input(\">>>\")\nif inp == \"1\":\n event.set() # 主动将状态设置为绿灯\n\n# 练习:使用redis实现分布式锁\n","sub_path":"thirdWeek/threading/p9_event.py","file_name":"p9_event.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"} +{"seq_id":"610585197","text":"people = {\n 'person1': {\n 'name': 'Sally Sue',\n 'city': 'Phoenix'\n },\n 'person2': {\n 'name': 'Billy Bob',\n 'city': 'Scottsdale'\n },\n 'person3': {\n 'name': 'Rover',\n 'city': 'Zappa'\n }\n}\ngreetings = []\nfor person in people.values():\n greeting = \"Hello \" + person['name'] + \" from \" + person['city']\n greetings.append(greeting)","sub_path":"dictionaries.py","file_name":"dictionaries.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"60"}