diff --git "a/5333.jsonl" "b/5333.jsonl" new file mode 100644--- /dev/null +++ "b/5333.jsonl" @@ -0,0 +1,741 @@ +{"seq_id":"492263971","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 28 14:15:09 2020\n\n@author: Ron\n\"\"\"\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nimport time\n\n\ndriver = None\n\nytlink=\"https://www.youtube.com/watch?v=rfscVS0vtbw\"\n\ntry:\n cpath = 'chromedriver.exe'\n driver = webdriver.Chrome(cpath)\n driver.get(ytlink)\n # how do we fix this next statement?\n time.sleep(5)\n cs_selector = \"#count > yt-view-count-renderer > span.view-count.style-scope.yt-view-count-renderer\"\n e = driver.find_element(By.CSS_SELECTOR,cs_selector)\n time.sleep(3)\n txt_views = print(e.text)\n\nfinally:\n if driver is not None:\n driver.quit()","sub_path":"getYoutube.py","file_name":"getYoutube.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"310913224","text":"\"\"\"Implement opinionated Py<->R conversion functions.\"\"\"\n\nimport datetime\n\nimport numpy as np\nimport pandas as pd\n\nfrom loguru import logger\n\nimport rpy2.rinterface as ri\nfrom rpy2.rinterface import RTYPES\n\nimport rpy2.robjects as ro\nfrom rpy2.robjects import numpy2ri, pandas2ri\n\nfrom rpy2.robjects.conversion import (\n converter as template_converter,\n Converter)\n\n\n# setup converter\ntemplate_converter += numpy2ri.converter\ntemplate_converter += pandas2ri.converter\nconverter = Converter('r_wrapper', template=template_converter)\n\n\n@converter.py2rpy.register(list)\ndef _(obj):\n logger.debug('py2rpy: list -> Vector')\n logger.trace(f' object: {obj}')\n\n if len({type(e) for e in obj}) == 1:\n # has no mixed types\n\n vector_type_map = {\n float: ro.FloatVector,\n int: ro.IntVector,\n bool: ro.BoolVector,\n str: ro.StrVector\n }\n\n for type_, VectorClass in vector_type_map.items():\n if isinstance(obj[0], type_):\n logger.trace(f'Detected: {type_}')\n return VectorClass([converter.py2rpy(x) for x in obj])\n\n # no fitting type found, let R decide\n logger.warning('Using slow string conversion')\n return ro.r('c('+','.join([converter.py2rpy(x).r_repr() for x in obj])+')')\n\n\n@converter.py2rpy.register(dict)\ndef _(obj):\n logger.debug('py2rpy: dict -> ro.ListVector')\n logger.trace(f' object: {obj}')\n logger.trace(f' member types: {[type(o) for o in obj.values()]}')\n\n return ro.vectors.ListVector(\n {k: converter.py2rpy(v) for k, v in obj.items()})\n\n\n@converter.py2rpy.register(datetime.datetime)\ndef _(obj):\n logger.debug('py2rpy: datetime.datetime -> lubridate::Date')\n logger.trace(f' object: {obj}')\n\n return ro.r(f'lubridate::make_date(year={obj.year}, month={obj.month}, day={obj.day})')\n\n\n@converter.rpy2py.register(ro.vectors.ListVector)\ndef _(obj):\n logger.debug('rpy2py: ro.ListVector -> dict/list')\n logger.trace(f' object: {obj}')\n\n keys = obj.names\n values = [converter.rpy2py(x) for x in obj]\n\n if isinstance(keys, np.ndarray) or keys.typeof != RTYPES.NILSXP:\n return dict(zip(keys, values))\n else:\n return values\n\n\n@converter.rpy2py.register(ri.FloatSexpVector)\ndef rpy2py_sexp(obj):\n \"\"\"Convert named arrays while keeping the names.\n\n This function is adapted from 'rpy2/robjects/numpy2ri.py'.\n \"\"\"\n logger.debug('rpy2py: ri.FloatSexpVector -> np.array/pd.Series')\n logger.trace(f' object: {obj}')\n\n if 'Date' in obj.rclass:\n days2date = lambda days_since_epoch: \\\n datetime.datetime.fromtimestamp(days_since_epoch * 24 * 60 * 60).replace(hour=0, minute=0, second=0)\n dates = [days2date(days_since_epoch) for days_since_epoch in obj]\n\n res = dates\n else:\n # TODO: implement this for other SexpVector types\n _vectortypes = (RTYPES.LGLSXP,\n RTYPES.INTSXP,\n RTYPES.REALSXP,\n RTYPES.CPLXSXP,\n RTYPES.STRSXP)\n\n if (obj.typeof in _vectortypes) and (obj.typeof != RTYPES.VECSXP):\n if obj.names.typeof == RTYPES.NILSXP:\n # no names associated\n res = np.array(obj)\n else:\n res = pd.Series(obj, index=obj.names)\n else:\n res = ro.default_converter.rpy2py(obj)\n\n return res if len(res) > 1 else res[0]\n","sub_path":"r_wrapper/converter.py","file_name":"converter.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364185903","text":"#dictionary to store values of occupied tiles on the game board\ntiles = {}\n\n#helper functions\ndef validateInput(ui):\n\t\"\"\"Checks whether the input is in range 1-9 and the tile is not \n\talready taken by another symbol.\n\tReturns True if input is valid, otherwise returns False and an\n\terror message.\"\"\"\n\ttry:\n\t\tif int(ui) < 1 or int(ui) > 9:\n\t\t\treturn False, \"You can only use numbers 1-9.\"\n\t\telif tuplifyInput(int(ui)) in tiles.keys():\n\t\t\treturn False, \"Tile no. %s is already occupied.\" % ui\n\t\telse:\n\t\t\treturn True, \"Input OK\"\n\texcept ValueError:\n\t\treturn False, \"Could not parse input. Use only numerical characters.\"\n\t\t\ndef printBoard():\n\t\"\"\"Prints the game board using a dictionary that stores values\n\tof occupied tiles (either O or X shape). If there is no value for a given\n\ttile in the dictionary, an empty tile is printed.\"\"\"\n\tprint()\n\tfor i in range(1,4):\n\t\tcount = {}\n\t\tprint(\"#\" * 19)\n\t\tfor j in range(1,4):\n\t\t\tif (i,j) in tiles.keys():\n\t\t\t\tcount[(i,j)] = 1\n\t\tfor k in range(1,4):\n\t\t\tfor l in range(1,4):\n\t\t\t\tif count.get((i,l)) is not None:\n\t\t\t\t\tif count[(i,l)] == 1 or count[(i,l)] == 3:\n\t\t\t\t\t\tif tiles[(i,l)] == \"X\":\n\t\t\t\t\t\t\tprint(\"# X X \", end=\"\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"# O \", end=\"\")\n\t\t\t\t\telif count[(i,l)] == 2:\n\t\t\t\t\t\tif tiles[(i,l)] == \"X\":\n\t\t\t\t\t\t\tprint(\"# X \", end=\"\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"# O O \", end=\"\")\n\t\t\t\t\tcount[(i,l)] += 1\n\t\t\t\telse:\n\t\t\t\t\tprint(\"# \", end=\"\")\n\t\t\t\tif l == 3:\n\t\t\t\t\tprint(\"#\")\n\tprint(\"#\" * 19)\n\tprint()\n\t\t\n#UNUSED FUNCTION\ndef printBoardBasic():\n\t\"\"\"Simple version of the printBoard() function which doesn't draw \n\tshapes but only single X or O characters.\"\"\"\n\tprint()\n\tfor i in range(1,4):\n\t\tprint(\"#\" * 13)\n\t\tprint(\"# \" * 3, end=\"#\\n\")\n\t\tfor j in range(1,4):\n\t\t\tif (i,j) in tiles.keys():\n\t\t\t\tprint(\"# %s \" % tiles[(i,j)], end=\"\")\n\t\t\telse:\n\t\t\t\tprint(\"# \", end=\"\")\n\t\tprint(\"#\")\n\t\tprint(\"# \" * 3, end=\"#\\n\")\n\tprint(\"#\" * 13)\n\tprint()\n\t\ndef tuplifyInput(ui):\n\t\"\"\"Converts user input into a tuple of (row, column).\"\"\"\n\tif ui < 4:\n\t\treturn (1, ui)\n\telif ui < 7:\n\t\treturn (2, ui - 3)\n\telse:\n\t\treturn (3, ui - 6)\n\ndef checkForWin():\n\t\"\"\"Checks whether or not the board has entered a win state.\"\"\"\n\tgameOver = False\n\tmsg = \"The game continues.\"\n\t\n\t#tie check\n\tmovesLeft = False\n\tfor i in range(10):\n\t\tif validateInput(i)[0]:\n\t\t\tmovesLeft = True\n\t\t\tbreak\n\tif not movesLeft:\n\t\tgameOver, msg = True, \"It's a tie!\"\n\t\n\t#win check\n\tfor i in range(1,4):\n\t\tif tiles.get((i,1)) == tiles.get((i,2)) == tiles.get((i,3)) and tiles.get((i,1)) is not None:\n\t\t\tgameOver, msg = True, \"You win!\"\n\t\telif tiles.get((1,i)) == tiles.get((2,i)) == tiles.get((3,i)) and tiles.get((1,i)) is not None:\n\t\t\tgameOver, msg = True, \"You win!\"\n\tif tiles.get((1,1)) == tiles.get((2,2)) == tiles.get((3,3)) and tiles.get((1,1)) is not None:\n\t\tgameOver, msg = True, \"You win!\"\n\telif tiles.get((1,3)) == tiles.get((2,2)) == tiles.get((3,1)) and tiles.get((1,3)) is not None:\n\t\tgameOver, msg = True, \"You win!\"\n\t\t\n\treturn gameOver, msg\n\ndef reset():\n\ttiles.clear()\n\tprintBoard()\n\tisPlayerOne = True\n\n#main program loop\nprint(\"Welcome to A Boring Game of Tic Tac Toe!\")\nprint(\"The game is designed for two players.\")\nprint(\"Type a number from 1 to 9 to select the square you want to mark,\\n\" + \\\n \"1 being the top left and 9 the bottom right corner.\")\nprint(\"(Type q to quit.)\")\nisPlayerOne = True\nprintBoard()\n\nwhile True:\n\t#get user input\n\tuserInput = input(\"Type your move: \")\n\t\n\tif userInput.lower() == \"q\":\n\t\tbreak\n\t\t\n\tsuccess, message = validateInput(userInput)\n\tif not success:\n\t\tprint(message)\n\t\tcontinue\n\t\n\t#input OK, time to update and print the board\n\tformattedInput = tuplifyInput(int(userInput))\n\ttiles[formattedInput] = \"O\" if isPlayerOne else \"X\"\n\tprintBoard()\n\t\t\n\t#announce win or tie and ask if the player wants to go again\t\n\tstatus, msg = checkForWin()\n\tif status:\n\t\tprint(msg)\n\t\tprint()\n\t\tnewGame = input(\"Play again? (y/n) \")\n\t\t\n\t\t#reset everything to default and start a new game if yes\n\t\tif newGame.lower() == \"y\":\n\t\t\treset()\n\t\t\tcontinue\n\t\telse:\n\t\t\tbreak\n\t\n\t#switch turns\t\n\tisPlayerOne = not isPlayerOne\n\t\nprint(\"Thanks for playing!\")\n","sub_path":"ticTacToeMP.py","file_name":"ticTacToeMP.py","file_ext":"py","file_size_in_byte":4075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"647643850","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nimport statistics\nfrom scipy import linalg as LA\nfrom operator import xor\n\ndef PCA(data,k):\n\tmean_vec = np.mean(data, axis=0)\n\t# X_std=X_std- mean_vec\n\tm, n = data.shape\n\t# cov_mat = (X_std - mean_vec).T.dot((X_std - mean_vec)) / (X_std.shape[0]-1)\n\tdata=data- mean_vec\n\tR = np.cov(data, rowvar=False)\n\tevals, evecs = LA.eigh(R)\n\tidx = np.argsort(evals)[::-1]\n\tevecs = evecs[:,idx]\n\tevals = evals[idx]\n\tevecs = evecs[:, :k]\n\tY=np.dot(evecs.T, data.T).T\n\t# u,s,v = np.linalg.svd(X_std.T)\n\t# Y=X_std.dot(u[:,0:k])\n\treturn Y\n\nl25=[]\nfor a in range(1,16):\n\tfname1='k/k.jpg'\n\tfname2='k/k%s.jpeg'%(a)\n\n\timg1_ = cv2.imread(fname1,0) # queryImage\n\timg2 = cv2.imread(fname2,0) # trainImage\n\ts = 150.0 / img1_.shape[1]\n\tdim = (150, int(img1_.shape[0] * s))\n\n\t# perform the actual resizing of the image and show it\n\timg1 = cv2.resize(img1_, dim, interpolation = cv2.INTER_AREA)\n\t# Initiate SIFT detector\n\tsift = cv2.xfeatures2d.SURF_create()\n\t# sift = cv2.SURF()\n\n\tkp1_, des1_= sift.detectAndCompute(img1,None)\n\tkp2_, des2_ = sift.detectAndCompute(img2,None)\n\tc=(len(kp1_))\n\tr=int(c/1)\n\tc1=(len(kp2_))\n\tr1=int(c1/1)\n\tlen1=50\n\tlen2=100\n\tkp1, des1=kp1_[0:len1],des1_[0:len1,0:50] \n\tkp2, des2=kp2_[0:len2],des2_[0:len2,0:50]\n\tdes11=des1\n\tdes22=des2\n\n\tfor l in range(len(des1)):\n\t\tmed=np.median(des1[l])\n\t\tfor v in range(50):\n\t\t\tif des1[l][v]>med:\n\t\t\t\tdes11[l][v]=1\n\t\t\telse:\n\t\t\t\tdes11[l][v]=0\n\tfor l in range(len(des2)):\n\t\tmed=np.median(des2[l])\n\t\tfor v in range(50):\n\t\t\tif des2[l][v]>med:\n\t\t\t\tdes22[l][v]=1\n\t\t\telse:\n\t\t\t\tdes22[l][v]=0\n\t\t\t\tres=[]\n\t\t\t\tele=[]\n\tdes11_=des11.astype(int)\n\tdes22_=des22.astype(int)\n\t# print(des111)\n\tfor u in range(len(des11_)):\n\t\tinx=0\n\t\tscore=0\n\t\tx=np.bitwise_xor(des11_[u],des22_)\n\t\tc=[[50-sum(x[i])] for i in range(len(x))]\n\t\tscore=np.amax(c)\n\t\tinx=np.argmax(c)\n\t\tele=[u, inx, score]\n\t\tres.append(ele)\n\tres=np.array(res)\n\tprint(res)\t\n\n\n\t# des1=PCA(des1,64)\n\t# des2=PCA(des2,64)\n\tbf = cv2.BFMatcher()\n\t# matches = bf.knnMatch(des1,des2,k=2)\n\tmatches = bf.knnMatch(np.asarray(des11,np.float32),np.asarray(des22,np.float32), k=2)\n\n\t# Apply ratio test\n\tgood = []\n\tcount=1\n\tratios=[]\n\tfor m,n in matches:\n\t if m.distance < 0.75*n.distance:\n\t good.append([m])\n\t # print(m.distance)\n\t ratios.append(m.distance/n.distance)\n\t # print(m.queryIdx,m.trainIdx)\n\t # z=m.queryIdx\n\t # x=m.trainIdx\n\t # plt.plot(des11[z],'-b')\n\t # plt.title('(%d)Query Image Descriptor(Idx=%d),Response=%f'%(count,z,kp1[z].response))\n\t # plt.xlabel('Descriptor Array index')\n\t # plt.ylabel('Value')\n\t # # add='plot/des1_%s_%d'%(z,count)\n\t # add='Plot_bit_value/k/%s.jpg'%(count)\n\t # plt.savefig(add)\n\t # plt.clf()\n\t # plt.plot(des22[x],'-b')\n\t # plt.title('(%d)Train Image Descriptor(Idx=%d),Response=%f'%(count,x,kp2[x].response))\n\t # plt.xlabel('Descriptor Array index')\n\t # plt.ylabel('Value')\n\t # # add1='plot/des2_%s_%d'%(x,count)\n\t # add1='Plot_bit_value/k/%s_.jpg'%(count)\n\t # plt.savefig(add1)\n\t # plt.clf()\n\t # # idx[count]=1\n\t # count=count+1\n\t # # print (count)\n\t \t\n\tl25.append(len(good))\n\n\t# cv2.drawMatchesKnn expects list of lists as matches.\n\n\timg3 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,img2,flags=2)\n\t# gres=[]\n\t# for i in range(10):\n\t# \tgres[i]=kp2[i].response\n\n\t# print(fname1,' ',fname2)\n\t# print(\"no of kp1 are :\",len(kp1))\n\t# print(\"no of kp2 are :\",len(kp2))\n\t# print(\"no of goods are :\",len(good))\n\t# print(\"point\t\t \t\t\t\t\t\t\t\t\t\t size \t \t\t\t response \t\t\t\t class_id \t\t\t\t angle \")\n\t# # for i in range(len(kp2)):\n\t# \tprint( kp2[i].pt,'\t\t\t' , kp2[i].size,'\t\t\t', kp2[i].response, '\t\t\t', kp2[i].class_id,'\t\t\t', kp2[i].angle )\n\t# print(len(good))\n\t\t# print(des1_[])\n\t# print(des1[1][1])\n\n\t# for m in good[]:\n\t# \tprint(m)\n\t#plt.imshow(img3),plt.show()\n\t# l1=len(good)\n\t# l=int(l1/r)\n\t# path='result_k/25_full/false_k%s_25_full_%s.jpg'%(a,l1)\n\t# cv2.imwrite(path,img3)\n\t# print(\"length of kp1=40,dim is 15:50\",\"mean=\",statistics.mean(l25),\"max=\",max(l25),\"min=\",min(l25),\"variance=\",statistics.variance(l25))","sub_path":"matcher_surf.py","file_name":"matcher_surf.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482041643","text":"#!/usr/bin/env python3\n\nimport tweepy\nimport time\nimport sys\nfrom pyfastogt import utils\nfrom random import randint\n\nfrom keys import keys # keep keys in separate file, keys.py\n\nCONSUMER_KEY = keys['consumer_key']\nCONSUMER_SECRET = keys['consumer_secret']\nACCESS_TOKEN = keys['access_token']\nACCESS_TOKEN_SECRET = keys['access_token_secret']\n\n\ndef print_usage():\n print(\"Usage:\\n\"\n \"[required] argv[1] input file path\\n\")\n\n\nif __name__ == \"__main__\":\n argc = len(sys.argv)\n\n if argc <= 1:\n print_usage()\n sys.exit(1)\n\n input_file = sys.argv[1]\n\n auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\n auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\n api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)\n me = api.me()\n friends_ids = sorted(api.friends_ids())\n\n user_count = 0\n error_count = 0\n followed_count = 0\n\n all_ids = utils.read_file_line_by_line_to_list(input_file)\n\n for i in range(len(all_ids)):\n user_id = all_ids[i]\n # u = api.get_user(user_id)\n uid = int(user_id)\n if utils.binary_search_number(uid, friends_ids):\n print(\"@{0} already follow to id: {1}\".format(me.name, uid))\n followed_count += 1\n continue\n\n try:\n print(\"try to follow id: {0}\".format(uid))\n api.create_friendship(id=uid)\n user_count += 1\n except tweepy.TweepError as e:\n error_count += 1\n print(\"error when api.create_friendship({0}), error: {1}\".format(uid, e))\n if e.api_code == 161:\n restore_file = input_file + '.restore'\n with open(restore_file, 'w') as outfile:\n for rid in all_ids[i:]:\n line = \"{0}\\n\".format(rid)\n outfile.write(line)\n break\n\n sleep_time = randint(3, 5)\n time.sleep(sleep_time)\n\n print(\"followed_count: {0}, user_count: {1}, error_count: {2}\".format(followed_count, user_count, error_count))\n","sub_path":"twitter/follow.py","file_name":"follow.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"4625728","text":"import re\nimport time\nimport json\nimport boto3\nimport numpy as np\nfrom pprint import pprint\nfrom argparse import ArgumentParser\nfrom datetime import datetime, timedelta\n\nlog_client = boto3.client('logs')\ncloudwatch = boto3.resource('cloudwatch')\n\n\ndef get_log_streams(lambda_id):\n group = '/aws/lambda/beldi-dev-{}'.format(lambda_id)\n r = log_client.describe_log_streams(logGroupName=group)\n r = r['logStreams']\n r = [x['logStreamName'] for x in r]\n return r\n\n\ndef delete_logs(lambda_id):\n group = '/aws/lambda/beldi-dev-{}'.format(lambda_id)\n try:\n log_client.delete_log_group(logGroupName=group)\n except:\n pass\n\n\ndef get_logs(lambda_id):\n group = '/aws/lambda/beldi-dev-{}'.format(lambda_id)\n streams = get_log_streams(lambda_id)\n res = []\n for stream in streams:\n r = log_client.get_log_events(logGroupName=group,\n logStreamName=stream)\n r = [e['message'].strip() for e in r['events']]\n res += r\n return res\n\n\ndef main():\n parser = ArgumentParser()\n parser.add_argument(\"--command\", required=True)\n parser.add_argument(\"--config\", required=False)\n parser.add_argument(\"--duration\", required=False)\n args = parser.parse_args()\n if args.command == 'clean':\n delete_logs(\"gctest\")\n return\n if args.command == 'run':\n end_time = datetime.utcnow()\n time.sleep(1 * 60) # Wait until metric generated\n metric = cloudwatch.Metric('AWS/Lambda', 'Duration')\n if args.config == 'baseline':\n tname = 'bgateway'\n else:\n tname = 'gateway'\n duration = int(args.duration)\n response = metric.get_statistics(\n Dimensions=[\n {\n 'Name': 'FunctionName',\n 'Value': 'beldi-dev-{}'.format(tname)\n }\n ],\n ExtendedStatistics=['p50', 'p99'],\n StartTime=end_time - timedelta(minutes=duration + 1),\n EndTime=end_time + timedelta(minutes=1),\n Period=60,\n Unit='Milliseconds'\n )\n points = response['Datapoints']\n points.sort(key=lambda x: x['Timestamp'])\n res = []\n for point in points:\n point = point['ExtendedStatistics']\n res.append([point['p50'], point['p99']])\n res = res[1:-1]\n with open('result/hotel/{}.json'.format(args.config), \"w\") as f:\n json.dump(res, f)\n time.sleep(1 * 60) # avoid conflicts\n print(\"=========================================\")\n print(\"Median: {}\".format(np.mean([x[0] for x in res])))\n print(\"99 Percentile: {}\".format(np.mean([x[1] for x in res])))\n print(\"=========================================\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"workloads/workflow/boki/scripts/hotel/hotel.py","file_name":"hotel.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463024835","text":"\"\"\"\nPython script for data pre-processing\n\"\"\"\n\nimport re\n\nimport utils.text_processing as tp\nfrom utils.helpers import logger\n\n\ndef remove_referenced_name(text):\n pattern = r\"@[^\\s\\.\\?,;:!]*\"\n return re.sub(pattern, \" \", text).strip()\n\n\ndef simple_processing(text):\n text = tp.unicode_normalize(text)\n text = tp.general_regex(text)\n text = remove_referenced_name(text)\n return text\n\n\ndef complex_processing(text):\n text = tp.unicode_normalize(text)\n text = tp.lowercasing(text)\n text = tp.general_regex(text)\n text = remove_referenced_name(text)\n text = tp.get_decontracted_form(text)\n text = tp.keep_alpha_space(text)\n text = tp.remove_repeating_chars(text)\n text = tp.remove_stopwords(text)\n if text != \"\":\n text = tp.perform_lemmatization(text)\n return text\n\n\ndef preprocess(data, preprocess_type=\"simple\"):\n try:\n if preprocess_type == \"simple\":\n data[\"text\"] = data[\"content\"].map(simple_processing)\n else:\n data[\"text\"] = data[\"content\"].map(complex_processing)\n data = data[[\"text\", \"type\"]].dropna()\n data = data.drop(data.loc[data[\"text\"] == \"\"].index)\n return data.reset_index(drop=True)\n except Exception as e:\n logger.error(\"Exception in pre-processing : {}\".format(str(e)))\n return None\n","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"479020478","text":"\"\"\" File reader\n\"\"\"\nimport os\nimport glob\nimport numpy as np\nfrom obspy import UTCDateTime\n\n# read phase file\ndef read_fpha(fpha):\n f=open(fpha); lines=f.readlines(); f.close()\n event_list = []\n for line in lines:\n codes = line.split(',')\n if len(codes[0])>10:\n ot = UTCDateTime(codes[0])\n lat, lon, dep, mag = [float(code) for code in codes[1:5]]\n event_loc = [ot, lat, lon, dep, mag]\n event_list.append([event_loc, {}])\n else:\n net_sta = codes[0]\n tp, ts = [UTCDateTime(code) for code in codes[1:3]]\n event_list[-1][-1][net_sta] = [tp, ts]\n return event_list\n\n# read station file \ndef read_fsta(fsta):\n f=open(fsta); lines=f.readlines(); f.close()\n sta_dict = {}\n for line in lines:\n codes = line.split(',')\n net_sta = codes[0]\n lat, lon, ele = [float(code) for code in codes[1:4]]\n sta_dict[net_sta] = [lat, lon, ele]\n return sta_dict\n\n# get data dict, given path structure\ndef get_data_dict(date, data_dir):\n # get data paths\n data_dict = {}\n date_code = '{:0>4}{:0>2}{:0>2}'.format(date.year, date.month, date.day)\n st_paths = sorted(glob.glob(os.path.join(data_dir, date_code, '*')))\n for st_path in st_paths:\n fname = os.path.split(st_path)[-1]\n net_sta = '.'.join(fname.split('.')[0:2])\n if net_sta in data_dict: data_dict[net_sta].append(st_path)\n else: data_dict[net_sta] = [st_path]\n # drop bad sta\n todel = [net_sta for net_sta in data_dict if len(data_dict[net_sta])!=3]\n for net_sta in todel: data_dict.pop(net_sta)\n return data_dict\n\n# UTCDateTime to string\ndef dtime2str(dtime):\n date = ''.join(str(dtime).split('T')[0].split('-'))\n time = ''.join(str(dtime).split('T')[1].split(':'))[0:9]\n return date + time\n\n\"\"\" Custimized functions\n\"\"\"\n\n","sub_path":"hypodd/cc/preprocess/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"334628578","text":"#!/usr/bin/env python3\n# -*- coding:utf8 -*-\n\n__author__ = 'Sam'\n\n'TCP'\n'''\nSocket是网络编程的一个抽象概念。通常我们用一个Socket表示“打开了一个网络链接”,而打开一个Socket需要知道目标计算机的IP地址和端口号,再指定协议类型即可\n\n大多数连接都是可靠的TCP连接。创建TCP连接时,主动发起连接的叫客户端,被动响应连接的叫服务器\n'''\n\n# 客户端\nimport socket \n\n#\t- 创建\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n#\t- 连接\ns.connect(('www.sina.com', 80))\n'''\n客户端要主动发起TCP连接,必须知道服务器的IP地址和端口号。新浪网站的IP地址可以用域名www.sina.com.cn自动转换到IP地址,但是怎么知道新浪服务器的端口号呢?\n\n答案是作为服务器,提供什么样的服务,端口号就必须固定下来。由于我们想要访问网页,因此新浪提供网页服务的服务器必须把端口号固定在80端口,因为80端口是Web服务的标准端口。其他服务都有对应的标准端口号,例如SMTP服务是25端口,FTP服务是21端口,等等。端口号小于1024的是Internet标准服务的端口,端口号大于1024的,可以任意使用\n'''\n\n#\t- 发送数据\ns.send(b'GET / HTTP/1.1 \\r\\nHost: www.sina.com\\r\\nConnection: Close\\r\\n\\r\\n ')\n'''\nTCP连接创建的是双向通道,双方都可以同时给对方发数据。但是谁先发谁后发,怎么协调,要根据具体的协议来决定。例如,HTTP协议规定客户端必须先发请求给服务器,服务器收到后才发数据给客户端\n'''\n#\t- 接收数据\nbuffer = []\nwhile True:\n\td = s.recv(1024)\n\tif d:\n\t\tbuffer.append(d)\n\telse:\n\t\tbreak\ndata = b''.join(buffer)\n\n#\t- 关闭连接\ns.close()\n\n#\t- 读取\n'''\n接收到的数据包括HTTP头和网页本身,我们只需要把HTTP头和网页分离一下,把HTTP头打印出来,网页内容保存\n'''\nheader, html = data.split(b'\\r\\n\\r\\n', 1)\nprint(header.decode('utf-8'))\n\n# 把接收的数据写入文件:\nwith open('sina.html', 'wb') as f:\n f.write(html)\n\n\n\n\n\n","sub_path":"Code/Network/do_tcp.py","file_name":"do_tcp.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"332288791","text":"\nimport sys\n#定義一個Node資料結構(class)\n#資料包含姓名分數學號\nclass Student:\n def __init__(self):#新增__ini__函式\n self.name = ''#資料\n self.score1 = 0\n self.score2 = 0\n self.score3 = 0\n self.num=''\n self.next = None #指向下一個節點的指標\n\n\n \n#初始化串列 \nptr = None\ncurrent = None\nprev = None\nhead = Student()#建立空節點head\nhead.next = None#指向下一個節點的指標\n\ndef insert_f():#新增insert_f函式\n global ptr #使ptr可以在函數中進行處理(全域變數)\n global head\n global current\n global prev\n\n ptr = Student()\n ptr.next = None#指向下一個節點的指標\n ptr.num=(input('學號:'))#新增學號\n ptr.name = input('姓名 : ')\n ptr.score1 = eval(input('計概成績: '))#新增計概成績\n ptr.score2 = eval(input('微積分成績: '))#新增微積分成績\n ptr.score3 = eval(input('程式設計成績: '))#新增程式設計成績\n ptr.total=(ptr.score1+ptr.score2+ptr.score3)#新增總分\n ptr.aver=round((ptr.score1+ptr.score2+ptr.score3)/3)#新增平均分數\n \n print()\n\n prev = head\n current = head.next\n while current != None and current.score1 >= ptr.score1:\n prev = current\n current = current.next\n while current != None and current.score2 >= ptr.score2:\n prev = current\n current = current.next\n while current != None and current.score3 >= ptr.score3:\n prev = current\n current = current.next\n ptr.next = current\n prev.next = ptr \n\n#新增\"刪除\"函數\ndef delete_f():\n global head\n global current\n global prev\n\n del_name = ''\n if head.next == None:\n print(' 沒有學生成績\\n')\n else:\n del_name = input(' 要刪除的學生姓名: ')\n prev = head\n current = head.next\n while current != None and del_name != current.name:\n prev = current\n current = current.next\n if current != None:\n prev.next = current.next\n current = None\n print('\\n 學生 %s 成績已刪除\\n' % del_name)\n else:\n print('\\n 無 %s 學生\\n' % del_name)\n#新增\"修改\"函數\ndef modify_f():\n global head\n global current\n global prev\n global ptr\n\n if head.next == None:\n print(' 沒有學生成績\\n')\n else:\n modify_name = input(' 修改的學生姓名: ')\n prev = head\n current = head.next\n while current != None and modify_name != current.name:\n prev = current\n current = current.next\n if current != None:\n print('\\n 學生姓名: %s' % current.name)\n print(' 學生計概成績: %d\\n' % current.score1)\n print(' 學生微積分成績: %d\\n' % current.score2)\n print(' 學生程式設計成績: %d\\n' % current.score3)\n prev.next = current.next # 把舊的資料刪除\n current = None\n # 重新加入新的資料\n newnum=ptr.num\n newscore1 = eval(input(' 輸入新的計概成績: '))\n newscore2 = eval(input(' 輸入新的微積分成績: '))\n newscore3 = eval(input(' 輸入新的程式設計成績: '))\n newtotal= newscore1+ newscore2+ newscore3\n newaver=round((newscore1+ newscore2+ newscore3)/3)\n \n ptr = Student()\n ptr.next = None\n ptr.num=newnum\n ptr.name = modify_namessss\n ptr.score1 = newscore1\n ptr.score2 = newscore2\n ptr.score3 = newscore3\n ptr.total=newtotal\n ptr.aver=newaver\n \n prev = head\n current = head.next\n while current != None and current.score1 >= ptr.score1:\n prev = current\n current = current.next\n while current != None and current.score2 >= ptr.score2:\n prev = current\n current = current.next\n while current != None and current.score3 >= ptr.score3:\n prev = current\n current = current.next\n ptr.next = current\n prev.next = ptr\n print(' 資料更新成功!\\n')\n else:\n print('\\n 無 %s 學生!\\n' % modify_name)\n#新增\"���示\"函數\ndef display_f():\n global head\n global current\n\n count = 0\n if head.next == None:\n print(' 無此成績\\n')\n else:\n print('%-13s %-10s %-8s %-8s %-10s %-8s %-8s' % ('學號','姓名','計概成績','微積分成績','程式設計成績','總成績','平均成績'))\n for i in range(100):\n print('-', end = '')\n print()\n current = head.next\n while current != None:\n print('%-15s %-15s %-14d %-14d %-11d %-10d %-10d' % (current.num,current.name, current.score1,current.score2,current.score3,current.total,current.aver))\n count = count + 1\n current = current.next\n for i in range(100):\n print('-', end = '')\n print()\n print('總共 %d 筆成績\\n' % count)\n#新增\"選單\"函數\ndef main():\n option = 0\n while True:\n print('****** 選單 ******')\n print(' <1> 輸入 ')\n print(' <2> 刪除 ')\n print(' <3> 修改 ')\n print(' <4> 顯示 ')\n print(' <5> 退出 ')\n print('*************************************')\n \n try:\n option = int(input(' 選擇 : '))\n except ValueError:\n print('非選單號碼')\n print('重試\\n')\n\n print()\n if option == 1:\n insert_f()\n elif option == 2:\n delete_f()\n elif option == 3:\n modify_f()\n elif option == 4:\n display_f()\n elif option == 5:\n sys.exit(0)\n\nmain()\n\n\n\n\n\n\n\nprint(x)\nmain()\n","sub_path":"成績輸入系統.py","file_name":"成績輸入系統.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"404156027","text":"# coding: utf8\n\n# Gibbs-Sampler, in LDAGibbsTopicIdentification.pdf beschrieben\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport multiprocessing as mp\nimport time as tm\nimport os\nfrom sklearn.preprocessing import normalize\n\n# Parameter:\nK=40 # Anzahl Topics\nnumOfProc=36\n\n# Dokumente laden:\nDocs=[]\nfile=open(\"docs.txt\",\"r\")\nDs=file.read()\nDs=Ds.split(\";\")\nfor D in Ds:\n d=D.split()\n Docs.append(d)\nprint(\"documents loaded\")\n\n# Vokabular laden:\nVocs=[]\nfile=open(\"vocs.txt\",\"r\")\nVs=file.read()\nVocs=Vs.split(\";\")\nwordIdx=dict()\nfor i in range(len(Vocs)):\n wordIdx[Vocs[i]]=i\nprint(\"vocabulary loaded\")\n\n# Dokumente aus Indizes:\niDocs=[]\nfor d in Docs:\n id=np.zeros(len(d),dtype=int)\n for i in range(len(d)):\n id[i]=wordIdx[d[i]]\n iDocs.append(id)\niDocs=np.array(iDocs)\n\n# Eigentlicher Samplingschritt\ndef gibsSampling(seed,K,iDocs,Vocs,wordIdx,outputTetas,outputPhis):\n np.random.seed(seed)\n # Parameter:\n M=len(iDocs)\n V=len(Vocs)\n bet=np.ones([V])/V\n betCount=0\n sumBet=np.sum(bet)\n alp=np.ones([K])/K\n alpCount=0\n Tops=[np.zeros(len(d),dtype=int) for d in iDocs]\n Tops=np.asanyarray(Tops)\n # Variablen:\n NMK=np.zeros([M,K],dtype=int)\n NKT=np.zeros([K,V],dtype=int)\n nk=np.zeros([K],dtype=int)\n Tetas=np.zeros([M,K],dtype=float)\n Phis=np.zeros([K,V],dtype=float)\n # Initialisation:\n for m in range(M):\n for n in range(len(iDocs[m])):\n k=np.argwhere(np.random.multinomial(1,alp)==1)[0][0]\n Tops[m][n]=k\n t=iDocs[m][n]\n NMK[m,k]+=1\n NKT[k,t]+=1\n nk[k]+=1\n # Gibbs sampling:\n finished=False\n L=-10\n LL=0 # Anz. gezogene Samples für Mittelwertbildung\n while not finished:\n for m in range(M):\n for n in range(len(iDocs[m])):\n k=Tops[m][n]\n t=iDocs[m][n]\n NMK[m,k]-=1\n NKT[k,t]-=1\n nk[k]-=1\n nenn=nk+sumBet\n pt=NKT[:,t]+bet[t]\n pk=NMK[m,:]+alp\n p=np.multiply(np.divide(pt,nenn),pk)\n p-=np.min(p)\n p/=np.sum(p)\n k_new=np.argwhere(np.random.multinomial(1,p)==1)[0][0]\n Tops[m][n]=k_new\n NMK[m,k_new]+=1\n NKT[k_new,t]+=1\n nk[k_new]+=1\n L+=1\n if L%1==0:\n filename=str(mp.current_process())\n filename=filename[9:19].replace(',','')\n file=open(filename+\".txt\",\"w\")\n file.write(filename+\" LL: \"+str(LL)+\" L: \"+str(L))\n file.close()\n if L>=10:\n Tetas=np.add(Tetas,NMK)\n alpCount+=1\n Phis=np.add(Phis,NKT)\n betCount+=1\n L=0\n LL+=1\n if LL==15:\n finished=True\n # Mittelwertbildung für Teta und Phi:\n alpMat=[alp for mm in range(M)]\n alpMat=np.array(alpMat)*alpCount\n Tetas=np.add(Tetas,alpMat)\n Tetas=normalize(Tetas,axis=1,norm='l1')\n betMat=[bet for kk in range(K)]\n betMat=np.array(betMat)*betCount\n Phis=np.add(Phis,betMat)\n Phis=normalize(Phis,axis=1,norm='l1')\n outputTetas.put(Tetas)\n outputPhis.put(Phis)\n return\n\n# Prozesse anlegen:\noutputTetas=mp.Queue()\noutputPhis=mp.Queue()\nprocesses=[mp.Process(target=gibsSampling, args=(x*7+43,K,iDocs,Vocs,wordIdx,outputTetas,outputPhis)) for x in range(numOfProc)]\n\n# Sampling Prozesse ausführen:\nprint(\"start gibs-sampling\")\nstartTime=tm.time()\nfor p in processes:\n p.start()\nTetas=[outputTetas.get() for p in processes]\nPhis=[outputPhis.get() for p in processes]\nfor p in processes:\n p.join()\nendTime=tm.time()\nduration=endTime-startTime\nduration\nprint(\"gibs-sampling finished, ...duration [min]: \"+str(duration/60))\n\nTetas=np.asanyarray(Tetas)\nPhis=np.asanyarray(Phis)\nprint('results from gibs-sampling collected')\n\n# Permutation, da Themen in unterschiedlicher Reihenfolge vorliegen können:\nfinalTeta=Tetas[0]\nsimMat=np.zeros([K,K])\nperm=np.zeros([K],dtype=int)\nfor i in range(1,numOfProc):\n for ii in range(K):\n for iii in range(K):\n sim=np.dot(finalTeta[:,ii],Tetas[i][:,iii])\n sim=sim/(np.linalg.norm(finalTeta[:,ii])*np.linalg.norm(Tetas[i][:,iii]))\n simMat[ii,iii]=sim\n print(\"Teta simMat finished for Proc. \"+str(i))\n for ii in range(K):\n maxIdx=np.unravel_index(np.argmax(simMat),[K,K])\n perm[maxIdx[0]]=maxIdx[1]\n simMat[maxIdx[0],:]=0\n simMat[:,maxIdx[1]]=0\n finalTeta=finalTeta+Tetas[i][:,perm]\n print(\"permuted Teta from Proc. \"+str(i))\nprint(\"Teta permutation finished\")\n\n# Permutation, da Themen in unterschiedlicher Reihenfolge vorliegen können:\nfinalPhi=Phis[0]\nsimMat=np.zeros([K,K])\nperm=np.zeros([K],dtype=int)\nfor i in range(1,numOfProc):\n for ii in range(K):\n for iii in range(K):\n sim=np.dot(finalPhi[ii,:],Phis[i][iii,:])\n sim=sim/(np.linalg.norm(finalPhi[ii,:])*np.linalg.norm(Phis[i][iii,:]))\n simMat[ii,iii]=sim\n print(\"Phi simMat finished for Proc. \"+str(i))\n for ii in range(K):\n maxIdx=np.unravel_index(np.argmax(simMat),[K,K])\n perm[maxIdx[0]]=maxIdx[1]\n simMat[maxIdx[0],:]=0\n simMat[:,maxIdx[1]]=0\n finalPhi=finalPhi+Phis[i][perm,:]\n print(\"permuted Phi from Proc. \"+str(i))\nprint(\"Phi permutation finished\")\n\nfinalTeta=normalize(finalTeta, axis=1, norm='l1')\nfinalPhi=normalize(finalPhi, axis=1, norm='l1')\nnp.savetxt(\"tetas.txt\",finalTeta)\nnp.savetxt(\"phis.txt\",finalPhi)\nprint(\"tetas and phis saved to file\")\n","sub_path":"gibbsSampler.py","file_name":"gibbsSampler.py","file_ext":"py","file_size_in_byte":5602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466378408","text":"\"\"\"\nThis example uses OpenGL via Pyglet and draws\na bunch of rectangles on the screen.\n\"\"\"\n\nimport random\nimport time\nimport pyglet.gl as GL\nimport pyglet\nimport ctypes\n\n# Set up the constants\nSCREEN_WIDTH = 700\nSCREEN_HEIGHT = 500\n\nRECT_WIDTH = 50\nRECT_HEIGHT = 50\n\n\nclass Shape():\n def __init__(self):\n self.x = 0\n self.y = 0\n\n\nclass VertexBuffer():\n \"\"\" Class to hold vertex buffer info. \"\"\"\n def __init__(self, vbo_id, size):\n self.vbo_id = vbo_id\n self.size = size\n\n\ndef add_rect(rect_list, x, y, width, height, color):\n \"\"\" Create a vertex buffer for a rectangle. \"\"\"\n rect_list.extend([-width / 2, -height / 2,\n width / 2, -height / 2,\n width / 2, height / 2,\n -width / 2, height / 2])\n\n\ndef create_vbo_for_rects(v2f):\n vbo_id = GL.GLuint()\n\n GL.glGenBuffers(1, ctypes.pointer(vbo_id))\n\n data2 = (GL.GLfloat*len(v2f))(*v2f)\n\n GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo_id)\n GL.glBufferData(GL.GL_ARRAY_BUFFER, ctypes.sizeof(data2), data2,\n GL.GL_STATIC_DRAW)\n\n shape = VertexBuffer(vbo_id, len(v2f)//2)\n return shape\n\n\ndef render_rect_filled(shape, x, y):\n \"\"\" Render the shape at the right spot. \"\"\"\n # Set color\n GL.glDisable(GL.GL_BLEND)\n GL.glColor4ub(shape.color[0], shape.color[1], shape.color[2], 255)\n\n GL.glBindBuffer(GL.GL_ARRAY_BUFFER, shape.vbo_id)\n GL.glVertexPointer(2, GL.GL_FLOAT, 0, 0)\n\n GL.glLoadIdentity()\n GL.glTranslatef(x + shape.width / 2, y + shape.height / 2, 0)\n\n GL.glDrawArrays(GL.GL_QUADS, 0, shape.size)\n\n\nclass MyApplication():\n \"\"\" Main application class. \"\"\"\n\n def setup(self):\n \"\"\" Set up the game and initialize the variables. \"\"\"\n\n # Set background to white\n GL.glClearColor(1, 1, 1, 1)\n\n self.rect_list = []\n self.shape_list = []\n\n for i in range(2000):\n x = random.randrange(0, SCREEN_WIDTH)\n y = random.randrange(0, SCREEN_HEIGHT)\n width = random.randrange(20, 71)\n height = random.randrange(20, 71)\n\n d_x = random.randrange(-3, 4)\n d_y = random.randrange(-3, 4)\n\n red = random.randrange(256)\n blue = random.randrange(256)\n green = random.randrange(256)\n alpha = random.randrange(256)\n color = (red, blue, green, alpha)\n\n shape = Shape()\n shape.x = x\n shape.y = y\n self.shape_list.append(shape)\n\n add_rect(self.rect_list, 0, 0, width, height, color)\n\n print(\"Creating vbo for {} vertices.\".format(len(self.rect_list) // 2))\n self.rect_vbo = create_vbo_for_rects(self.rect_list)\n print(\"VBO {}\".format(self.rect_vbo.vbo_id))\n\n def animate(self, dt):\n \"\"\" Move everything \"\"\"\n\n pass\n\n def on_draw(self):\n \"\"\"\n Render the screen.\n \"\"\"\n start = time.time()\n\n float_size = ctypes.sizeof(ctypes.c_float)\n record_len = 10 * float_size\n\n GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)\n\n GL.glMatrixMode(GL.GL_MODELVIEW)\n GL.glEnableClientState(GL.GL_VERTEX_ARRAY)\n\n GL.glColor4ub(255, 0, 0, 255)\n\n GL.glBindBuffer(GL.GL_ARRAY_BUFFER, self.rect_vbo.vbo_id)\n GL.glVertexPointer(2, GL.GL_FLOAT, record_len, 0)\n\n for i in range(len(self.shape_list)):\n shape = self.shape_list[i]\n GL.glLoadIdentity()\n GL.glTranslatef(shape.x, shape.y, 0)\n GL.glDrawArrays(GL.GL_QUADS, i * 8, 8)\n # GL.glDrawArrays(GL.GL_QUADS,\n # 0,\n # self.rect_vbo.size)\n\n elapsed = time.time() - start\n print(elapsed)\n\n\ndef main():\n window = pyglet.window.Window(SCREEN_WIDTH, SCREEN_HEIGHT)\n app = MyApplication()\n app.setup()\n pyglet.clock.schedule_interval(app.animate, 1/60)\n\n @window.event\n def on_draw():\n window.clear()\n app.on_draw()\n\n pyglet.app.run()\n\nmain()\n","sub_path":"experimental/a_quick_test5.py","file_name":"a_quick_test5.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"524958026","text":"from django.conf.urls import url\n\nfrom snote import views\n\n\nurlpatterns = (\n url(r'^$', views.home, name='home'),\n url(r'^(?P[0-9]+)$', views.detail, name='detail'),\n url(r'^(?P[0-9]+)/notes$', views.notes, name='notes'),\n)","sub_path":"snote/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"29433325","text":"\n\nfrom typing import *\n\n\ndef reconstructQueue(people: List[List[int]]) -> List[List[int]]:\n people.sort(key=lambda x: (x[0], x[1]))\n rtn = [None for _ in range(len(people))]\n for p in people:\n count, i = 0, 0\n while count < p[1]:\n if rtn[i] is None or rtn[i][0]==p[0]:\n count, i = count + 1, i + 1\n else:\n i += 1\n while rtn[i] != None:\n i += 1\n rtn[i] = p\n return rtn\n\n\nif __name__ == '__main__':\n print(reconstructQueue([[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]))\n","sub_path":"406_reconstructQueueByHeight.py","file_name":"406_reconstructQueueByHeight.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607576674","text":"import sys, os\r\nfrom cx_Freeze import setup, Executable\r\nfrom PyQt4 import uic\r\nimport shutil\r\n\r\nui = open(\"Form.ui\", 'r')\r\npy = open(\"Form.py\", 'w')\r\nerr = uic.compileUi(ui, py, True)\r\nui.close()\r\npy.close()\r\n\r\ntry:\r\n for i in os.listdir(\"C:\\\\Python32\\\\Lib\\\\site-packages\\\\PyQt4\\\\plugins\"):\r\n shutil.copytree(\"C:\\\\Python32\\\\Lib\\\\site-packages\\\\PyQt4\\\\plugins\\\\\"+i,\"C:\\\\Users\\\\Alen\\\\PycharmProjects\\\\Oratorij\\\\build\\\\exe.win-amd64-3.2\\\\\"+i)\r\nexcept:\r\n pass\r\n\r\nbuild_exe_options = {\"packages\": [\"decimal\"], \"excludes\": [\"tkinter\"], 'include_files':[], 'includes':['sip', 'PyQt4.QtCore']}\r\nif sys.platform == \"win32\":\r\n base = \"Win32GUI\"\r\n\r\nsetup( name = \"Prijave\",\r\n version = \"1\",\r\n description = \"Program za prijavo otrok na oratorij\",\r\n options = {\"build_exe\": build_exe_options},\r\n executables = [Executable(\"Prijave.py\", base=base,icon = \"logotip.ico\")])","sub_path":"Program za tablo/OratorijPyQt/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"121427891","text":"import random\r\n #for generating random integers\r\n #randint(self,a,b) returns random int in range a-b including ep's\r\nimport matplotlib.pyplot as plt\r\n #for plotting histogram... below is syntax to print histogram\r\n #x = [value1, value2, value3,....]\r\n #plt.style.use('ggplot')\r\n #plt.hist(x, bins = number of bins)\r\n #plt.show()\r\n \r\n \r\ndef hash1(word):\r\n #hash1\r\n sum = 0\r\n\r\n for i in range(len(word)):\r\n for j in range(len(a2z)):\r\n if (word[i] == a2z[j]):\r\n sum = sum + j + 1\r\n sum = (sum%5851)\r\n return sum\r\ndef hash2(word):\r\n #hash2\r\n sum = 0\r\n for i in range(len(word)):\r\n for j in range(len(a2z)):\r\n if (word[i] == a2z[j]):\r\n sum = sum + ((j + 1) * randNumList[j])\r\n sum = (sum%5851)\r\n return sum\r\n\r\n#list Initializations and Declarations\r\n\r\nnameList = []\r\nnewNameList = []\r\n\r\nhashOneList = []\r\nhashTwoList = []\r\n\r\nrandNumList = [6605, 5537, 7219, 6371, 2569, 5340, 7666, 8100, 7049, 3275, 1893, 28, 3280, 7087, 4876, 8722, 3340, 2778, 3417, 3270, 4707, 7854, 6743, 3015, 5840, 8399]\r\na2z = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] \r\n\r\n#Open File line by line\r\nnameInput = open('dist.all.last.txt', 'r')\r\n\r\n#Read only first word from each line and append it to nameList\r\nfor line in nameInput:\r\n nameList.append(line.split(None, 1)[0])\r\n \r\n#For 50% of the names in original list:\r\n#Access a random index in said list and append it to newNameList\r\nfor i in range(44394):\r\n newNameList.append(nameList[random.randint(0,88798)])\r\n \r\n#iterate through newNameList and call hash1 on names, then append the return value to hashOneList\r\nfor i in range(len(newNameList)):\r\n word = newNameList[i]\r\n hashOneList.append(hash1(word))\r\n#iterate through newNameList and call hash2 on names, then append the return value to hashTwoList\r\nfor i in range(len(newNameList)):\r\n word = newNameList[i]\r\n hashTwoList.append(hash2(word))\r\n \r\n \r\n#Graph hash1 histogram\r\ngraph1 = plt.figure()\r\naxis1 = graph1.add_subplot()\r\nn, bins, patches = axis1.hist(hashOneList, 300)\r\naxis1.set_title(\"Hash 1\")\r\naxis1.set_xlabel(\"Hash Index\")\r\naxis1.set_ylabel(\"Number of Strings\")\r\n\r\n#Graph hash2 histogram\r\ngraph2 = plt.figure()\r\naxis2 = graph2.add_subplot()\r\nn, bins, patches = axis2.hist(hashTwoList, 5851)\r\naxis2.set_title(\"Hash 2\")\r\naxis2.set_xlabel(\"Hash Index\")\r\naxis2.set_ylabel(\"Number of Strings\")\r\n\r\n#initialize counterList1 and counterList2 values to 0\r\n\r\ncounterList1 = []\r\ngraphCounter = []\r\ncounterList2 = []\r\ngraphCounter2 = []\r\n\r\n#Assign all values in counterList1 to 0\r\nfor i in range(300):\r\n counterList1.append(0)\r\n#iterate through hashOneList and increment counterList1 every time index is encountered\r\nfor i in range(len(hashOneList)):\r\n counterList1[hashOneList[i]] = counterList1[hashOneList[i]] + 1\r\n graphCounter.append(max(counterList1))\r\n \r\n \r\n# #Graph hash1 growth rate\r\ngraph3 = plt.figure()\r\naxis3 = graph3.add_subplot()\r\naxis3.plot(range(0, len(graphCounter)), graphCounter)\r\naxis3.set_title(\"Hash 1 Max Growth Rate\")\r\naxis3.set_xlabel(\"Words Hashed\")\r\naxis3.set_ylabel(\"Longest Chain\") \r\n\r\n# #Assign all values in counterList2 to 0\r\nfor i in range(5851):\r\n counterList2.append(0)\r\n#iterate through hashTwoList and increment counterList1 every time index is encountered\r\nfor i in range(len(hashTwoList)):\r\n counterList2[hashTwoList[i]] = counterList2[hashTwoList[i]] + 1\r\n graphCounter2.append(max(counterList2))\r\n \r\n# #Graph hash2 growth rate\r\ngraph4 = plt.figure()\r\naxis4 = graph4.add_subplot()\r\naxis4.plot(range(0, len(graphCounter2)), graphCounter2)\r\naxis4.set_title(\"Hash 2 Max Growth Rate\")\r\naxis4.set_xlabel(\"Words Hashed\")\r\naxis4.set_ylabel(\"Longest Chain\")\r\n\r\n#Need to show #of collisions as a function of #of buckets\r\ncollisionA = [] \r\nfor a in range(1,300):\r\n col = 0\r\n finalForm1 = []\r\n for b in range(1, len(hashOneList)):\r\n word = hashOneList[b]\r\n if(word > 0):\r\n word = word % a\r\n if(word in finalForm1):\r\n col += 1\r\n else:\r\n finalForm1.append(word)\r\n collisionA.append(col)\r\n\r\ncollisionB = []\r\nfor c in range(1,500):\r\n col = 0\r\n finalForm2 = []\r\n for d in range(1 ,len(hashTwoList)):\r\n word = hashTwoList[d]\r\n if(word > 0):\r\n word = word % c\r\n if(word in finalForm2):\r\n col += 1\r\n else:\r\n finalForm2.append(word)\r\n collisionB.append(col)\r\n\r\n# #Graph collisions as a function of l\r\ngraph5 = plt.figure()\r\naxis5 = graph5.add_subplot()\r\naxis5.plot(range(0, len(collisionA)), collisionA)\r\naxis5.set_title(\"Collisions as a function of L\")\r\naxis5.set_xlabel(\"Size of L\")\r\naxis5.set_ylabel(\"Number of Collisions\") \r\n\r\n# #Graph collisions as a function of L\r\ngraph6 = plt.figure()\r\naxis6 = graph6.add_subplot()\r\naxis6.plot(range(0, len(collisionB)), collisionB)\r\naxis6.set_title(\"Collisions as a function of L\")\r\naxis6.set_xlabel(\"Size of L\")\r\naxis6.set_ylabel(\"Number of Collisions\") ","sub_path":"McGregor-Ian-0526-PS4.py3","file_name":"McGregor-Ian-0526-PS4.py3","file_ext":"py3","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"449244060","text":"## Read input as specified in the question\n## Print the required output in given format\nn = int(input())\n\ni=1\nwhile i<=n:\n spaces = 1\n while spaces <= n-i:\n print(\" \",end='')\n spaces = spaces + 1\n \n num = 1\n while num <= i:\n print(num,end='')\n num = num+1\n print()\n i = i+1\n","sub_path":"mirror_no_pattern.py","file_name":"mirror_no_pattern.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"477977327","text":"# Copyright 2016 NOKIA\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 netaddr\n\nfrom nuage_neutron.vsdclient.common.cms_id_helper import get_vsd_external_id\nfrom nuage_neutron.vsdclient.common import constants\nfrom nuage_neutron.vsdclient.common import helper\nfrom nuage_neutron.vsdclient.common import nuagelib\nfrom nuage_neutron.vsdclient import restproxy\n\nVSD_RESP_OBJ = constants.VSD_RESP_OBJ\n\nLOG = logging.getLogger(__name__)\n\n\ndef get_l3dom_policygroup_by_sgid(restproxy_serv, l3dom_id, sg_id):\n req_params = {\n 'domain_id': l3dom_id,\n 'externalID': get_vsd_external_id(sg_id)\n }\n\n nuage_policygroup = nuagelib.NuagePolicygroup(create_params=req_params)\n response = restproxy_serv.rest_call(\n 'GET', nuage_policygroup.post_resource(), '',\n extra_headers=nuage_policygroup.extra_headers_get())\n\n if not nuage_policygroup.validate(response):\n raise restproxy.RESTProxyError(nuage_policygroup.error_msg)\n\n if not response[3]:\n return response[3]\n else:\n return nuage_policygroup.get_policygroup_id(response)\n\n\ndef get_l2dom_policygroup_by_sgid(restproxy_serv, l2dom_id, sg_id):\n req_params = {\n 'domain_id': l2dom_id,\n 'externalID': get_vsd_external_id(sg_id)\n }\n\n nuage_policygroup = nuagelib.NuagePolicygroup(create_params=req_params)\n response = restproxy_serv.rest_call(\n 'GET', nuage_policygroup.post_resource_l2dom(), '',\n extra_headers=nuage_policygroup.extra_headers_get())\n\n if not nuage_policygroup.validate(response):\n raise restproxy.RESTProxyError(nuage_policygroup.error_msg)\n\n if not response[3]:\n nuage_policygroup_id = response[3]\n else:\n nuage_policygroup_id = nuage_policygroup.get_policygroup_id(response)\n return nuage_policygroup_id\n\n\ndef get_policygroup_by_sgid(restproxy_serv, params):\n neutron_rtr_id = params.get('neutron_rtr_id', None)\n l3dom_id = None\n l2dom_id = params.get('l2dom_id')\n if neutron_rtr_id:\n l3dom_id = helper.get_l3domid_by_router_id(restproxy_serv,\n neutron_rtr_id)\n policygroup_id = get_l3dom_policygroup_by_sgid(\n restproxy_serv, l3dom_id, params['sg_id'])\n else:\n policygroup_id = get_l2dom_policygroup_by_sgid(\n restproxy_serv, params.get('l2dom_id'), params['sg_id'])\n\n result = {\n 'nuage_rtr_id': l3dom_id,\n 'nuage_l2dom_id': l2dom_id,\n 'policygroup_id': policygroup_id\n }\n\n return result\n\n\ndef get_l3dom_inbound_acl_id(restproxy_serv, dom_id):\n req_params = {\n 'parent_id': dom_id\n }\n nuageibacl = nuagelib.NuageInboundACL(create_params=req_params)\n default_l3_acl_name = dom_id + constants.NUAGE_DEFAULT_L3_INGRESS_ACL\n extra_headers = nuageibacl.extra_headers_get_by_name(default_l3_acl_name)\n response = restproxy_serv.rest_call('GET',\n nuageibacl.get_resource_l3(), '',\n extra_headers=extra_headers)\n if not nuageibacl.get_validate(response):\n raise restproxy.RESTProxyError(nuageibacl.error_msg)\n nuageibacl_id = nuageibacl.get_iacl_id(response)\n\n return nuageibacl_id\n\n\ndef get_l3dom_outbound_acl_id(restproxy_serv, dom_id):\n req_params = {\n 'parent_id': dom_id\n }\n nuageobacl = nuagelib.NuageOutboundACL(create_params=req_params)\n default_l3_acl_name = dom_id + constants.NUAGE_DEFAULT_L3_EGRESS_ACL\n extra_headers = nuageobacl.extra_headers_get_by_name(default_l3_acl_name)\n response = restproxy_serv.rest_call('GET',\n nuageobacl.get_resource_l3(), '',\n extra_headers=extra_headers)\n if not nuageobacl.get_validate(response):\n raise restproxy.RESTProxyError(nuageobacl.error_msg)\n nuageobacl_id = nuageobacl.get_oacl_id(response)\n\n return nuageobacl_id\n\n\ndef get_l2dom_inbound_acl_id(restproxy_serv, dom_id):\n req_params = {\n 'parent_id': dom_id\n }\n nuageibacl = nuagelib.NuageInboundACL(create_params=req_params)\n default_l2_acl_name = dom_id + constants.NUAGE_DEFAULT_L2_INGRESS_ACL\n extra_headers = nuageibacl.extra_headers_get_by_name(default_l2_acl_name)\n response = restproxy_serv.rest_call('GET',\n nuageibacl.get_resource_l2(), '',\n extra_headers=extra_headers)\n if not nuageibacl.get_validate(response):\n raise restproxy.RESTProxyError(nuageibacl.error_msg)\n nuageibacl_id = nuageibacl.get_iacl_id(response)\n\n return nuageibacl_id\n\n\ndef get_l2dom_outbound_acl_id(restproxy_serv, dom_id):\n req_params = {\n 'parent_id': dom_id\n }\n nuageobacl = nuagelib.NuageOutboundACL(create_params=req_params)\n default_l2_acl_name = dom_id + constants.NUAGE_DEFAULT_L2_EGRESS_ACL\n extra_headers = nuageobacl.extra_headers_get_by_name(default_l2_acl_name)\n response = restproxy_serv.rest_call('GET',\n nuageobacl.get_resource_l2(), '',\n extra_headers=extra_headers)\n if not nuageobacl.get_validate(response):\n raise restproxy.RESTProxyError(nuageobacl.error_msg)\n nuageobacl_id = nuageobacl.get_oacl_id(response)\n\n return nuageobacl_id\n\n\ndef get_inbound_acl_details(restproxy_serv, dom_id, type=constants.SUBNET):\n req_params = {\n 'parent_id': dom_id\n }\n nuageibacl = nuagelib.NuageInboundACL(create_params=req_params)\n if type == constants.L2DOMAIN:\n default_acl_name = dom_id + constants.NUAGE_DEFAULT_L2_INGRESS_ACL\n url = nuageibacl.get_resource_l2()\n else:\n default_acl_name = dom_id + constants.NUAGE_DEFAULT_L3_INGRESS_ACL\n url = nuageibacl.get_resource_l3()\n extra_headers = nuageibacl.extra_headers_get_by_name(default_acl_name)\n response = restproxy_serv.rest_call('GET',\n url, '',\n extra_headers=extra_headers)\n if not nuageibacl.get_validate(response):\n raise restproxy.RESTProxyError(nuageibacl.error_msg)\n return response[3][0]\n\n\ndef _get_remote_policygroup_id(restproxy_serv, sg_id, resourcetype,\n resource_id, sg_name):\n req_params = {\n 'name': sg_name,\n 'domain_id': resource_id,\n 'sg_id': sg_id,\n 'externalID': get_vsd_external_id(sg_id)\n }\n\n nuage_policygroup = nuagelib.NuagePolicygroup(create_params=req_params)\n if resourcetype == 'l3domain':\n url = nuage_policygroup.post_resource()\n else:\n url = nuage_policygroup.post_resource_l2dom()\n policygroups = restproxy_serv.get(\n url, extra_headers=nuage_policygroup.extra_headers_get(),\n required=True)\n if policygroups:\n return policygroups[0]['ID']\n else:\n policygroups = restproxy_serv.post(\n url,\n nuage_policygroup.post_data())\n return policygroups[0]['ID']\n\n\ndef _create_nuage_prefix_macro(restproxy_serv, sg_rule, np_id):\n net = netaddr.IPNetwork(sg_rule['remote_ip_prefix'])\n macro_name = (np_id + '_' + str(int(net.ip)) + '_' +\n str(int(net.netmask)))\n req_params = {\n 'net_partition_id': np_id,\n 'net': net,\n 'name': macro_name\n }\n nuage_np_net = nuagelib.NuageNetPartitionNetwork(\n create_params=req_params)\n response = restproxy_serv.rest_call(\n 'GET',\n nuage_np_net.get_resource(), '',\n nuage_np_net.extra_headers_get_netadress(\n str(net.ip), str(net.netmask)))\n pubnet_id = None\n if not nuage_np_net.validate(response):\n raise restproxy.RESTProxyError(nuage_np_net.error_msg)\n if response[3]:\n pubnet_id = response[3][0]['ID']\n\n if pubnet_id:\n return pubnet_id\n\n response = restproxy_serv.rest_call(\n 'POST',\n nuage_np_net.post_resource(),\n nuage_np_net.post_data())\n if not nuage_np_net.validate(response):\n if response[0] != constants.CONFLICT_ERR_CODE:\n raise restproxy.RESTProxyError(nuage_np_net.error_msg)\n else:\n response = restproxy_serv.rest_call(\n 'GET',\n nuage_np_net.get_resource(), '')\n LOG.debug(nuage_np_net.error_msg)\n return nuage_np_net.get_np_network_id(response)\n","sub_path":"nuage_neutron/vsdclient/common/pg_helper.py","file_name":"pg_helper.py","file_ext":"py","file_size_in_byte":8961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"477580322","text":"#! env python3\n####################################################\n#\n# Uebung:\n# Erweitern Sie das Programm so, dass die Figur bis zur Gerechtigkeitsgasse läuft.\n#\n# Verwenden Sie hierfür eine while-Schleife\n# Die Gerechtigkeitsgasse beginnt an der x-Position 670\n#\n# Vorhandene Funktionen\n#\n# go_right() : Geht einen Schritt nach rechts\n# go_left() : Geht einen Schritt nach links\n# go_up() : Geht einen Schritt hoch\n# go_down() : Geht einen Schritt runter\n# Taste q : Abbruch des Spiels\n#\n# Hinweis: Neuer Code nur im markierten Bereich eintragen\n#\n####################################################\n\n#Module\nimport pygame\nimport time\nfrom stadtlauf_bern_modul import *\n\nd=1 #Anzahl Durchgänge\nslower=0.01 #Je höher die Zahl, umso langsamer läuft die Figur\n\nwhile run:\n clock.tick(27)\n if d>0:\n\n #Lauf zu Zytglogge Turm\n for i in range(440):\n time.sleep(slower) #Laufgeschwindigkeit reduzieren\n x=go_right()\n if x%10==0 and x<=210:\n y=go_up()\n elif x%10==0 and x<450:\n y=go_down()\n redrawGameWindow() #Grafik neu darstellen\n\n##############################################\n #######################################\n # Hier kommt Ihr Code (ab diesem Einzug)\n #Lauf zu Gerechtigkeitsgasse\n\n while x<670:\n time.sleep(slower) #Laufgeschwindigkeit reduzieren\n x=go_right()\n redrawGameWindow() #Grafik neu darstellen\n\n #bis hier\n #######################################\n##############################################\n\n d-=1\n go_stop()\n run=check_key() #Prüfen ob und welche Taste gedrückt wurde\n redrawGameWindow() #Grafik neu darstellen\n \n#Ende Darstellung\npygame.quit()\n\n","sub_path":"U3_5_Stadtlauf_Bern_while_Lösung.py","file_name":"U3_5_Stadtlauf_Bern_while_Lösung.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"289963617","text":"from owlready2 import *\nfrom UInterface import userMenu, multiUserMenu, clear\nfrom Agent import Agent as ag\nfrom ProtectiveGear import extractProtectionGear\nimport Activity as AC\n\ntexts = {True:{\"age\":\"How old are you?: \",\n \"gender\":\"What is your gender?: \",\n \"covidtest\":\"What was the result of your test?: \",\n \"weight\":\"Under which weight type do you fall?: \",\n \"smokes\":\"Do you smoke? (yes/no): \",\n \"symptoms\":\"What symptoms do you have?\",\n \"diseases\":\"What serious diseases do you have?\",\n \"liveswith\":\"Perfect! Do you wish to share who you live with? This information is important to value risk at home. (yes/no): \",\n \"liveswithintroduce\":\"Alright! Tell me about a person you live with, what is their name?: \",\n \"furtherliveswith\":\"Alright! Do you wish to tell me about someone else you live with? (yes/no): \",\n \"companionsintroduce\":\"Alright! Tell me about this companion, what is their name?: \",\n \"pastactivityyesno\":\"Have you gone to other places earlier that might be relevant? (yes/no): \",\n \"pastactivitytell\":\"Alright! Tell me, where did you go?\\n\"},\n\n False:{\"age\":\"How old is {name}?: \",\n \"gender\":\"What is {name}'s gender?: \",\n \"covidtest\":\"What was the result of {name}'s test?: \",\n \"weight\":\"Under which weight type does {name} fall?: \",\n \"smokes\":\"Does {name} smoke? (yes/no): \",\n \"symptoms\":\"What symptoms does {name} have?\",\n \"diseases\":\"What serious diseases does {name} have?\",\n \"liveswith\":\"Perfect! Do you know who {name} lives with? (yes/no): \",\n \"liveswithintroduce\":\"Alright! Tell me about a person {name} lives with, what is their name?: \",\n \"furtherliveswith\":\"Alright! Do you recall anybody else who lives with {name}? (yes/no): \",\n \"companionsintroduce\":\"Alright! Tell me about this companion, what is their name?: \",\n \"pastactivityyesno\":\"Has {name} gone to other places earlier that might be relevant? (yes/no): \",\n \"pastactivitytell\":\"Alright! Tell me, where did {name} go?\\n\"}}\n\ndef getAge(main, person):\n age = input(texts[main][\"age\"].format(name=person.name))\n age = int(age)\n if age < 18:\n person.age = \"Child\"\n elif age > 65:\n person.age = \"Old\"\n else:\n person.age = \"Adult\"\n\ndef getGender(main, person):\n genders = [\"Male\", \"Female\"]\n print(texts[main][\"gender\"].format(name=person.name))\n uindex = userMenu(genders)\n person.gender = genders[uindex]\n\ndef covidTest(main, person):\n testvalues = [(\"Positive\", \"Positive_Test\"), (\"Negative\", \"Negative_Test\")]\n print(texts[main][\"covidtest\"].format(name=person.name))\n uindex = userMenu([x[0] for x in testvalues])\n person.covidtest = testvalues[uindex][1]\n\ndef getWeight(main, person):\n weightvalues = [(\"Underweight\", \"Underweight\"), (\"On expected weight\", \"On_Weight\"), (\"Overweight\", \"Overweight\")]\n print(texts[main][\"weight\"].format(name=person.name))\n uindex = userMenu([x[0] for x in weightvalues])\n person.weight = weightvalues[uindex][1]\n\ndef hasWeakLungs(main, person):\n person.lungs = \"Weak_Lungs\"\n\ndef getSmoking(main, person):\n uinput = input(texts[main][\"smokes\"].format(name=person.name))\n person.smoking = uinput.lower() == \"yes\"\n if not person.smoking:\n person.smoking = None\n\ndef getDiseases(main, person):\n diseases = [(\"Breast Cancer\", \"Breast_Cancer\"), (\"Lung Cancer\", \"Lung_Cancer\"),\n (\"Prostate Cancer\", \"Prostate_Cancer\"), (\"Acute Bronchitis\", \"Acute_Bronchitis\"),\n (\"Asthma\", \"Asthma\"), (\"COVID-19\", \"COVID-19\"), (\"AIDS\", \"AIDS\")]\n uindexes = multiUserMenu([x[0] for x in diseases], textprompt=texts[main][\"diseases\"].format(name=person.name))\n person.diseases = list([diseases[index][1] for index in uindexes])\n\ndef getSymptoms(main, person):\n symptoms = [(\"Coughing\",\"Coughing\"), (\"Severe coughing\",\"Heavy_Coughing\"),\n (\"Minor coughing\",\"Minor_Coughing\"),\n (\"Severe shortness of breath\", \"Heavy_Breathlessness\"),\n (\"Slight shortness of breath\", \"Minor_Breathlessness\"),\n (\"High fever\",\"High_Fever\"),\n (\"Moderate fever\",\"Fever\"),\n (\"Slight fever\",\"Low_Fever\"),\n (\"Severe sneezing\", \"Heavy_Sneezing\"),(\"Slight sneezing\",\"Minor_Sneezing\"),\n (\"Severe throat pain\",\"Heavy_Throat_Pain\"), (\"Minor throat pain\",\"Minor_Throat_Pain\"),\n (\"Severe muscle aching\",\"Heavy_Muscle_Ache\"), (\"Slight muscle aching\",\"Minor_Muscle_Ache\")]\n uindexes = multiUserMenu([x[0] for x in symptoms], textprompt=texts[main][\"symptoms\"].format(name=person.name))\n person.symptoms = list([symptoms[index][1] for index in uindexes])\n\nhealthparams = [(\"Age\", getAge), (\"Gender\", getGender), (\"Took a COVID test\", covidTest), (\"Weight\", getWeight), (\"Have/has weak lungs\", hasWeakLungs), (\"Smoking\", getSmoking), (\"Have/has an important disease\", getDiseases), (\"Experience/s illness symptoms\", getSymptoms)]\n\nhealthliveswith = [(\"Age\", getAge), (\"Took a COVID test\", covidTest),\n (\"Have/has an important disease\", getDiseases)]\n\nhealthcompanions = [(\"Took a COVID test\", covidTest), (\"Experiences illness symptoms\", getSymptoms)]\n\n\nclass AGPerson:\n\n def __init__(self, name, onto):\n self.name = name\n self.onto = onto\n self.useronto = None\n self.userclass = self.onto.search_one(iri=\"*User\")\n self.age = None\n self.gender = None\n self.lungs = None\n self.smoking = None\n self.weight = None\n self.covidtest = None\n self.diseases = None\n self.symptoms = None\n self.travelvia = None\n self.trans = None\n self.pastTransps = []\n self.gears = []\n\n def updateTransps(self):\n if (self.trans is not None) and (self.trans.toOnto() is not None):\n self.useronto.isTravellingVia = []\n self.useronto.isTravellingVia.append(self.trans.toOnto())\n\n self.useronto.hasTravelledVia = []\n for element in self.pastTransps:\n if element.toOnto() is not None:\n self.useronto.hasTravelledVia.append(element.toOnto())\n\n def toOnto(self):\n if self.useronto is not None:\n return self.useronto\n self.useronto = self.userclass(self.name, namespace=self.onto)\n elements = [self.age, self.gender, self.lungs, self.smoking, self.weight, self.covidtest]\n for element in elements:\n if element is None:\n continue\n ontoel = self.onto.search_one(iri=\"*\" + element)\n self.useronto.hasHealth.append(ontoel)\n if self.diseases is not None:\n for disease in self.diseases:\n ontoel = self.onto.search_one(iri=\"*\" + disease)\n self.useronto.hasHealth.append(ontoel)\n if self.symptoms is not None:\n for symptom in self.symptoms:\n ontoel = self.onto.search_one(iri=\"*\" + symptom)\n self.useronto.hasHealth.append(ontoel)\n \n\n def linkLivesWith(self, people):\n for person in people:\n person.toOnto()\n self.useronto.livesWith.append(person.toOnto())\n\n def updateGears(self):\n for gear in self.gears:\n self.useronto.hasProtectiveGear.append(gear)\n\ndef extractPerson(main=False, onto=None, functType=None, name=None, time=\"present\"):\n\n if onto is None:\n raise Exception(\"Parameters found None\")\n\n if main and functType is None:\n usernametext = \"Alright! Tell me about yourself. What is your name?: \"\n healthparamsaux = healthparams\n elif functType == \"liveswith\":\n usernametext = texts[main][\"liveswithintroduce\"].format(name=name)\n healthparamsaux = healthliveswith\n main = False\n elif functType == \"companions\":\n usernametext = texts[main][\"companionsintroduce\"]\n healthparamsaux = healthcompanions\n main = False\n else:\n pass#debug\n\n username = input(usernametext)\n person = AGPerson(username, onto)\n if username in ag.globalAgent().people:\n name = renameUser(username, ag.globalAgent().people.keys())\n if name is None:\n return ag.globalAgent().people[name]\n person.name = name\n ag.globalAgent().addPerson(person)\n\n if main:\n userparamstext = \"What else could be of interest about you? This data will help me give you a better analysis.\"\n else:\n userparamstext = \"What else could be of interest about \" + username + \"? This data will help me give you a better analysis.\"\n \n while(True):\n clear()\n print(userparamstext)\n\n uindex = userMenu(list(x[0] for x in healthparamsaux)+[\"That's enough data.\"])\n if uindex == len(healthparamsaux):\n break\n else:\n clear()\n healthparamsaux[uindex][1](main, person)\n if uindex == len(healthparamsaux)-1:\n healthparamsaux = healthparamsaux[:uindex]\n elif uindex == 0:\n healthparamsaux = healthparamsaux[uindex+1:]\n else:\n healthparamsaux = healthparamsaux[:uindex] + healthparamsaux[uindex+1:]\n\n if functType != \"liveswith\":\n liveswith = extractLivingwith(main=main, person=person, onto=onto)\n person.toOnto()\n if liveswith is not None:\n person.linkLivesWith(liveswith)\n gears = extractProtectionGear(main=main, onto=onto, personname=person.name, placename=name)\n if gears is not None:\n person.gears = gears\n person.updateGears()\n\n clear()\n while(True):\n resp = input(texts[main][\"pastactivityyesno\"].format(name=person.name))\n if resp.lower() == \"no\":\n break\n elif resp.lower() == \"yes\":\n clear()\n pastActivities = AC.extractActivity(main=main, entranceText=texts[main][\"pastactivitytell\"].format(name=person.name), onto=onto, locations=[\"Bookshop\", \"Boutique\", \"Cafe\", \"Library\", \"Restaurant\", \"Shop\", \"Stadium\"], time=\"past\", agent=person)\n clear()\n else:\n clear()\n print(\"Please introduce yes or no.\")\n\n person.toOnto()\n return person\n\ndef renameUser(username, names):\n resp = input(\"Mmm... Is this person the same \" + username + \" you mentioned before? (yes/no): \")\n while(True):\n if resp.lower() == \"yes\":\n return None\n elif resp.lower() == \"no\":\n break\n resp = input(\"Please answer yes or no: \")\n clear()\n print(\"I see, in that case, we're gonna have to name them something different. What do you want to name this new \" + username + \"?: \")\n resp = input(\"Answer: \")\n while(resp in names):\n clear()\n print(\"You already told me about someone named!\")\n resp = input(\"What do you want to name this new \" + username + \"?: \")\n return resp\n\ndef extractLivingwith(main=False, onto=None, person=None):\n clear()\n liveswith = []\n while(True):\n resp = input(texts[main][\"liveswith\"].format(name=person.name))\n if resp.lower() == \"yes\":\n break\n elif resp.lower() == \"no\":\n return None\n else:\n print(\"Please answer yes or no\")\n\n while(True):\n clear()\n p = extractPerson(main=main, onto=onto, functType=\"liveswith\", name=person.name)\n liveswith.append(p)\n while(True):\n clear()\n resp = input(texts[main][\"furtherliveswith\"].format(name=person.name))\n if resp.lower() == \"yes\":\n break\n elif resp.lower() == \"no\":\n return liveswith\n else:\n print(\"Please answer yes or no\")\n","sub_path":"agent/Person.py","file_name":"Person.py","file_ext":"py","file_size_in_byte":11880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"293703579","text":"# -*- coding: utf-8 -*-\n\nimport rospy\nimport quad_srvs.srv as quad_srvs\nimport std_msgs.msg as std_msgs\nimport std_srvs.srv as std_srvs\n\n\nimport yaml\n\ndef upload_parameters(param_dict, quad_name):\n print('Uploading Parameters')\n for param_name in param_dict.keys():\n param_request = quad_srvs.OnboardParameterRequest()\n param_request.parameter.param_id = param_name\n param_request.parameter.param_value = param_dict[param_name]\n param_write_client = rospy.ServiceProxy('/'+quad_name+'/write_onboard_parameter', quad_srvs.OnboardParameter )\n reply = param_write_client( param_request ) \n print( '\\t%s:\\t%.3f'% (param_name, reply.parameter.param_value ))\n\ndef download_parameters( quad_name):\n rpg_mixer_parameters = ['RPG_MIN_THRUST',\n 'RPG_MAX_THRUST',\n 'RPG_YAW_ASSURED',\n 'RPG_MASS',\n 'RPG_L',\n 'RPG_KAPPA']\n \n rpg_power_mapping_parameters = ['RPG_ARM_THRUST_N',\n 'RPG_MIN_CMD',\n 'RPG_MIN_CMD_SPIN',\n 'RPG_MAX_CMD',\n 'RPG_THRUST_MAP_A',\n 'RPG_THRUST_MAP_B',\n 'RPG_THRUST_MAP_C']\n \n rpg_controller_parameters = ['RPG_RCONT_IXX',\n 'RPG_RCONT_IYY',\n 'RPG_RCONT_IZZ',\n 'RPG_RCONT_K_PQ',\n 'RPG_RCONT_K_R',\n 'MAX_YAW_RATE_ERR',\n 'RPG_ATTCONT_KRP']\n \n rpg_att_est_parameters = ['ATT_EST_K_CORR']\n \n parameters = rpg_mixer_parameters+rpg_power_mapping_parameters + rpg_controller_parameters + rpg_att_est_parameters\n param_dict = {}\n print('Downloading Parameters')\n\n for param_name in parameters:\n param_request = quad_srvs.OnboardParameterRequest()\n param_request.parameter.param_id = param_name\n service_client = rospy.ServiceProxy('/'+quad_name+'/read_onboard_parameter', quad_srvs.OnboardParameter )\n reply = service_client( param_request ) \n param_dict[param_name] = reply.parameter.param_value\n print( '\\t%s:\\t%.3f'% (param_name, reply.parameter.param_value ))\n\n return param_dict \n\ndef dump_to_yaml_file(param_dict, file_name):\n f = open(file_name, 'w+')\n yaml.dump(param_dict, f, default_flow_style = False)\n f.close\n\ndef load_from_yaml_file(file_name):\n f = open(file_name)\n param_dict = yaml.load(f)\n f.close\n return param_dict\n\ndef dump_parameters_to_yaml_file(quad_name, file_name):\n param_dict = download_parameters( quad_name )\n dump_to_yaml_file(param_dict, file_name)\n \ndef load_parameters_from_yaml_file(quad_name, file_name):\n param_dict = load_from_yaml_file(file_name)\n param_dict['RPG_GAMMA_1'] = 1.0\n param_dict['RPG_GAMMA_2'] = 1.0\n param_dict['RPG_GAMMA_3'] = 1.0\n param_dict['RPG_GAMMA_4'] = 1.0\n upload_parameters(param_dict, quad_name)\n\n\ndef save_parameters_to_vehicle(quad_name):\n save_to_vehicle_client = rospy.ServiceProxy('/'+quad_name+'/save_onboard_parameters_to_flash', std_srvs.Empty )\n save_to_vehicle_client( std_srvs.EmptyRequest() )\n\n","sub_path":"quadrotors/parameters/parameter_dumper_lib.py","file_name":"parameter_dumper_lib.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172448518","text":"'''\nIK/FK limb class\n'''\n\n## MAYA MODULES ##\nimport maya.cmds as mc\n\n## CUSTOM MODULES ##\nfrom . import fkChain, ikChain, jointChain\nreload(fkChain)\nreload(ikChain)\nreload(jointChain)\n\n\nclass Limb(object):\n def __init__(self,\n prefix='c',\n name='limb',\n color='auto',\n posList=([0, 0, 0])\n ):\n\n self.prefix = prefix\n self.name = '{0}'.format(name)\n self.color = color\n self.posList = posList\n\n self.jntchain = None\n self.fkchain = None\n self.ikchain = None\n\n def createTemplate(self):\n self.jntchain = jointChain.JntChain(posList=self.posList,\n prefix=self.prefix, name=self.name)\n self.jntchain.createTemplate()\n\n def build(self):\n # create joints from pos list from template locs\n self.posList = [mc.xform(loc, q=1, ws=1, t=1)\n for loc in self.jntchain.locs]\n\n # build chains\n # init fk and ik chains\n self.fkchain = fkChain.FKChain(\n posList=self.posList, prefix=self.prefix, name=self.name)\n self.ikchain = ikChain.IKChain(\n posList=self.posList, prefix=self.prefix, name=self.name)\n\n # build\n self.jntchain.build()\n self.fkchain.build()\n self.ikchain.build()\n","sub_path":"modules/limb.py","file_name":"limb.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619732121","text":"#!/usr/bin/env python3\n\nfrom sys import argv\nimport pathlib\nimport models\n\ndef help():\n \"Initialize icfpc in your current directory\"\n \"Creates ./.icfp/ directory with database.\"\n\ndef create_dir():\n p = pathlib.Path(\"./.icfpc/\")\n if not p.exists():\n p.mkdir()\n\ndef create_subdirs():\n for s in [\"./.icfpc/solutions/\"]:\n p = pathlib.Path(s)\n if not p.exists():\n p.mkdir()\n\ndef create_db():\n models.connect()\n models.create_tables()\n models.close()\n\ndef main():\n create_dir()\n create_subdirs()\n create_db()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"meta/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"225144986","text":"import requests\nimport datetime\nfrom .models import *\nAPI_URL=\"https://account.netpap.co.ke\"\nclass LocalPermissionClass:\n def checkIfWatcher(self,code):\n\n w=Watchers.objects.filter(unique_code=code)\n if w.exists():\n return w\n else:\n return False\n def checkExpiry(self,w):\n current_tym=datetime.datetime.now()\n\n w=w.filter(code_expiration__gt=current_tym)\n if w.exists():\n return True #still active\n else:\n return False\n def checkCount(self,w):\n print(w[0].paid_count)\n print(w[0].count)\n if w[0].count>=w[0].paid_count:\n return False\n else:\n return True\n def storeLocal(self,code,expiration_date,count):\n \n \n\n expiration_date=datetime.datetime.strptime(expiration_date,\"%Y-%m-%d %H:%M:%S\")\n \n\n w=Watchers()\n w.unique_code=code\n w.paid_count=count\n w.code_expiration = expiration_date\n w.save()\n return True\n\nclass RemotePermissionClass:\n\n\n def verify_code(self,code):\n\n r=requests.get(API_URL+\"/mobflix/code/search/\"+code)\n\n a=r.json()\n if \"success\" in a['status']:\n LocalPermissionClass().storeLocal(code,a['message']['expire_date'],a['message']['paid_count'])\n print(a)\n print (\"successful\")\n return a\n else:\n print (\"Not successful\")\n print(a)\n print(\"remote\")\n return a\n","sub_path":"content/mobflixPermissions.py","file_name":"mobflixPermissions.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"189269430","text":"#aflarea celui mai mare divizor comun\ndef gcd(a, b):\n while (b != 0):\n remainder = a % b\n a = b\n b = remainder\n return a\n#aflarea celuilalt element din factorizarea unui numar format din inmultirea a doua numere prime\n#prin impartirea numarului initial la primul factor prin gasit in numar\ndef factorizare(numar, factorPrim1):\n factorPrim2=numar/factorPrim1\n print(\"Factorizarea numarului\", numar, \" este: \", factorPrim1, \" si \", factorPrim2)\n#algoritmul lui Pollard\n#numar = numarul ca carui factorizare se doreste a afla\n#bound = o limita pana la care sa se faca verificarea de fatorizare\n#factorExpansiune = se extinde bound-ul in cazul in care counterul a ajuns deja la limita superioara a bound-ului\n# si nu s-a gasit inca un factor prim in factorizarea numarului ales\ndef Pollard(numar, bound, factorExpansiune):\n expansiune=False\n counter=1\n var=2\n\n while(counter= birds:\n\t\t\tfed_birds = birds\n\t\t\tportions -= birds\n\n\t\telif portions > old_birds:\n\t\t\tfed_birds = old_birds + (portions-old_birds) \n\t\t\tportions -= birds\n\n\t\t# when the number of old_birds is greater then potions no new birds will be fed \n\t\t# therefore the number of fed birds can be returned\n\t\telse:\n\t\t\tprint(fed_birds)\n\t\t\treturn fed_birds\n\n\t\tminute += 1 \n\t\told_birds = birds\n\t\t#the number of new birds arriving is equal to the number of minutes that has passed\n\t\tbirds += minute \n\t\t\n\t\t\n\t\tprint('fed_birds -', fed_birds)\n\t\tprint('birds -----', birds)\n\t\tprint('old_birds -', old_birds)\n\t\tprint('portions --',portions)\n\t\tprint()\n\n\n\nfeed_pigeons(117)\n#print('-------------------')\n#feed_pigeons(10)\n#print('-------------------')\n#feed_pigeons(17)\n","sub_path":"home/feed_pigeons.py","file_name":"feed_pigeons.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"14260019","text":"import numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import f1_score, make_scorer\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nimport random\r\n\r\n\r\ndef load_pts(csv_name):\r\n data = np.asarray(pd.read_csv(csv_name, header=None))\r\n\r\n X = data[:, 0:2]\r\n y = data[:, 2]\r\n\r\n plt.scatter(X[np.argwhere(y == 0).flatten(), 0], X[np.argwhere(y == 0).flatten(), 1], c='blue',\r\n edgecolor='k', s=50)\r\n plt.scatter(X[np.argwhere(y == 1).flatten(), 0], X[np.argwhere(y == 1).flatten(), 1], c='red',\r\n edgecolor='k', s=50)\r\n plt.xlim(-2.05, 2.05)\r\n plt.ylim(-2.05, 2.05)\r\n plt.grid(False)\r\n plt.tick_params(axis='x', which='both', bottom=False, top=False)\r\n\r\n return X, y\r\n\r\n\r\nX, y = load_pts('data.csv')\r\nplt.show()\r\n\r\nrandom.seed(42)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\r\n\r\nclf = DecisionTreeClassifier(random_state=42)\r\n\r\nclf.fit(X_train, y_train)\r\n\r\ntrain_predictions = clf.predict(X_train)\r\ntest_predictions = clf.predict(X_test)\r\n\r\n\r\ndef plot_model(X, y, clf):\r\n\r\n plt.scatter(X[np.argwhere(y == 0).flatten(), 0], X[np.argwhere(y == 0).flatten(), 1], c='blue',\r\n edgecolor='k', s=50)\r\n plt.scatter(X[np.argwhere(y == 1).flatten(), 0], X[np.argwhere(y == 1).flatten(), 1], c='red',\r\n edgecolor='k', s=50)\r\n plt.xlim(-2.05, 2.05)\r\n plt.ylim(-2.05, 2.05)\r\n plt.grid(False)\r\n plt.tick_params(axis='x', which='both', bottom=False, top=False)\r\n\r\n r = np.linspace(-2.1, 2.1, 300)\r\n s, t = np.meshgrid(r, r)\r\n s = np.reshape(s, (np.size(s), 1))\r\n t = np.reshape(t, (np.size(t), 1))\r\n h = np.concatenate((s, t), 1)\r\n\r\n z = clf.predict(h)\r\n\r\n s = s.reshape((np.size(r), np.size(r)))\r\n t = t.reshape((np.size(r), np.size(r)))\r\n z = z.reshape((np.size(r), np.size(r)))\r\n\r\n plt.contourf(s, t, z, colors=['blue', 'red'], alpha=0.2, levels=range(-1, 2))\r\n if len(np.unique(z)) > 1:\r\n plt.contour(s, t, z, colors='k', linewidths=2)\r\n plt.show()\r\n\r\n\r\nplot_model(X, y, clf)\r\nprint('The Training F1 Score is', f1_score(train_predictions, y_train))\r\nprint('The Testing F1 Score is', f1_score(test_predictions, y_test))\r\n\r\nclf = DecisionTreeClassifier(random_state=42)\r\n\r\nparameters = {'max_depth': [2, 4, 6, 8, 10], 'min_samples_leaf': [2, 4, 6, 8, 10],\r\n 'min_samples_split': [2, 4, 6, 8, 10]}\r\n\r\nscorer = make_scorer(f1_score)\r\n\r\ngrid_obj = GridSearchCV(clf, parameters, scoring=scorer, cv=3)\r\n\r\ngrid_fit = grid_obj.fit(X_train, y_train)\r\n\r\nbest_clf = grid_fit.best_estimator_\r\n\r\nbest_clf.fit(X_train, y_train)\r\n\r\nbest_train_predictions = best_clf.predict(X_train)\r\nbest_test_predictions = best_clf.predict(X_test)\r\nprint('The training F1 Score is', f1_score(best_train_predictions, y_train))\r\nprint('The testing F1 Score is', f1_score(best_test_predictions, y_test))\r\n\r\nplot_model(X, y, best_clf)\r\n\r\nprint(best_clf)\r\n\r\n\r\n","sub_path":"0_Supervised_Learning/GridSearch/grid_search.py","file_name":"grid_search.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"408628358","text":"from __future__ import print_function\nimport zipfile\nimport os\n\nimport torchvision.transforms as transforms\n\n# data augmentation for training and test time\n# Resize all images to 32 * 32 and normalize them to mean = 0 and standard-deviation = 1 based on statistics collected from the training set\n\ndata_transforms = transforms.Compose([\n\ttransforms.Resize((64, 64)),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\n\n\ndef initialize_data(folder):\n train_zip = folder + '/train_images.zip'\n test_zip = folder + '/test_images.zip'\n if not os.path.exists(train_zip) or not os.path.exists(test_zip):\n raise(RuntimeError(\"Could not find \" + train_zip + \" and \" + test_zip\n + ', please download them from https://www.kaggle.com/c/nyu-cv-fall-2017/data '))\n \n # extract train_data.zip to train_data\n train_folder = folder + '/train_images'\n if not os.path.isdir(train_folder):\n print(train_folder + ' not found, extracting ' + train_zip)\n zip_ref = zipfile.ZipFile(train_zip, 'r')\n zip_ref.extractall(folder)\n zip_ref.close()\n \n # extract test_data.zip to test_data\n test_folder = folder + '/test_images'\n if not os.path.isdir(test_folder):\n print(test_folder + ' not found, extracting ' + test_zip)\n zip_ref = zipfile.ZipFile(test_zip, 'r')\n zip_ref.extractall(folder)\n zip_ref.close()\n \n # make validation_data by using images 00000*, 00001* and 00002* in each class\n val_folder = folder + '/val_images'\n if not os.path.isdir(val_folder):\n print(val_folder + ' not found, making a validation set')\n os.mkdir(val_folder)\n for dirs in os.listdir(train_folder):\n if dirs.startswith('000'):\n os.mkdir(val_folder + '/' + dirs)\n for f in os.listdir(train_folder + '/' + dirs):\n if f.startswith('00000') or f.startswith('00001') or f.startswith('00002'):\n # move file to validation folder\n os.rename(train_folder + '/' + dirs + '/' + f, val_folder + '/' + dirs + '/' + f)\n\n\n#Additional transformations used for data augmentation\n\ndata_rotate = transforms.Compose([\n\ttransforms.Resize((64, 64)),\n transforms.RandomRotation(15),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\n\ndata_shear = transforms.Compose([\n\ttransforms.Resize((64, 64)),\n transforms.RandomAffine(degrees = 15,shear=2),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\ndata_translate = transforms.Compose([\n\ttransforms.Resize((64, 64)),\n transforms.RandomAffine(degrees = 15,translate=(0.1,0.1)),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\ndata_center = transforms.Compose([\n\ttransforms.Resize((72, 72)),\n transforms.CenterCrop(64),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\ndata_brightnesstransform = transforms.Compose([\n\ttransforms.Resize((64, 64)),\n transforms.ColorJitter(brightness=1),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\ndata_saturationtransform = transforms.Compose([\n\ttransforms.Resize((64, 64)),\n transforms.ColorJitter(saturation=1),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\ndata_huetransform = transforms.Compose([\n\ttransforms.Resize((64, 64)),\n transforms.ColorJitter(hue=0.25),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\ndata_contrasttransform = transforms.Compose([\n\ttransforms.Resize((64, 64)),\n transforms.ColorJitter(contrast=1),\n transforms.ToTensor(),\n #transforms.Normalize((0.3337, 0.3064, 0.3171), ( 0.2672, 0.2564, 0.2629))\n])\n\n\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"91866274","text":"import struct\nimport random\nimport numpy\nfrom obj import Obj \nfrom collections import namedtuple\n\n# implementacion de \"vectores\" para manejar menos variables en funciones y tener mejor orden de coordenadas\nV2 = namedtuple('Point2', ['x', 'y'])\nV3 = namedtuple('Point3', ['x', 'y', 'z'])\n\ndef sum(v0, v1):\n # suma dos vectores de 3 elementos \n return V3(v0.x + v1.x, v0.y + v1.y, v0.z + v1.z)\n\ndef sub(v0, v1):\n # resta dos vectores de 3 elementos\n return V3(v0.x - v1.x, v0.y - v1.y, v0.z - v1.z)\n\ndef mul(v0, k):\n # multiplica un vector de 3 elementos por una constante\n return V3(v0.x * k, v0.y * k, v0.z *k)\n\ndef dot(v0, v1):\n # reliza el producto punto de dos vectores de 3 elementos \n # el resultado es un escalar\n return v0.x * v1.x + v0.y * v1.y + v0.z * v1.z\n\ndef cross(v1, v2):\n return V3(\n v1.y * v2.z - v1.z * v2.y,\n v1.z * v2.x - v1.x * v2.z,\n v1.x * v2.y - v1.y * v2.x,\n )\n\ndef length(v0):\n # devuelve el tamaño (escalar) del vector\n return (v0.x**2 + v0.y**2 + v0.z**2)**0.5\n\ndef norm(v0):\n #calcula la normal de un vector de 3 elementos\n v0length = length(v0)\n\n if not v0length:\n return V3(0, 0, 0)\n\n return V3(v0.x/v0length, v0.y/v0length, v0.z/v0length)\n\ndef bbox(*vertices):\n # Se reciben *n vectores de 2 elementos para encontrar los x,y maximos y minimos\n # para poder hacer la boundingbox, es decir cubrir el poligono\n xs = [ vertex.x for vertex in vertices ]\n ys = [ vertex.y for vertex in vertices ]\n\n return (max(xs), max(ys), min(xs), min(ys))\n\ndef barycentric(A, B, C, P):\n # Este algoritmo de numeros baricentricos sirve para llena un poligono\n # Parametros: 3 vectores de 2 elementos y un punto\n # Return: 3 coordinadas baricentricas del punto segun el triangulo formado a partir de los vectores\n cx, cy, cz = cross(\n V3(B.x - A.x, C.x - A.x, A.x - P.x), \n V3(B.y - A.y, C.y - A.y, A.y - P.y)\n )\n\n if abs(cz) < 1:\n return -1, -1, -1 # no es un triangulo de verdad, no devuelve nada afuera\n\n # [cx cy cz] == [u v 1]\n\n u = cx/cz\n v = cy/cz\n w = 1 - (cx + cy)/cz\n\n return w, v, u\n\ndef char(c):\n return struct.pack('=c', c.encode('ascii'))\n\ndef word(w):\n return struct.pack('=h', w)\n\ndef dword(d):\n return struct.pack('=l', d)\n\ndef color(r, g, b):\n return bytes([b, g, r])\n\n\nBLACK = color(0,0,0)\nWHITE = color(255,255,255)\nRED = color(255, 0, 0)\n\n\n# ===============================================================\n# Render BMP file\n# ===============================================================\n\nclass Render(object):\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.current_color = WHITE\n self.glClear()\n\n def glClear(self):\n self.buffer = [\n [BLACK for x in range(self.width)] \n for y in range(self.height)\n ]\n self.zbuffer = [\n [-float('inf') for x in range(self.width)] \n for y in range(self.height)\n ]\n\n def finish(self, filename):\n f = open(filename, 'bw')\n\n # File header (14 bytes)\n f.write(char('B'))\n f.write(char('M'))\n f.write(dword(14 + 40 + self.width * self.height * 3))\n f.write(dword(0))\n f.write(dword(14 + 40))\n\n # Image header (40 bytes)\n f.write(dword(40))\n f.write(dword(self.width))\n f.write(dword(self.height))\n f.write(word(1))\n f.write(word(24))\n f.write(dword(0))\n f.write(dword(self.width * self.height * 3))\n f.write(dword(0))\n f.write(dword(0))\n f.write(dword(0))\n f.write(dword(0))\n\n # Pixel data (width x height x 3 pixels)\n for x in range(self.height):\n for y in range(self.width):\n f.write(self.buffer[x][y])\n\n f.close()\n\n def set_color(self, color):\n self.current_color = color\n\n def glColor(self, r=1, g=1, b=1):\n red = round(r*255)\n green = round(g*255)\n blue = round(g*255)\n self.current_color = color(red, green, blue)\n\n def point(self, x, y):\n try:\n self.buffer[y][x] = self.current_color\n except:\n # si esta \"out of index\"\n pass\n \n def glLine(self, x0, y0, x1, y1):\n # Funciones para aplicar la ecuacion de la recta y dibujar lineas con valores mayores de -1 a 1\n x1, y1 = x0, y0\n x2, y2 = x1, y1\n\n dy = abs(y2 - y1)\n dx = abs(x2 - x1)\n steep = dy > dx\n\n if steep:\n x1, y1 = y1, x1\n x2, y2 = y2, x2\n\n if x1 > x2:\n x1, x2 = x2, x1\n y1, y2 = y2, y1\n\n dy = abs(y2 - y1)\n dx = abs(x2 - x1)\n\n offset = 0\n threshold = dx\n\n y = y1\n for x in range(x1, x2 + 1):\n if steep:\n self.point(y, x)\n else:\n self.point(x, y)\n \n offset += dy * 2\n if offset >= threshold:\n y += 1 if y1 < y2 else -1\n threshold += dx * 2\n\n\n def shader(self, x, y):\n if(y>=275 and y<=279 and x>=435 and x%2==0):\n return color(57,79,198) #empiza parte de abajo\n elif(y>=280 and y<=285 and x>=430 and x%2==0):\n return color(57,79,198)\n elif(y>=286 and y<=290 and x>=425 and x%2==0):\n return color(57,79,198)\n elif(y>=291 and y<=295 and x>=420 and x%2==0):\n return color(57,79,198)\n elif(y>=296 and y<=300 and x>=415 and x%2==0):\n return color(57,79,198)\n elif(y>=304 and y<=306 and x>=427 and x%2==0):\n return color(250,250,250) #en medio\n elif(y>=307 and y<=325 and x<=250):\n return color(69,111,254) #empieza parte de arriba\n elif(y>=420 and y<=460):\n return color(57,79,198)\n elif(y>=400 and y<=320 and x>=200):\n return color(250,250,250)\n else:\n return color(69,111,254)\n\n def triangle(self, A, B, C):\n xmax, ymax, xmin, ymin = bbox(A, B, C)\n\n for x in range(xmin, xmax + 1):\n for y in range(ymin, ymax + 1):\n P = V2(x, y)\n w, v, u = barycentric(A, B, C, P)\n if w < 0 or v < 0 or u < 0: # 0 es valido y estan el la orilla\n #el punto esta afuera y no se dibuja\n continue\n #se calcula la profunidad en z de cada punto\n z = A.z * w + B.z * u + C.z * v\n #self.current_color = self.shader(x, y, z, intesidad)\n try:\n if z > self.zbuffer[x][y]:\n self.point(x,y)\n self.zbuffer[x][y] = z\n except:\n pass\n \n def load(self, filename, translate=(0, 0, 0), scale=(1, 1, 1)):\n model = Obj(filename)\n\n light = V3(-0.5, 0.7, 0.7)\n \n for face in model.faces:\n vcount = len(face)\n\n if vcount == 3:\n f1 = face[0][0] - 1\n f2 = face[1][0] - 1\n f3 = face[2][0] - 1\n\n v1 = V3(model.vertices[f1][0], model.vertices[f1][1], model.vertices[f1][2])\n v2 = V3(model.vertices[f2][0], model.vertices[f2][1], model.vertices[f2][2])\n v3 = V3(model.vertices[f3][0], model.vertices[f3][1], model.vertices[f3][2])\n\n x1 = round((v1.x * scale[0]) + translate[0])\n y1 = round((v1.y * scale[1]) + translate[1])\n z1 = round((v1.z * scale[2]) + translate[2])\n\n x2 = round((v2.x * scale[0]) + translate[0])\n y2 = round((v2.y * scale[1]) + translate[1])\n z2 = round((v2.z * scale[2]) + translate[2])\n\n x3 = round((v3.x * scale[0]) + translate[0])\n y3 = round((v3.y * scale[1]) + translate[1])\n z3 = round((v3.z * scale[2]) + translate[2])\n\n A = V3(x1, y1, z1)\n B = V3(x2, y2, z2)\n C = V3(x3, y3, z3)\n\n # Shading\n xp = min([x1, x2, x3])\n yp = min([y1, y2, y3])\n colorShader = self.shader(xp, yp)\n\n normal = norm(cross(sub(B, A), sub(C, A)))\n intensity = dot(normal, norm(light))\n colors = []\n for i in colorShader:\n if i * intensity > 0:\n colors.append(round(i*intensity))\n else:\n colors.append(10)\n colors.reverse()\n\n self.current_color = color(colors[0], colors[1], colors[2])\n self.triangle(A, B, C)\n\n \"\"\"normal = norm(cross(sub(B, A), sub(C, A)))\n intensity = dot(normal, light)\n grey = round(200*intensity)\n grey = round(intensity)\n if grey < 0:\n continue \n\n self.current_color = color(grey, grey, grey)\n\n self.triangle(A, B, C, grey)\"\"\"\n\n else:\n f1 = face[0][0] - 1\n f2 = face[1][0] - 1\n f3 = face[2][0] - 1\n f4 = face[3][0] - 1 \n\n v1 = V3(model.vertices[f1][0], model.vertices[f1][1], model.vertices[f1][2])\n v2 = V3(model.vertices[f2][0], model.vertices[f2][1], model.vertices[f2][2])\n v3 = V3(model.vertices[f3][0], model.vertices[f3][1], model.vertices[f3][2])\n v4 = V3(model.vertices[f4][0], model.vertices[f4][1], model.vertices[f4][2])\n\n x1 = round((v1.x * scale[0]) + translate[0])\n y1 = round((v1.y * scale[1]) + translate[1])\n z1 = round((v1.z * scale[2]) + translate[2])\n\n x2 = round((v2.x * scale[0]) + translate[0])\n y2 = round((v2.y * scale[1]) + translate[1])\n z2 = round((v2.z * scale[2]) + translate[2])\n\n x3 = round((v3.x * scale[0]) + translate[0])\n y3 = round((v3.y * scale[1]) + translate[1])\n z3 = round((v3.z * scale[2]) + translate[2])\n\n x4 = round((v4.x * scale[0]) + translate[0])\n y4 = round((v4.y * scale[1]) + translate[1])\n z4 = round((v4.z * scale[2]) + translate[2])\n\n A = V3(x1, y1, z1)\n B = V3(x2, y2, z2)\n C = V3(x3, y3, z3)\n D = V3(x4, y4, z4)\n \n # Shading\n xp = min([x1, x2, x3, x4])\n yp = min([y1, y2, y3, y4])\n colorShader = self.shader(xp, yp)\n\n normal = norm(cross(sub(B, A), sub(C, A)))\n intensity = dot(normal, norm(light))\n colors = []\n for i in colorShader:\n if i * intensity > 0:\n colors.append(round(i*intensity))\n else:\n colors.append(10)\n self.current_color = color(colors[0], colors[1], colors[2])\n colors.reverse()\n\n self.triangle(A, B, C)\n self.triangle(A, C, D)\n\n \"\"\"normal = norm(cross(sub(B, A), sub(C, A))) # no necesitamos dos normales!!\n intensity = dot(normal, light)\n grey = round(intensity)\n if grey < 0:\n continue # dont paint this face\n\n #self.current_color = color(grey, grey, grey)\n self.triangle(A, B, C, grey) \n\n self.triangle(A, D, C, grey)\"\"\"\n\n\n ","sub_path":"gl.py","file_name":"gl.py","file_ext":"py","file_size_in_byte":10222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401513407","text":"def pi100pe ():\r\n\tx = input(\"Introduza um número: \")\r\n\ty = input(\"Introduza ou o mesmo número ou um número diferente: \")\r\n\tif x == y:\r\n\t\tprint(\"Paravéns, és vué fixe!!!\")\r\n\telse:\r\n\t\tprint(\"És um ganda vurro!!!\")\r\ndef errocrasso ():\r\n\ta = input(\"Introduza um número: \")\r\n\tb = input(\"Introduza ou um número divisor do anterior ou um que não seja divisor: \")\r\n\tif a % b:\r\n\t\tprint(\"Mereces um viscoito!!\")\r\n\telse:\r\n\t\tprint(\"És um cócó!!\")\r\n__version__ = '0.1'","sub_path":"xmodules.py","file_name":"xmodules.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"589964942","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('questions', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Topics',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('topic_title', models.CharField(max_length=30, unique=True)),\n ('topic_description', models.TextField(max_length=500)),\n ('questions_in_topic', models.ManyToManyField(to='questions.Question', related_name='topics_included')),\n ],\n ),\n ]\n","sub_path":"quora/topic/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"546143780","text":"import requests\nimport bs4\n\nres = requests.get('https://www.thegoldbugs.com/blog')\nsoup = bs4.BeautifulSoup(res.text,'lxml')\nblog = soup.select('pre')\ntext = blog[0]\nblog_text = text.contents[0]\nnew = blog_text.split('-----')[1:]\nfinal = ''\nfor each in new:\n final = final + each[0]\nprint(final)\n\n\n\n","sub_path":"pgm/goldbug.py","file_name":"goldbug.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"162820268","text":"from gevent.lock import BoundedSemaphore\nfrom . import Manager\nfrom .utils import LcApiException\nfrom .utils import parallelExec\n\nimport uuid\nimport json\nimport yaml\nimport gevent\nimport time\nimport sys\n\nclass Replay( object ):\n '''Interface to query historical sensor data in Insight with specific D&R rules.'''\n\n def __init__( self, manager, maxTimeWindow = ( 60 * 60 * 24 * 1 ), maxConcurrent = 10, isInteractive = False ):\n '''Create a Replay manager object.\n\n Args:\n manager (limacharlie.Manager): manager providing authentication.\n maxTimeWindow (int): number of seconds to split sensor data during analysis.\n maxConcurrent (int): number of sensors windows to process in parallel.\n isInteractive (bool): if True, display progress updates to standard out.\n '''\n\n self._lc = manager\n self._apiURL = None\n self._maxTimeWindow = maxTimeWindow\n self._maxConcurrent = maxConcurrent\n self._replayURL = self._lc.getOrgURLs()[ 'replay' ]\n\n self._isInteracive = isInteractive\n self._statusMutex = BoundedSemaphore()\n self._queryPending = 0\n self._sensorPending = 0\n self._limitEvent = None\n self._imitEval = None\n self._queryStartedAt = None\n if self._isInteracive:\n self._queryStartedAt = time.time()\n gevent.spawn_later( 0, self._reportStatus )\n\n def _reportStatus( self ):\n timing = 1\n flag = self._isInteracive\n if isinstance( self._isInteracive, ( tuple, list ) ):\n timing, flag = self._isInteracive\n with self._statusMutex:\n if self._queryStartedAt is None:\n # Indicating the query is done, don't print.\n return\n if flag is True:\n sys.stdout.write( \"\\rSensors pending: %8s, queries pending: %8s, elapsed: %8.2f seconds\" % ( self._sensorPending, self._queryPending, time.time() - self._queryStartedAt ) )\n sys.stdout.flush()\n else:\n # Assuming this is a callback instead.\n flag( self._sensorPending, self._queryPending )\n\n gevent.spawn_later( timing, self._reportStatus )\n\n def scanHistoricalSensor( self, sid, startTime, endTime, ruleName = None, ruleContent = None, isRunTrace = False, limitEvent = None, limitEval = None, isIgnoreState = False ):\n '''Scan a specific sensor's data with a D&R rule.\n\n Args:\n sid (str): sensor ID to scan.\n startTime (int): seconds epoch to start scanning at.\n endTime (int): seconds epoch to stop scanning at.\n ruleName (str): the name of an existing D&R rule to use.\n ruleContent (dict): D&R rule to use to scan, with a \"detect\" key and a \"respond\" key.\n isRunTrace (bool): if True, generate a trace of the evaluation.\n limitEvent (int): approximately limit the number of events evaluated.\n limitEval (int): approximately limit the number of rule evaluations.\n isIgnoreState (bool): if True, parallelize processing of single sensors to increase performance but limit effectiveness of stateful detection.\n\n Returns:\n a dict containing results of the query.\n '''\n windows = []\n\n with self._statusMutex:\n isSingleQuery = False\n if 0 == self._sensorPending:\n isSingleQuery = True\n self._sensorPending = 1\n # Only initialize the limits if we are not called for\n # an org-wide query. Otherwise the caller will have\n # set the limits already.\n self._limitEvent = limitEvent\n self._limitEval = limitEval\n\n try:\n # Split up the total time into windows we can query in parallel.\n if endTime - startTime > self._maxTimeWindow:\n tmpStart = startTime\n while tmpStart < endTime:\n tmpEnd = min( tmpStart + self._maxTimeWindow, endTime )\n windows.append( ( tmpStart, tmpEnd ) )\n tmpStart += self._maxTimeWindow\n else:\n windows = [ ( startTime, endTime ) ]\n\n with self._statusMutex:\n self._queryPending += len( windows )\n\n if isIgnoreState:\n # Just run it all together.\n results = parallelExec( lambda w: self._scanHistoricalSensor( sid, w[ 0 ], w[ 1 ], ruleName = ruleName, ruleContent = ruleContent, isRunTrace = isRunTrace, isIgnoreState = isIgnoreState ), windows, maxConcurrent = self._maxConcurrent )\n else:\n # We need to iterate one at a time and keep passing the state along.\n results = []\n state = None\n for w in windows:\n tmpResult = self._scanHistoricalSensor( sid, w[ 0 ], w[ 1 ], ruleName = ruleName, ruleContent = ruleContent, isRunTrace = isRunTrace, isIgnoreState = isIgnoreState, state = state )\n if 'state' in tmpResult:\n # Extract the state update so we can pass it to the next call.\n state = tmpResult[ 'state' ]\n # Remove the state data from the result.\n del( tmpResult[ 'state' ] )\n results.append( tmpResult )\n finally:\n with self._statusMutex:\n self._sensorPending -= 1\n\n if isSingleQuery:\n with self._statusMutex:\n if self._queryStartedAt is not None:\n self._queryStartedAt = None\n\n return self._rollupResults( results )\n\n def _scanHistoricalSensor( self, sid, startTime, endTime, ruleName = None, ruleContent = None, isRunTrace = False, isIgnoreState = False, state = None ):\n # print( \"Starting query %s-%s for %s\" % ( startTime, endTime, sid ) )\n # qStart = time.time()\n\n resp = None\n\n try:\n if self._apiURL is None:\n # Get the ingest URL from the API.\n self._apiURL = 'https://%s/' % ( self._replayURL, )\n req = {\n 'start' : startTime,\n 'end' : endTime,\n }\n if isRunTrace:\n req[ 'trace' ] = 'true'\n if isIgnoreState is False:\n req[ 'return_state' ] = 'true'\n\n # If limits were reached, short circuit the execution.\n with self._statusMutex:\n if self._limitEvent is not None:\n if 0 >= self._limitEvent:\n return {}\n req[ 'limit_event' ] = str( self._limitEvent )\n if self._limitEval is not None:\n if 0 >= self._limitEval:\n return {}\n req[ 'limit_eval' ] = str( self._limitEval )\n\n body = {}\n if state is not None:\n body[ 'state' ] = state\n if ruleName is not None:\n req[ 'rule_name' ] = ruleName\n elif ruleContent is not None:\n body[ 'rule' ] = ruleContent\n else:\n raise LcApiException( 'no rule specified' )\n\n if 0 == len( body ):\n body = None\n else:\n body = json.dumps( body ).encode()\n\n nRetry = 0\n while True:\n try:\n resp = self._lc._apiCall( 'sensor/%s/%s' % ( self._lc._oid, sid, ),\n 'POST',\n {},\n altRoot = self._apiURL,\n queryParams = req,\n rawBody = body,\n contentType = 'application/json' )\n\n break\n except:\n nRetry += 1\n if nRetry > 5:\n raise\n time.sleep( 2 * nRetry )\n finally:\n with self._statusMutex:\n self._queryPending -= 1\n\n # If there are limits, compute the left-over quota.\n if isinstance( resp, dict ):\n if self._limitEvent is not None:\n self._limitEvent -= resp.get( 'num_events', 0 )\n if self._limitEval is not None:\n self._limitEval -= resp.get( 'num_evals', 0 )\n # print( \"Finished query %s-%s for %s in %s seconds\" % ( startTime, endTime, sid, time.time() - qStart ) )\n\n return resp\n\n def scanEntireOrg( self, startTime, endTime, ruleName = None, ruleContent = None, isRunTrace = False, limitEvent = None, limitEval = None, isIgnoreState = False ):\n '''Scan an entire organization's data with a D&R rule.\n\n Args:\n startTime (int): seconds epoch to start scanning at.\n endTime (int): seconds epoch to stop scanning at.\n ruleName (str): the name of an existing D&R rule to use.\n ruleContent (dict): D&R rule to use to scan, with a \"detect\" key and a \"respond\" key.\n isRunTrace (bool): if True, generate a trace of the evaluation.\n limitEvent (int): approximately limit the number of events evaluated.\n limitEval (int): approximately limit the number of rule evaluations.\n isIgnoreState (bool): if True, parallelize processing of single sensors to increase performance but limit effectiveness of stateful detection.\n\n Returns:\n a dict containing results of the query.\n '''\n sensors = list( self._lc.sensors() )\n\n with self._statusMutex:\n self._sensorPending = len( sensors )\n self._limitEvent = limitEvent\n self._limitEval = limitEval\n\n results = parallelExec( lambda sid: self.scanHistoricalSensor( sid, startTime, endTime, ruleName = ruleName, ruleContent = ruleContent, isRunTrace = isRunTrace, isIgnoreState = isIgnoreState ), sensors, maxConcurrent = self._maxConcurrent )\n\n with self._statusMutex:\n if self._queryStartedAt is not None:\n self._queryStartedAt = None\n\n return self._rollupResults( results )\n\n def scanEvents( self, events, ruleName = None, ruleContent = None, isRunTrace = False, limitEvent = None, limitEval = None ):\n '''Scan the specific events with a D&R rule.\n\n Args:\n events (list): list of events to scan.\n ruleName (str): the name of an existing D&R rule to use.\n ruleContent (dict): D&R rule to use to scan, with a \"detect\" key and a \"respond\" key.\n isRunTrace (bool): if True, generate a trace of the evaluation.\n limitEvent (int): approximately limit the number of events evaluated.\n limitEval (int): approximately limit the number of rule evaluations.\n\n Returns:\n a dict containing results of the query.\n '''\n # qStart = time.time()\n\n with self._statusMutex:\n self._sensorPending = 1\n\n try:\n if self._apiURL is None:\n # Get the ingest URL from the API.\n self._apiURL = 'https://%s/' % ( self._replayURL, )\n req = {}\n body = {\n 'events' : events,\n }\n if ruleName is not None:\n req[ 'rule_name' ] = ruleName\n elif ruleContent is not None:\n body[ 'rule' ] = ruleContent\n else:\n raise LcApiException( 'no rule specified' )\n\n if isRunTrace:\n req[ 'trace' ] = 'true'\n\n if limitEvent is not None:\n req[ 'limit_event' ] = str( limitEvent )\n if limitEval is not None:\n req[ 'limit_eval' ] = str( limitEval )\n\n nRetry = 0\n while True:\n try:\n resp = self._lc._apiCall( 'simulate/%s' % ( self._lc._oid, ),\n 'POST',\n {},\n altRoot = self._apiURL,\n queryParams = req,\n rawBody = json.dumps( body ).encode(),\n contentType = 'application/json' )\n\n break\n except:\n nRetry += 1\n if nRetry > 5:\n raise\n time.sleep( 2 * nRetry )\n finally:\n with self._statusMutex:\n self._queryPending -= 1\n # print( \"Finished query %s-%s for %s in %s seconds\" % ( startTime, endTime, sid, time.time() - qStart ) )\n\n return resp\n\n def validateRule( self, ruleContent = None ):\n '''Validate a D&R rule compiles properly.\n\n Args:\n ruleContent (dict): D&R rule to use to scan, with a \"detect\" key and a \"respond\" key.\n\n Returns:\n a dict containing results of the query.\n '''\n # qStart = time.time()\n\n if self._apiURL is None:\n # Get the ingest URL from the API.\n self._apiURL = 'https://%s/' % ( self._replayURL, )\n req = {}\n body = {\n 'rule' : ruleContent,\n }\n if ruleContent is None:\n raise LcApiException( 'no rule specified' )\n\n nRetry = 0\n while True:\n try:\n resp = self._lc._apiCall( 'validate/%s' % ( self._lc._oid, ),\n 'POST',\n {},\n altRoot = self._apiURL,\n queryParams = req,\n rawBody = json.dumps( body ).encode(),\n contentType = 'application/json' )\n\n break\n except:\n nRetry += 1\n if nRetry > 5:\n raise\n time.sleep( 2 * nRetry )\n # print( \"Finished query %s-%s for %s in %s seconds\" % ( startTime, endTime, sid, time.time() - qStart ) )\n\n return resp\n\n def _rollupResults( self, results ):\n final = {}\n for result in results:\n if not isinstance( result, dict ):\n raise result\n for k, v in result.items():\n if isinstance( v, bool ):\n # MUST test for bool before int because in Python\n # a bool IS an instance of an INT.....\n if k not in final:\n final[ k ] = v\n elif not final[ k ] and v:\n final[ k ] = v\n elif isinstance( v, ( int, float ) ):\n if k not in final:\n final[ k ] = 0\n final[ k ] += v\n elif isinstance( v, ( str, bytes ) ):\n final.setdefault( k, [] ).append( v )\n elif isinstance( v, dict ):\n final.setdefault( k, {} ).update( v )\n elif isinstance( v, ( list, tuple ) ):\n tmp = final.setdefault( k, [] )\n tmp += list( v )\n else:\n raise LcApiException( 'unexpected data type: %s' % ( type( v ), ) )\n return final\n\ndef main( sourceArgs = None ):\n import argparse\n\n parser = argparse.ArgumentParser( prog = 'limacharlie.io replay detection and response' )\n\n parser.add_argument( '--sid',\n type = uuid.UUID,\n required = False,\n dest = 'sid',\n default = None,\n help = 'sensor id to scan traffic from.' )\n\n parser.add_argument( '--entire-org',\n action = 'store_true',\n default = False,\n required = False,\n dest = 'isEntireOrg',\n help = 'if set and --sid is not set, replay traffic from entire organization.' )\n\n parser.add_argument( '--start',\n type = int,\n required = False,\n dest = 'start',\n default = None,\n help = 'epoch seconds at which to start scanning sensor traffic.' )\n\n parser.add_argument( '--end',\n type = int,\n required = False,\n dest = 'end',\n default = None,\n help = 'epoch seconds at which to end scanning sensor traffic.' )\n\n parser.add_argument( '--events',\n type = str,\n required = False,\n dest = 'events',\n default = None,\n help = 'path to file containing events to use in evaluation.' )\n\n parser.add_argument( '--rule-name',\n type = str,\n required = False,\n dest = 'ruleName',\n default = None,\n help = 'name of the an already-existing rule to scan with.' )\n\n parser.add_argument( '--rule-content',\n type = str,\n required = False,\n dest = 'ruleContent',\n default = None,\n help = 'file path where rule to scan is.' )\n\n parser.add_argument( '--max-time-window',\n type = int,\n required = False,\n dest = 'maxTimeWindow',\n default = ( 60 * 60 * 24 * 1 ),\n help = 'maximum number of seconds in a window used to shard the search.' )\n\n parser.add_argument( '--max-concurrent',\n type = int,\n required = False,\n dest = 'maxConcurrent',\n default = 10,\n help = 'maximum number of concurrent queries per sensor searched.' )\n\n parser.add_argument( '--last-seconds',\n type = int,\n required = False,\n dest = 'lastSeconds',\n default = None,\n help = 'can be specified instead of --start and --end, will make the time window the last X seconds.' )\n\n parser.add_argument( '--quiet',\n action = 'store_false',\n default = True,\n required = False,\n dest = 'isInteractive',\n help = 'if set, will not print status update to stdout.' )\n\n parser.add_argument( '--trace',\n action = 'store_true',\n default = False,\n required = False,\n dest = 'isRunTrace',\n help = 'if set will output a trace of each operator evaluation and the result' )\n\n parser.add_argument( '--limit-event',\n type = int,\n required = False,\n dest = 'limitEvent',\n default = None,\n help = 'limits the number of events evaluated to approximately this number.' )\n\n parser.add_argument( '--limit-eval',\n type = int,\n required = False,\n dest = 'limitEval',\n default = None,\n help = 'limits the number of rule evaluations to approximately this number.' )\n\n parser.add_argument( '--validate',\n action = 'store_true',\n default = False,\n required = False,\n dest = 'isValidate',\n help = 'if set will only validate the rule compiles properly' )\n\n parser.add_argument( '--ignore-state',\n action = 'store_true',\n default = False,\n required = False,\n dest = 'isIgnoreState',\n help = 'if set, processing from single sensors will be parallelized increasing performance but limiting effectiveness of stateful detection.' )\n\n args = parser.parse_args( sourceArgs )\n\n replay = Replay( Manager( None, None ),\n isInteractive = args.isInteractive,\n maxTimeWindow = args.maxTimeWindow,\n maxConcurrent = args.maxConcurrent )\n\n ruleContent = None\n if args.ruleContent is not None:\n with open( args.ruleContent, 'rb' ) as f:\n ruleContent = f.read().decode()\n try:\n ruleContent = yaml.safe_load( ruleContent )\n except:\n try:\n ruleContent = json.loads( ruleContent )\n except:\n raise LcApiException( 'rule content not valid yaml or json' )\n\n if args.isValidate:\n response = replay.validateRule( ruleContent )\n else:\n if args.events is None:\n if ( args.start is None or args.end is None ) and args.lastSeconds is None:\n print( 'must specify start and end, or last-seconds' )\n parser.print_help()\n sys.exit(1)\n\n if args.events is None:\n # We want to use Insight-based events.\n start = args.start\n end = args.end\n if start is None and end is None and args.lastSeconds is not None:\n now = int( time.time() )\n start = now - args.lastSeconds\n end = now\n\n if args.sid is not None:\n response = replay.scanHistoricalSensor( str( args.sid ),\n start,\n end,\n ruleName = args.ruleName,\n ruleContent = ruleContent,\n isRunTrace = args.isRunTrace,\n limitEvent = args.limitEvent,\n limitEval = args.limitEval,\n isIgnoreState = args.isIgnoreState )\n elif args.isEntireOrg:\n response = replay.scanEntireOrg( start,\n end,\n ruleName = args.ruleName,\n ruleContent = ruleContent,\n isRunTrace = args.isRunTrace,\n limitEvent = args.limitEvent,\n limitEval = args.limitEval,\n isIgnoreState = args.isIgnoreState )\n else:\n raise LcApiException( '--sid or --entire-org must be specified' )\n else:\n # We are using an events file.\n with open( args.events, 'rb' ) as f:\n fileContent = f.read().decode()\n # We support two formats.\n try:\n try:\n # This is a JSON list containing all the events like you get\n # from the historical view download button. Or just single\n # JSON event.\n events = json.loads( fileContent )\n except:\n # This is newline-delimited like you get from LC Outputs.\n events = [ json.loads( e ) for e in fileContent.split( '\\n' ) ]\n\n # If the result is a dictionary and not a list we assume this was\n # just a single event so we will wrap it.\n if isinstance( events, dict ):\n events = [ events ]\n except:\n print( \"!!! Invalid events provided. Content should be a JSON event, a JSON LIST of events or newline-separated JSON.\" )\n sys.exit( 1 )\n response = replay.scanEvents( events,\n ruleName = args.ruleName,\n ruleContent = ruleContent,\n isRunTrace = args.isRunTrace,\n limitEvent = args.limitEvent,\n limitEval = args.limitEval )\n\n if args.isInteractive:\n # If this is interactive, we displayed progress, so we need a new line.\n print( \"\" )\n\n print( json.dumps( response, indent = 2 ) )\n\nif '__main__' == __name__:\n main()","sub_path":"limacharlie/Replay.py","file_name":"Replay.py","file_ext":"py","file_size_in_byte":25259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"648320998","text":"\"\"\"hunter_toy.views.\n\nThis module provides the application views handler.\n\"\"\"\n\n\nfrom hunter_toy.views.dashboard import dashboard_view\nfrom hunter_toy.views.game import game_view\nfrom hunter_toy.views.index import index_view\nfrom hunter_toy.views.login import login_view\nfrom hunter_toy.views.logout import logout_view\n\n\n__all__ = [\n 'dashboard_view',\n 'game_view',\n 'index_view',\n 'login_view',\n 'logout_view'\n]\n\n\ndef make_views(app):\n \"\"\"Register the views blueprints into the given app.\n \n Args:\n app (WSGIApplication): the application you want register the views\n \"\"\"\n app.register_blueprint(index_view, url_prefix='')\n app.register_blueprint(dashboard_view, url_prefix='/dashboard')\n app.register_blueprint(game_view, url_prefix='/game')\n app.register_blueprint(login_view, url_prefix='/login')\n app.register_blueprint(logout_view, url_prefix='/logout')\n","sub_path":"hunter_toy/views/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"101917164","text":"#!/usr/local/bin/python\nimport string\nimport tracemalloc\n\nfrom PIL import Image, ImageTk\nfrom tkinter import Tk, Frame, BOTH, StringVar, Label, Button, Menu\n\nimport craft\nimport sprites\nimport maps\n\nimport constants\nfrom keyhandlers import on_keypress\nfrom starting_inventory import starting_inventory\n\nMALLOC_LOG = False\nmove_counter = 0\nMALLOC_INTERVAL = 10\n\nMAKE_MONSTERS = True\nMAKE_FISH = True\n# MAKE_MONSTERS = False\ntracemalloc.start()\nclass Application(Frame):\n g=constants.grid_size\n selected_square=None\n spears = []\n def save(self):\n maps.save_world(app=self)\n\n def load(self):\n maps.load_world(app=self)\n\n def toggle_pause(self):\n self.pause = not self.pause\n\n def make_monster(self):\n s = self.selected_square\n x = s.column\n y = s.row\n m = self.screen.monsters\n monster = sprites.Monster(self, x=x, y=y)\n if monster.placed: \n m.append(monster)\n l = len(m) - 1\n m[l].ind = l\n\n def make_fish(self):\n s = self.selected_square\n x = s.column\n y = s.row\n f = self.screen.fishes\n fish = sprites.Fish(self, x=x, y=y)\n if fish.placed: \n f.append(fish)\n l = len(f) - 1\n f[l].ind = l\n\n def make_rocks(self):\n s = self.selected_square\n s.add_feature(\"rock\", self)\n\n def make_trees(self):\n s = self.selected_square\n s.add_feature(\"tree\", self)\n\n def make_water(self):\n s=self.selected_square\n s.passable=False\n s.square_type='water'\n self.screen.canvas.itemconfig(s.representation, fill='blue')\n self.selected_square=None\n\n def make_grass(self):\n s=self.selected_square\n s.passable=True\n s.square_type='grass'\n self.screen.canvas.itemconfig(s.representation, fill='green')\n self.selected_square=None\n\n def edit_square(self, event):\n grid_size = constants.grid_size\n row = int(event.y/grid_size)\n column = int(event.x/grid_size)\n # o = string.Template('Right Clicked {x:$column, y:$row}').substitute({'column':column, 'row': row})\n # print o\n ss = self.screen\n s = ss.grid[row][column]\n self.selected_square = s\n grass_only = [\"Make Monster\", \"Make Trees\", \"Make Rocks\", \"Make Water\"]\n water_only = [\"Make Grass\", \"Make Fish\"]\n # print s.square_type\n if s.square_type == 'grass':\n for g in grass_only:\n self.popup.entryconfig(g, state='normal')\n for w in water_only:\n self.popup.entryconfig(w, state='disabled')\n elif s.square_type == 'water':\n for g in grass_only:\n self.popup.entryconfig(g, state='disabled')\n for w in water_only:\n self.popup.entryconfig(w, state='normal')\n # print s.passable\n try:\n self.popup.tk_popup(event.x_root, event.y_root, 0)\n finally:\n # make sure to release the grab (Tk 8.0a1 only)\n self.popup.grab_release()\n\n def keypress(self, event):\n on_keypress(self, event)\n\n def monsters_move(self):\n global move_counter, MALLOC_INTERVAL, MALLOC_LOG\n if move_counter == MALLOC_INTERVAL and MALLOC_LOG:\n snapshot = tracemalloc.take_snapshot()\n constants.display_top(snapshot)\n move_counter = 0\n move_counter +=1\n # print(move_counter)\n \n g = constants.grid_size\n # c=0\n if not self.pause:\n for fish in self.screen.fishes:\n fish.moved = False\n fish.move(app=self)\n\n for monster in self.screen.monsters:\n monster.moved = False\n monster.move(app=self)\n \n self.root.after(constants.INTERVAL * 25, self.monsters_move)\n\n def add_sprites(self, tux_x=None, tux_y=None, monsters=[], fishes=[]):\n global MAKE_MONSTERS\n print('add_sprites')\n self.tux = sprites.Tux(self,x=tux_x, y=tux_y)\n \n if len(monsters)>0:\n print('value of monsters argument')\n print(monsters)\n raise Exception()\n self.screen.monsters=monsters\n self.screen.fishes=fishes\n m = self.screen.monsters\n f = self.screen.fishes\n print('self.screen.monsters')\n print(self.screen.monsters)\n print(fishes)\n if MAKE_MONSTERS and len(m) == 0:\n for i in range(0,10):\n monster = sprites.Monster(self)\n if monster.placed: \n m.append(monster)\n l = len(m) - 1\n m[l].ind = l\n if MAKE_FISH and len(f) == 0:\n for i in range(0,10):\n fish = sprites.Fish(self)\n if fish.placed: \n f.append(fish)\n l = len(f) - 1\n f[l].ind = l\n # Consumables added here\n sprites.Rocks(self)\n sprites.Trees(self)\n\n def display_inventory(self):\n self.inventory = starting_inventory\n self.update_inventory()\n\n def update_inventory(self):\n si=self.inventory\n row=1;\n for key in self.inventory: \n si[key][\"s\"]=StringVar()\n si[key][\"s\"].set(self.inventory[key][\"qty\"])\n si[key][\"l1\"]=Label(self.frame2, text=si[key][\"display\"]+\": \", bg=\"gray\")\n si[key][\"l2\"]=Label(self.frame2, textvariable=si[key][\"s\"], bg=\"gray\")\n si[key][\"l1\"].grid(row=row, column=0, sticky=\"we\")\n si[key][\"l2\"].grid(row=row, column=1, sticky=\"we\")\n row+=1\n if si[\"fish\"][\"qty\"] <= 0:\n print(\"Dieded\")\n\n def create_widgets(self):\n global root\n self.frame = Frame(root)\n self.frame2 = Frame(root)\n self.frame.pack(fill=BOTH, expand=1, side=\"left\")\n\n self.screen = sprites.Screen(self)\n x=self.screen.current_map[\"x\"]\n y=self.screen.current_map[\"y\"]\n self.add_sprites()\n self.screen.grids[y][x] = maps.save(app=self, in_memory=True)\n self.screen.canvas.pack(fill=BOTH, expand=1)\n self.display_inventory()\n self.frame2.pack(fill=BOTH, expand=1, side=\"right\")\n\n self.craft_button = Button(self.frame2, text=\"craft\")\n self.craft_button.grid(row=0, column=0, sticky=\"we\")\n self.craft_button[\"command\"]=self.craft.create_window\n\n self.screen.canvas.focus_set()\n self.screen.canvas.bind(\"\", self.keypress)\n\n def create_popups(self):\n self.popup = Menu(root, tearoff=0)\n self.popup.add_command(label=\"Make Grass\", command=self.make_grass) # , command=next) etc...\n self.popup.add_command(label=\"Make Water\", command=self.make_water)\n self.popup.add_separator()\n self.popup.add_command(label=\"Make Monster\", command=self.make_monster)\n self.popup.add_command(label=\"Make Rocks\", command=self.make_rocks)\n self.popup.add_command(label=\"Make Trees\", command=self.make_trees)\n self.popup.add_command(label=\"Make Fish\", command=self.make_fish)\n\n def __init__(self, master=None):\n self.pause=False\n self.starting_map = {}\n self.master=master\n self.counter=0\n self.root = root\n self.sprites = {}\n self.action=None\n\n self.craft = craft.Craft(app=self)\n\n Frame.__init__(self, master)\n # self.keypress = on_keypress\n self.pack()\n self.create_widgets()\n self.create_popups()\n self.root.after(constants.INTERVAL * 25, self.monsters_move)\n # master.after(1, lambda: master.focus_force())\n\n # self.animate()\n menubar = Menu(root)\n\n # create a pulldown menu, and add it to the menu bar\n filemenu = Menu(menubar, tearoff=0)\n\n filemenu.add_command(label=\"Open\", command=self.load, accelerator=\"Cmd-L\")\n filemenu.add_command(label=\"Save\", command=self.save, accelerator=\"Cmd-S\")\n filemenu.add_command(label=\"Pause\", command=self.toggle_pause, accelerator=\"Cmd-P\")\n filemenu.add_separator()\n filemenu.add_command(label=\"Exit\", command=root.quit, accelerator=\"Cmd-Q\")\n menubar.add_cascade(label=\"File\", menu=filemenu)\n root.config(menu=menubar)\n\n\nroot = Tk()\nroot.focus_force()\nroot.tkraise()\napp = Application(master=root)\napp.mainloop()\ntry: \n root.destroy()\nexcept:\n print(\"Couldn't destroy root. Maybe try a bigger drill?\")","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"192444984","text":"\n\nfrom xai.brain.wordbase.nouns._instruction import _INSTRUCTION\n\n#calss header\nclass _INSTRUCTIONS(_INSTRUCTION, ):\n\tdef __init__(self,): \n\t\t_INSTRUCTION.__init__(self)\n\t\tself.name = \"INSTRUCTIONS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"instruction\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_instructions.py","file_name":"_instructions.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"19474188","text":"# функция определяет предполагаемые основы слов (общие части) и (прото)аффиксы -- то,\n# что осталось после удаления предполагаемых основ\ndef extract_proto_morphemes(s1, s2):\n from strutil import str_convolution_max, str_split_by_equal\n\n sh, conv = str_convolution_max(s1, s2)\n components = str_split_by_equal(s1, s2, sh)\n\n assert len(components[0]) == len(components[1]), \"Unexpected str_split_by_equal(...) result\"\n if len(components[0]) <= 0:\n return ('', [])\n\n global i\n i = 0\n\n def map_func(ss1, ss2):\n global i\n v = (len(ss1), i) if ss1 == ss2 else (0, 0)\n i += 1\n return v\n\n proto_root_pos = max(map(map_func, components[0], components[1]), key=lambda x: x[0])\n\n proto_affixes = \\\n [\n ''.join(components[0][:proto_root_pos[1]])\n , ''.join(components[0][proto_root_pos[1] + 1:])\n , ''.join(components[1][:proto_root_pos[1]])\n , ''.join(components[1][proto_root_pos[1] + 1:])\n ]\n proto_affixes = [o for o in proto_affixes if o != '']\n\n return \\\n (\n # предполагаемый корень\n components[0][proto_root_pos[1]],\n # прото-аффиксы\n proto_affixes\n )\n\n","sub_path":"morpho.py","file_name":"morpho.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"157571127","text":"import streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.tree import export_graphviz\r\nfrom IPython.display import Image \r\nfrom sklearn import tree\r\n##import graphviz\r\nfrom matplotlib import pyplot as plt\r\nimport seaborn as sns\r\n##from statsmodels.graphics.mosaicplot import mosaic\r\nimport scipy\r\nimport awesome_streamlit as ast\r\nfrom PIL import Image\r\n\r\ndf = pd.read_csv('Bank_CS.csv')\r\ndf.drop(columns=['Unnamed: 0','Unnamed: 0.1'], inplace=True)\r\n## get numerical features\r\nnumeric_features = df.select_dtypes(include=[np.number])\r\n\r\nyear_feature = [feature for feature in numeric_features if 'Month' in feature or 'Year' in feature]\r\nyear_feature.remove('Monthly_Salary')\r\n\r\ndef write():\r\n with st.spinner(\"Loading EDA ...\"):\r\n ast.shared.components.title_awesome(\"Exploratory Data Analysis\")\r\n \r\n st.write(\r\n \"\"\"\r\n # Temporal Features\r\n\r\n \"\"\"\r\n )\r\n st.markdown('By visuaizing all the temporal features, some assumption and idea of the data can be grasp.')\r\n # for feature in year_feature:\r\n # data=df.copy()\r\n # g = sns.catplot(x='Decision', y=feature, kind=\"swarm\", data=data, height=5, aspect=2)\r\n # g.fig.suptitle(feature)\r\n # st.pyplot(g)\r\n name = \"Bank_EDA_cell_10_output_\"\r\n for i in range(1,5):\r\n _ = name + str(i) + '.png'\r\n image = Image.open(_)\r\n st.image(image, use_column_width=True)\r\n\r\n st.subheader(\"Observations: \")\r\n st.markdown('---')\r\n st.markdown(\"**Is there any pattern found from plotting the temporal variable against the Desicion for loan application?**\")\r\n st.markdown('For all the temporal features, the accepted case outnumbered the rejected cases.')\r\n\r\n st.markdown('---')\r\n st.markdown(\"**Does the duration of delayed credit carrd payment and the loan duration affect the loan application decision?**\")\r\n st.markdown(\"From the plot of Credit Card Exceed Months and Loan Tenure Year against Decision, we can observe that in general, how long a person did not pay for his or her credit card and loan duration **_do not directly_** affect the result of the loan application.\")\r\n\r\n st.markdown('---')\r\n st.markdown(\"**Is there any preference on year to financial freedom?**\")\r\n st.markdown(\"From the plot, it seems like among all the rejected cases, cases with 14 and 15 years to financial freedom got rejected the most.\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n write()","sub_path":"temporal.py","file_name":"temporal.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609930600","text":"import cv2\r\n\r\nfilepath = 'gender/7.jpg'\r\n\r\nimg = cv2.imread(filepath)\r\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\r\nclassifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\ncolor = (0,255,0)\r\n\r\nfaceRects = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=3,minSize=(32,32))\r\n\r\n#裁剪人脸\r\nx,y,w,h = faceRects[0]\r\ncut = img[y+h//2-91:y+h//2+91,x+w//2-91:x+w//2+91]\r\ncv2.imwrite('gender/cutting.jpg',cut)\r\ncv2.namedWindow('image',cv2.WINDOW_NORMAL)\r\ncv2.imshow('image',cut)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n\r\n\r\n#人脸检测\r\n# if len(faceRects):\r\n# for faceRect in faceRects:\r\n# x,y,w,h = faceRect\r\n# cv2.rectangle(img,(x,y),(x+w,y+h),color,2)\r\n# cv2.namedWindow('image',cv2.WINDOW_NORMAL)\r\n# cv2.imshow('image',img)\r\n# cv2.waitKey(0)\r\n# cv2.destroyAllWindows()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"face_cutting.py","file_name":"face_cutting.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"324031345","text":"\"\"\"\nConsole Input\n=============\n\nScoopPy Class Week 1, Lesson 2\n\nThis simple project, we learned how to\n\n- get user input from the console,\n- convert types\n- format strings\n- use the 'randomint' function from the python standard library\n- modify lists\n\"\"\"\nfrom random import randint\n\n\ndef main(name, age):\n print(\"Hello {name}! You are {age} years old\".format(name=name, age=age))\n\n\nif __name__ == '__main__':\n\n names = []\n\n number_of_people = int(input(\"How many people? \"))\n\n for _ in range(number_of_people):\n names.append(input(\"Enter name: \"))\n\n for name in names:\n main(name, randint(10, 100))\n","sub_path":"console_input.py","file_name":"console_input.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466990246","text":"import os\nimport logging\nimport shutil\nfrom ocs_ci.utility.utils import run_cmd, clone_repo\nfrom ocs_ci.ocs import constants, ocp\n\nlog = logging.getLogger(__name__)\n\n\ndef svt_project_clone():\n \"\"\"\n This function clones the SVT project.\n \"\"\"\n clone_repo(\"https://github.com/openshift/svt.git\", \"/tmp/svt\")\n\n\ndef svt_create_venv_setup():\n \"\"\"\n This function creates Virtual environemt for SVT project,\n and installs all the dependencies and activate the environment\n\n \"\"\"\n\n run_cmd(\"virtualenv -p /bin/python2 /tmp/venv\")\n run_cmd(\"/bin/sh -c 'source /tmp/venv/bin/activate && python --version'\")\n run_cmd(\"/bin/sh -c 'source /tmp/venv/bin/activate && pip install -r registry_requirement.txt'\")\n\n\ndef svt_cluster_loader(clusterload_file=\"/tmp/svt/openshift_scalability/config/master-vert.yaml\"):\n KUBECONFIG = os.getenv('KUBECONFIG')\n \"\"\"\n This function can be used to create an environment on top of an OpenShift installation.\n So, basically you can create any number of projects,\n each having any number of following objects -- ReplicationController, Pods, Services, etc..\n https://github.com/openshift/svt/blob/master/openshift_scalability/README.md\n Arguments for cluster-loader.py:\n -f : This is the input config file used to define the test.\n -kubeconfig : kubeconfig path\n\n Args:\n clusterload_file : clusterloader file\n\n \"\"\"\n\n cwd = os.getcwd()\n os.chdir('/tmp/svt/openshift_scalability/')\n cmd = (\n \"/bin/sh -c 'source /tmp/venv/bin/activate && python /tmp/svt/openshift_scalability/cluster-loader.py \"\n f\"-f {clusterload_file} --kubeconfig {KUBECONFIG}'\"\n )\n run_cmd(cmd)\n os.chdir(cwd)\n\n\ndef svt_cleanup():\n \"\"\"\n Removes clonned SVT project and virtual environemt and Projects\n Created while running SVT\n\n Raises:\n BaseException: In case any erros occured while removing project and ENV.\n\n Returns:\n bool: True if No exceptions, False otherwise\n\n \"\"\"\n\n try:\n shutil.rmtree('/tmp/svt')\n shutil.rmtree('/tmp/venv')\n except BaseException:\n log.error(\"Error while cleaning SVT project\")\n\n try:\n project_list = [\n \"cakephp-mysql0\",\n \"dancer-mysql0\",\n \"django-postgresql0\",\n \"eap64-mysql0\",\n \"nodejs-mongodb0\",\n \"rails-postgresql0\",\n \"tomcat8-mongodb0\"]\n oc = ocp.OCP(\n kind=constants.DEPLOYMENT\n )\n for project in project_list:\n oc.exec_oc_cmd(f\"delete project {project} --ignore-not-found=true --wait=true\")\n\n return True\n except Exception:\n return False\n","sub_path":"ocs_ci/utility/svt.py","file_name":"svt.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"251649906","text":"import time\nfrom gpiozero import MotionSensor\nfrom flask import Flask, render_template, Response, request\nfrom camera import VideoCamera\nimport time\nimport threading\nimport os\n\n\n# PIR motion sensor configuration and detection\n\npir = MotionSensor(4)\n\nwhile True:\n if pir.motion_detected:\n print('Motion detected')\n time.sleep(5)\n\n# Video camera setup\n\npi_camera = VideoCamera(flip=False) # Flip pi camera if upside down.\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html') # Render html template\n\ndef gen(camera):\n # Get camera frame\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n\n@app.route('/video_feed')\ndef video_feed():\n return Response(gen(pi_camera),\n mimetype='multipart/x-mixed-replace; boundary=frame')\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=False)","sub_path":"ArMyPi Server/tests/armypi_test.py","file_name":"armypi_test.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190482509","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nfrom pathlib import Path\nfrom sys import argv, stderr\n\ndef app(files):\n error = 0\n for y in main(files):\n print(y, file=stderr)\n error = 1\n raise SystemExit(error)\n\ndef main(files):\n for filename in files:\n try:\n Path(filename).unlink()\n except BaseException as e:\n yield e\n\nif __name__ == r'__main__':\n app(argv[1:])\n","sub_path":"libexec/sudo/rm.py","file_name":"rm.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"569323585","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom roblib import *\nimport matplotlib.pyplot as plt\nimport scipy as sc\nimport copy\n\ndef draw_axis(R, fig, ax, lim=3):\n \n# if not (R is None):\n# R = array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n# Rrot = R[:-1, :-1]\n \n# plt.close('all')\n# fig = plt.figure()\n# ax = fig.add_subplot(projection='3d')\n \n ax.set_xlim3d([-lim, lim])\n ax.set_ylim3d([-lim, lim])\n ax.set_zlim3d([-lim, lim])\n \n debut = R.dot(array([0, 0, 0, 1]).reshape(4, 1))\n print(\"DEBUT: \", debut)\n\n finZ = R.dot(array([0, 0, 1, 1]).reshape(4, 1))\n print(\"FINZ: \", finZ)\n finY = R.dot(array([0, 1, 0, 1]).reshape(4, 1))\n finX = R.dot(array([1, 0, 0, 1]).reshape(4, 1))\n \n finZ = finZ - debut\n finY = finY - debut\n finX = finX - debut\n \n draw_arrow3D(ax, debut, finZ, col='b')\n draw_arrow3D(ax, debut, finY, col='g')\n draw_arrow3D(ax, debut, finX, col='r')\n \n plt.show()\n\n#draw_axis()\n\ndef Transl(v):\n v = array(v)\n temp = eye(4,4)\n temp[:-1,-1] = v.reshape(3)\n return temp\n\n\ndef drawArm(R1, R2, e=2):\n J0 = array([[-e, 3*e, -e, -e],[-e,-e,3*e],[0,0,0,0],[1,1,1,1]])\n J1 = R1.dot(J0)\n J2 = R2.dot(J0)\n J = [J1[:,1], J2[:,1], J2[:,2], J1[:,2], J1[:,3], J2[:,3], J2[:,1], J2[:,2], J2[:,3], J1[:,3], J1[:,1]]\n plt.plot3D(J[1,:], J[2,:], J[3,:])\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1, projection='3d')\n\n\nA = eye(4,4)\nAcopy = copy.deepcopy(A)\ntemp = Acopy.dot(Transl([1, 1, 1])).dot(Rot([1, 0, 0]))\n\ndrawArm(A, temp)\naae\ndraw_axis(A, fig, ax, lim=5)\n\n\n\ndraw_axis(temp, fig, ax, lim=5)\n#draw_arrow3D(ax, array([[1], [1], [1], [1]]), array([[0],[0],[1],[1]]), col='yellow')\n\nzrgeg\ndef Rot(w):\n A = array([[0,-w[2],w[1]], [w[2],0,-w[0]], [-w[1],w[0],0]])\n R = array([[0.0 for i in range(4)] for j in range(4)])\n temp = array(sc.linalg.expm(A))\n R[:3, :3] = temp\n R[-1,-1] = 1\n return R\n\n\n\ndraw_axis(R=iden)\niden = Transl([1, 1, 1]).dot(Rot([1, 0, 0]))\ndraw_axis(iden)\n\n\n#toto = array([[42],[42],[42]])\n#print(Rot(toto))\n#print(Transl(toto))\n \n \n\n","sub_path":"python/brasRobot.py","file_name":"brasRobot.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"604698996","text":"from .base import *\n\n\nclass TexProjectorProperties:\n\n def __init__(self, panel):\n\n self._panel = panel\n self._fields = {}\n self._checkbuttons = {}\n\n self._targets = {}\n\n section = panel.add_section(\"tex_projector_props\", \"Tex. projector properties\", hidden=True)\n\n text = \"On\"\n checkbtn = PanelCheckButton(section, lambda on:\n self.__handle_value(\"on\", on), text)\n self._checkbuttons[\"on\"] = checkbtn\n section.add(checkbtn)\n\n borders = (0, 5, 0, 0)\n\n sizer = Sizer(\"horizontal\")\n section.add(sizer)\n text = \"Size:\"\n sizer.add(PanelText(section, text), alignment=\"center_v\", borders=borders)\n val_id = \"size\"\n field = PanelInputField(section, val_id, \"float\", self.__handle_value, 80)\n field.set_input_parser(self.__parse_size_input)\n self._fields[val_id] = field\n sizer.add(field, alignment=\"center_v\")\n\n group = section.add_group(\"Projection type\")\n radio_btns = PanelRadioButtonGroup(group, columns=1)\n group.add(radio_btns.sizer)\n\n get_command = lambda projection_type: lambda: self.__set_projection_type(projection_type)\n\n for projection_type in (\"orthographic\", \"perspective\"):\n radio_btns.add_button(projection_type, projection_type.title())\n radio_btns.set_button_command(projection_type, get_command(projection_type))\n\n radio_btns.set_selected_button(\"orthographic\")\n self._radio_btns = radio_btns\n\n group = section.add_group(\"Lens/Film\")\n sizer = GridSizer(rows=0, columns=2, gap_h=5, gap_v=2)\n group.add(sizer, expand=True)\n text = \"Width:\"\n sizer.add(PanelText(group, text), alignment_v=\"center_v\")\n val_id = \"film_w\"\n field = PanelInputField(group, val_id, \"float\", self.__handle_value, 80)\n field.set_input_parser(self.__parse_size_input)\n self._fields[val_id] = field\n sizer.add(field, proportion_h=1., alignment_v=\"center_v\")\n\n text = \"Height:\"\n sizer.add(PanelText(group, text), alignment_v=\"center_v\")\n val_id = \"film_h\"\n field = PanelInputField(group, val_id, \"float\", self.__handle_value, 80)\n field.set_input_parser(self.__parse_size_input)\n self._fields[val_id] = field\n sizer.add(field, proportion_h=1., alignment_v=\"center_v\")\n\n text = \"X offset:\"\n sizer.add(PanelText(group, text), alignment_v=\"center_v\")\n val_id = \"film_x\"\n field = PanelInputField(group, val_id, \"float\", self.__handle_value, 80)\n field.set_input_parser(self.__parse_size_input)\n self._fields[val_id] = field\n sizer.add(field, proportion_h=1., alignment_v=\"center_v\")\n\n text = \"Y offset:\"\n sizer.add(PanelText(group, text), alignment_v=\"center_v\")\n val_id = \"film_y\"\n field = PanelInputField(group, val_id, \"float\", self.__handle_value, 80)\n field.set_input_parser(self.__parse_size_input)\n self._fields[val_id] = field\n sizer.add(field, proportion_h=1., alignment_v=\"center_v\")\n\n section = panel.add_section(\"tex_projector_targets\", \"Projector targets\", hidden=True)\n\n self._target_combobox = PanelComboBox(section, 10, tooltip_text=\"Selected target\")\n borders = (5, 5, 5, 0)\n section.add(self._target_combobox, expand=True, borders=borders)\n\n btn_sizer = Sizer(\"horizontal\")\n section.add(btn_sizer, expand=True, borders=borders)\n\n borders = (0, 5, 0, 0)\n\n text = \"Pick\"\n btn = PanelButton(section, text, \"\", \"Add target model\", self.__pick_object)\n self._pick_btn = btn\n btn_sizer.add(btn, proportion=1., borders=borders)\n\n text = \"Remove\"\n btn = PanelButton(section, text, \"\", \"Remove selected target\", self.__remove_target)\n btn_sizer.add(btn, proportion=1., borders=borders)\n\n text = \"Clear\"\n btn = PanelButton(section, text, \"\", \"Remove all targets\", self.__clear_targets)\n btn_sizer.add(btn, proportion=1.)\n\n group = section.add_group(\"Target poly selection\")\n sizer = Sizer(\"horizontal\")\n borders = (0, 0, 5, 0)\n group.add(sizer, expand=True, borders=borders)\n\n borders = (0, 5, 0, 0)\n\n text = \"Use\"\n checkbtn = PanelCheckButton(group, lambda val:\n self.__handle_value(\"use_poly_sel\", val), text)\n checkbtn.enable(False)\n checkbtn.add_disabler(\"no_targets\", lambda: not self._targets)\n self._checkbuttons[\"use_poly_sel\"] = checkbtn\n sizer.add(checkbtn, alignment=\"center_v\")\n sizer.add((5, 0), proportion=1.)\n text = \"Show\"\n checkbtn = PanelCheckButton(group, lambda val:\n self.__handle_value(\"show_poly_sel\", val), text)\n checkbtn.enable(False)\n checkbtn.add_disabler(\"no_targets\", lambda: not self._targets)\n self._checkbuttons[\"show_poly_sel\"] = checkbtn\n sizer.add(checkbtn, alignment=\"center_v\")\n sizer.add((0, 0), proportion=1.)\n\n text = \"Affected UV sets:\"\n borders = (5, 5, 5, 10)\n section.add(PanelText(group, text), alignment=\"center_h\", borders=borders)\n val_id = \"uv_set_ids\"\n field = PanelInputField(section, val_id, \"custom\", self.__handle_value, 10)\n field.set_input_parser(self.__parse_uv_set_id_input)\n field.set_value_parser(self.__parse_uv_set_ids)\n field.set_value(())\n field.enable(False)\n field.add_disabler(\"no_targets\", lambda: not self._targets)\n self._fields[val_id] = field\n borders = (5, 5, 5, 0)\n section.add(field, expand=True, borders=borders)\n\n text = \"Apply UVs\"\n btn = PanelButton(section, text, \"\", \"Bake UVs into target vertices\", self.__apply_uvs)\n section.add(btn, alignment=\"center_h\")#, borders=borders)\n\n def setup(self):\n\n def enter_picking_mode(prev_state_id, active):\n\n Mgr.do(\"set_viewport_border_color\", \"viewport_frame_pick_objects\")\n self._pick_btn.active = True\n\n def exit_picking_mode(next_state_id, active):\n\n if not active:\n self._pick_btn.active = False\n\n add_state = Mgr.add_state\n add_state(\"texprojtarget_picking_mode\", -10, enter_picking_mode, exit_picking_mode)\n\n def __set_projection_type(self, projection_type):\n\n if GD[\"active_creation_type\"]:\n Mgr.update_app(\"tex_projector_prop_default\", \"projection_type\", projection_type)\n return\n\n Mgr.update_remotely(\"texproj_prop\", \"projection_type\", projection_type)\n\n def __handle_value(self, value_id, value, state=\"done\"):\n\n if GD[\"active_creation_type\"]:\n Mgr.update_app(\"tex_projector_prop_default\", value_id, value)\n return\n\n if value_id == \"use_poly_sel\":\n value_id = \"targets\"\n target_id = self._target_combobox.get_selected_item()\n self._targets[target_id][\"toplvl\"] = not value\n value = {k: v.copy() for k, v in self._targets.items()}\n target_prop = \"use_poly_sel\"\n elif value_id == \"show_poly_sel\":\n value_id = \"targets\"\n target_id = self._target_combobox.get_selected_item()\n self._targets[target_id][\"show_poly_sel\"] = value\n value = {k: v.copy() for k, v in self._targets.items()}\n target_prop = \"show_poly_sel\"\n elif value_id == \"uv_set_ids\":\n value_id = \"targets\"\n target_id = self._target_combobox.get_selected_item()\n self._targets[target_id][\"uv_set_ids\"] = value\n value = {k: v.copy() for k, v in self._targets.items()}\n target_prop = \"uv_set_ids\"\n else:\n target_id = None\n target_prop = \"\"\n\n Mgr.update_remotely(\"texproj_prop\", value_id, value, target_id=target_id,\n target_prop=target_prop)\n\n def __select_target(self, target_id):\n\n self._target_combobox.select_item(target_id)\n target_data = self._targets[target_id]\n uv_set_ids = target_data[\"uv_set_ids\"]\n use_poly_sel = not target_data[\"toplvl\"]\n show_poly_sel = target_data[\"show_poly_sel\"]\n field = self._fields[\"uv_set_ids\"]\n field.set_value(uv_set_ids)\n self._checkbuttons[\"use_poly_sel\"].check(use_poly_sel)\n self._checkbuttons[\"show_poly_sel\"].check(show_poly_sel)\n\n def __remove_target(self):\n\n if not self._targets:\n return\n\n target_id = self._target_combobox.get_selected_item()\n value = {k: v.copy() for k, v in self._targets.items()}\n del value[target_id]\n\n Mgr.update_remotely(\"texproj_prop\", \"targets\", value, target_id=target_id,\n target_prop=\"remove\")\n\n def __clear_targets(self):\n\n if not self._targets:\n return\n\n value = {}\n\n Mgr.update_remotely(\"texproj_prop\", \"targets\", value, target_prop=\"clear\")\n\n def __parse_size_input(self, input_text):\n\n try:\n size = float(input_text)\n except:\n try:\n size = eval(input_text)\n except:\n return None\n\n return max(.001, size)\n\n def __parse_uv_set_id_input(self, input_text):\n # TODO: use ranges\n\n try:\n uv_set_ids = tuple(set(sorted(min(7, max(0, int(s)))\n for s in input_text.replace(\" \", \"\").split(\",\"))))\n except:\n return None\n\n return uv_set_ids\n\n def __parse_uv_set_ids(self, uv_set_ids):\n # TODO: turn into ranges\n\n try:\n uv_set_id_str = str(uv_set_ids).strip(\"(),\")\n except:\n return None\n\n return uv_set_id_str\n\n def get_base_type(self):\n\n return \"helper\"\n\n def get_section_ids(self):\n\n return [\"tex_projector_props\"] + self.get_extra_section_ids()\n\n def get_extra_section_ids(self):\n\n return [\"tex_projector_targets\"]\n\n def set_object_property_default(self, prop_id, value):\n\n color = (1., 1., 0., 1.)\n\n if prop_id == \"on\":\n self._checkbuttons[\"on\"].check(value)\n self._checkbuttons[\"on\"].set_checkmark_color(color)\n elif prop_id == \"projection_type\":\n self._radio_btns.set_selected_button(value)\n self._radio_btns.set_bullet_color(color)\n elif prop_id in self._fields:\n field = self._fields[prop_id]\n field.show_text()\n field.set_value(value)\n field.set_text_color(color)\n\n def set_object_property(self, prop_id, value):\n\n if prop_id == \"on\":\n\n self._checkbuttons[\"on\"].check(value)\n\n elif prop_id == \"projection_type\":\n\n self._radio_btns.set_selected_button(value)\n\n elif prop_id == \"targets\":\n\n old_targets = self._targets\n new_targets, target_names = value\n\n if new_targets == old_targets:\n return\n\n self._targets = new_targets\n\n field = self._fields[\"uv_set_ids\"]\n checkbtns = self._checkbuttons\n combobox = self._target_combobox\n cur_target_id = combobox.get_selected_item()\n\n if not old_targets:\n field.enable()\n checkbtns[\"use_poly_sel\"].enable()\n checkbtns[\"show_poly_sel\"].enable()\n\n if cur_target_id in new_targets:\n\n old_target_data = old_targets[cur_target_id]\n new_target_data = new_targets[cur_target_id]\n\n if new_target_data != old_target_data:\n uv_set_ids = new_target_data[\"uv_set_ids\"]\n use_poly_sel = not new_target_data[\"toplvl\"]\n show_poly_sel = new_target_data[\"show_poly_sel\"]\n field.set_value(uv_set_ids)\n checkbtns[\"use_poly_sel\"].check(use_poly_sel)\n checkbtns[\"show_poly_sel\"].check(show_poly_sel)\n\n old_target_ids = set(old_targets.keys())\n new_target_ids = set(new_targets.keys())\n\n if new_target_ids == old_target_ids:\n return\n\n for target_id in new_target_ids - old_target_ids:\n target_name = target_names[target_id]\n get_command = lambda target_id: lambda: self.__select_target(target_id)\n combobox.add_item(target_id, target_name, get_command(target_id))\n combobox.select_item(target_id)\n\n for target_id in old_target_ids - new_target_ids:\n combobox.remove_item(target_id)\n\n new_target_id = combobox.get_selected_item()\n\n if new_target_id != cur_target_id:\n if new_target_id:\n target_data = new_targets[new_target_id]\n uv_set_ids = target_data[\"uv_set_ids\"]\n use_poly_sel = not target_data[\"toplvl\"]\n show_poly_sel = target_data[\"show_poly_sel\"]\n field.set_value(uv_set_ids)\n checkbtns[\"use_poly_sel\"].check(use_poly_sel)\n checkbtns[\"show_poly_sel\"].check(show_poly_sel)\n else:\n field.set_value(())\n field.enable(False)\n checkbtns[\"use_poly_sel\"].check(False)\n checkbtns[\"use_poly_sel\"].enable(False)\n checkbtns[\"show_poly_sel\"].check(False)\n checkbtns[\"show_poly_sel\"].enable(False)\n\n elif prop_id in self._fields:\n\n field = self._fields[prop_id]\n field.set_value(value)\n\n def check_selection_count(self):\n\n sel_count = GD[\"selection_count\"]\n multi_sel = sel_count > 1\n color = (.5, .5, .5, 1.) if multi_sel else None\n\n if multi_sel:\n self._checkbuttons[\"on\"].check(False)\n self._radio_btns.set_selected_button()\n\n fields = self._fields\n\n for val_id in (\"size\", \"film_w\", \"film_h\", \"film_x\", \"film_y\"):\n field = fields[val_id]\n field.set_text_color(color)\n field.show_text(not multi_sel)\n\n self._checkbuttons[\"on\"].set_checkmark_color(color)\n self._radio_btns.set_bullet_color(color, update=True)\n\n def __pick_object(self):\n\n if self._pick_btn.active:\n Mgr.exit_state(\"texprojtarget_picking_mode\")\n else:\n Mgr.enter_state(\"texprojtarget_picking_mode\")\n\n def __apply_uvs(self):\n\n Mgr.update_app(\"uv_projection\")\n\n\nObjectTypes.add_type(\"tex_projector\", \"Texture Projector\")\nPropertyPanel.add_properties(\"tex_projector\", TexProjectorProperties)\n","sub_path":"src/gui/components/props/tex_projector.py","file_name":"tex_projector.py","file_ext":"py","file_size_in_byte":14685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"634264925","text":"#!/usr/bin/env python3\n# HW04_ch07_ex02\n\n# The built-in function eval takes a string and evaluates it using the Python\n# interpreter.\n# For example:\n\n# >>> eval('1 + 2 * 3')\n# 7\n# >>> import math\n# >>> eval('math.sqrt(5)')\n# 2.2360679774997898\n# >>> eval('type(math.pi)')\n# \n\n# Write a function called eval_loop that iteratively prompts the user, takes\n# the resulting input and evaluates it using eval, and prints the result.\n\n# It should continue until the user enters 'done', and then return the value of\n# the last expression it evaluated.\n\n# Here is an opportunity to use things like `try`, `except`, and/or `finally`.\n\n# Please write a docstring for every function you write.\n\n###############################################################################\n# Imports\nimport math\n\n# Body\ndef eval_loop():\n \"\"\"return a math result with a given python string formula.\n \"\"\"\n while(True):\n print('please input a expression')\n input_v = input()\n if input_v == 'done':\n try:\n print('last expression calculated is: ', res)\n break\n except:\n print('No previous expression evaluated! ')\n break\n else:\n res = input_v\n try:\n print(eval(input_v))\n except:\n print('Illegal input!')\n\n\n###############################################################################\ndef main():\n eval_loop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Day_2/HW02_ch07_ex02.py","file_name":"HW02_ch07_ex02.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"498881140","text":"\n'''\npunkte_baseline are the wavenumbers were the spectrum is taken and pulled down to the baseline.\nband_start: is the start of the interval where the script searches for the highest intensity. this highest intensity is than shown over time.\nband_end: is the end of that interval.\n'''\n\n\n'''\nimput file: .tvf-TriVista-File\noutput file: band intensity over time after baseline correction\n'''\n#written by EvaMaria Hoehn\n\n\nimport lib.analyte\nfrom lib.baseline_corr_for_csv import baselinecorrection\n\n\n#suffix_for_new_filename = '_graphIntensityOverTime.csv'\npunkte_baseline = lib.analyte.kristallviolett_al_Raja()\nband_start = 1152\nband_end = 1215\n\n\nimport os\nimport plotly.graph_objs as go #import Scatter, Layout\nimport plotly\nimport scipy.signal\nimport pandas as pd\nfrom lib.allgemein import generate_filename\nfrom lib.plotlygraphen import plotly_zeitlVerlauf_2dscatter_layout\n\n\ndef plotly_zeitlVerlauf_2dscatter_data(highest_intensity, zeiten):\n ind = zeiten.ix['time [s]'].values.tolist()\n #print(ind)\n firstCol = highest_intensity.ix['highest intensity [a. u.]'].values.tolist()\n #print(firstCol)\n # for i in range(0, len(ind)):\n # ind[i] = i + 1\n trace1 = go.Scatter(\n x=ind,\n y=firstCol,\n mode='lines',\n line=go.Line(color=\"#000000\", width=3),\n name='Verlauf',\n showlegend=False)\n data = [trace1]\n return data, ind\n\n\ndef plotly_zeitlVerlauf_vergl(df_korregiert, smoothed, times, nwfile, xaxis_title, yaxis_title):\n data, ind = plotly_zeitlVerlauf_2dscatter_data(df_korregiert, smoothed, times)\n fig = go.Figure(data=data, layout=plotly_zeitlVerlauf_2dscatter_layout(ind, xaxis_title, yaxis_title))\n plotly.offline.plot(fig, filename=nwfile) #, auto_open=False) # , image='png', image_filename=nwfile, image_width=800, image_height=430)\n\n\n\nfor dateiname in os.listdir():\n if dateiname.endswith('_smoothed.csv') or dateiname.endswith('_smoothed.CSV'):\n print(dateiname)\n with open(dateiname, 'r') as fd:\n df = pd.read_csv(fd, sep=';', header=0, index_col=0) #, names=['time [s]', 'measured voltage [V]', 'leer'])\n intensities = pd.DataFrame(df.iloc[1:, 0:])\n times = pd.DataFrame(df.iloc[0, 0:]).transpose()\n\n # print(times)\n # print(intensities)\n df_out = baselinecorrection(intensities, punkte_baseline)\n all = times.append(df_out)\n all.to_csv(generate_filename(dateiname, '_baselinecorr_drawnDown.csv'), sep=';')\n","sub_path":"Ramanspektren/erstesPaper/baselinecorr just that band.py","file_name":"baselinecorr just that band.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"195469933","text":"#!/usr/bin/python3  \n#coding=utf-8  \n\"\"\"数据库操作类\"\"\"\n\nfrom PyQt5.QtSql import QSqlDatabase\nfrom datetime import *\nimport pymysql as mdb\nimport hashlib\nimport time\n\n\nclass myMdb(object):\n #数据库连接对象\n __db = None\n #游标对象\n __cursor = None\n def __new__(self, *args, **kwargs): # __new__ 通常用于控制生成一个新实例的过程。它是类级别的方法\n if not hasattr(self, '_instance'): # 参数是一个对象和一个字符串,如果字符串是对象属性之一的命名,则返回True,否则False\n self._instance = super().__new__(self)\n #主机\n host = 'host' in kwargs and kwargs['host'] or 'localhost'\n #端口\n port = 'port' in kwargs and kwargs['port'] or '3308'\n #用户名\n user = 'user' in kwargs and kwargs['user'] or 'root'\n #密码\n passwd = 'passwd' in kwargs and kwargs['passwd'] or 'root'\n #数据库\n db = 'db' in kwargs and kwargs['db'] or 'mrp'\n #编码\n charset = 'charset' in kwargs and kwargs['charset'] or 'utf8'\n # 打开数据库连接  \n # print('连接数据库')\n self.__db = mdb.connect(host=host, port=int(port), user=user, passwd=passwd, db=db, charset=charset)\n #创建一个游标对象 cursor\n self.__cursor = self.__db.cursor()\n # self.__cursor = self.__db.cursor(cursor=mdb.cursors.DictCursor) # 游标类型为字典类型\n return self._instance\n\n #返回执行execute()方法后影响的行数 \n def execute(self, sql):\n self.__cursor.execute(sql)\n rowcount = self.__cursor.rowcount\n return rowcount\n\n # 增->返回新增ID\n def insert(self, **kwargs):\n table = kwargs['table'] # 取字典中的table值\n del kwargs['table']\n sql = 'insert into %s set '%table\n for k, v in kwargs.items():\n sql += \"`%s`='%s',\"%(k, v)\n sql = sql.rstrip(',') # rstrip() 删除 string 字符串末尾的指定的','字符.(默认为空格)\n # print(sql)\n try:\n # 执行SQL语句\n self.__cursor.execute(sql)\n # 提交到数据库执行\n self.__db.commit()\n # 获取自增id\n res = self.__cursor.lastrowid\n except Exception as e:\n # 发生错误时回滚\n print(e)\n self.__db.rollback()\n else:\n return res\n\n def insert_many(self, sql, param): # 批量插入executemany\n \"\"\"executemany批量插入数据库\"\"\"\n # a = \"ON DUPLICATE KEY UPDATE\" # 自动判断是否有记录,待研究??????\n try:\n print(sql)\n self.__cursor.executemany(sql, param)\n self.__db.commit()\n rowcount = self.__cursor.rowcount\n except Exception as e:\n print(e)\n self.__db.rollback()\n else:\n return rowcount\n # print(rowcount)\n\n #测试插入时间\n # start = time.clock()\n # insert_many(table)\n # end = time.clock()\n # print('[insert_many executemany] Time Usage:',end-start)\n\n # 批量插入->返回影响的行数\n def insertMap(jsonArray, tableName):\n \"\"\"批量插入,返回影响行数rowcount\"\"\"\n for json in jsonArray:#遍历每一个子json 下面是为每一个json拼接sql 并执行\n preSql = \"insert into \"+tableName+\" (\" #前一段拼接字段\n subSql = \"values(\" #后一段拼接字段\n exc = () # 作为execute的参数值,这是一个tuble类型\n for x in json: # 取出每一个子json的key和value值\n preSql += x + \",\" # 拼接前面sql的key值\n subSql += \"%s,\" # 拼接后面sql的value数量\n exc = exc + (json[x],) # 每次 给exc添加新的值tuble,注意后面的“,”号不能少,否则不能识别为一个tuble\n preSql = preSql[0:preSql.__len__()-1] + \")\" # 去掉后面的“,”再添加“)���\n subSql = subSql[0:subSql.__len__()-1] + \")\" # 去掉后面的“,”再添加“)”\n sql = preSql+subSql # 前后相加成一个完整的sql\n # print(sql)\n # print(exc)\n try:\n self.__cursor.execute(sql, exc) # 将拼接好的sql和exc作为传入参数 执行\n # self.__db.commit()\n # 影响的行数\n rowcount = self.__cursor.rowcount\n except:\n self.__db.rollback()\n else:\n return rowcount\n self.__db.commit()\n #测试代码见图片 模块名.insertMap(jsonArray, \"students\")\n\n #删->返回影响的行数\n def delete(self, **kwargs):\n table = kwargs['table']\n where = kwargs['where']\n sql = 'DELETE FROM %s where %s'%(table, where)\n print(sql)\n try:\n # 执行SQL语句\n self.__cursor.execute(sql)\n # 提交到数据库执行\n self.__db.commit()\n # 影响的行数\n rowcount = self.__cursor.rowcount\n except:\n # 发生错误时回滚\n self.__db.rollback()\n else:\n return rowcount\n\n #改->返回影响的行数\n def update(self, **kwargs):\n # flag = False\n table = kwargs['table']\n #del kwargs['table']\n kwargs.pop('table') # 如果键值table在字典中存在,删除dict[table],返回 dict[table]的value值。\n\n where = kwargs['where']\n kwargs.pop('where')\n\n sql = 'update %s set '%table\n for k, v in kwargs.items(): # 待研究'是否合理问题,是否需要去除.1月3日去除',待看后面是否出问题????\n sql += \"%s=%s,\"%(k, v)\n sql = sql.rstrip(',')\n sql += ' where %s'%where\n print(sql)\n try:\n # 执行SQL语句\n self.__cursor.execute(sql)\n # 提交到数据库执行\n self.__db.commit()\n flag = True\n #影响的行数\n rowcount = self.__cursor.rowcount\n except Exception as e:\n print(\"执行失败, %s\" %e)\n # 发生错误时回滚\n # flag = False\n self.__db.rollback()\n else:\n return rowcount\n # return flag\n\n def updateAll(self, sql, param):\n # sql = \"INSERT INTO 锻造 (生产编号,序号,已完成数) VALUES (1901101,1,'2'),(1901101,3,'4') ON DUPLICATE KEY UPDATE 已完成数=VALUES(已完成数)\"\n try:\n self.__cursor.executemany(sql, param)\n # 提交到数据库执行\n self.__db.commit()\n rowcount = self.__cursor.rowcount\n except Exception as e:\n print(e)\n self.__db.rollback()\n else:\n return rowcount\n\n #查->单条数据\n def fetchone(self, **kwargs):\n table = kwargs['table']\n #字段\n field = 'field' in kwargs and kwargs['field'] or '*'\n #where\n where = 'where' in kwargs and 'where '+kwargs['where'] or ''\n #order\n order = 'order' in kwargs and 'order by '+ kwargs['order'] or ''\n sql = 'select %s from %s %s %s limit 1'%(field,table,where,order)\n # print(sql)\n try:\n # 执行SQL语句\n self.__cursor.execute(sql)\n # 使用 fetchone() 方法获取单条数据.\n data = self.__cursor.fetchone()\n except:\n # 发生错误时回滚\n self.__db.rollback()\n else:\n return data\n\n #查->多条数据\n def fetchall(self, **kwargs):\n data = \"\"\n table = kwargs['table']\n #字段\n field = 'field' in kwargs and kwargs['field'] or '*'\n #where\n where = 'where' in kwargs and 'where '+kwargs['where'] or ''\n #order\n order = 'order' in kwargs and 'order by '+ kwargs['order'] or ''\n #limit\n limit = 'limit' in kwargs and 'limit '+ kwargs['limit'] or ''\n sql = 'select %s from %s %s %s %s'%(field, table, where, order, limit)\n print(sql)\n try:\n # 执行SQL语句\n self.__cursor.execute(sql)\n # 使用 fetchone() 方法获取单条数据.\n res = self.__cursor.fetchall()\n cur = self.__cursor\n # print('data' +str(data))\n except:\n # 发生错误时回滚\n self.__db.rollback()\n else:\n return res, cur\n\n #析构函数,释放对象时使用\n def __del__(self):\n # 关闭数据库连接\n # self.__cursor.close()\n self.__db.close()\n # print('关闭数据库连接')\n\n\n#生成md5\ndef makeMd5(mstr):\n hmd5 = hashlib.md5()\n hmd5.update(mstr.encode(\"utf-8\"))\n return hmd5.hexdigest()\n\n\n#获取unix时间戳\ndef getTime():\n return round(time.time())\n\n\n#时间格式化\ndef timeFormat(timestamp):\n #return time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(timestamp))\n #return datetime.fromtimestamp(timestamp)\n return datetime.utcfromtimestamp(timestamp)\n\n\n# if __name__ == '__main__':\n \n \n # dbObject = myMdb(host='localhost',port=3308,user='root',passwd='root',db='mrp',charset='utf8')\n \n \n# #创建表\n# print('创建表:')\n# sql = \"DROP TABLE IF EXISTS `user`;\"\n# dbObject.execute(sql)\n# sql = '''\n# CREATE TABLE `user` (\n# `id` int(11) NOT NULL AUTO_INCREMENT,\n# `name` varchar(50) NOT NULL,\n# `pwd` char(32) NOT NULL,\n# `insert_time` int(11) NOT NULL,\n# PRIMARY KEY (`id`)\n# ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='用户表';\n# '''\n# print(sql)\n# res = dbObject.execute(sql)\n# print(res)\n \n \n #写入数据\n # print('\\n写入数据:')\n # pwd = makeMd5('root')\n # insert_time = getTime()\n # res = dbObject.insert(table='user',name='aaaa',pwd=pwd,insert_time=insert_time)\n # print(res)\n \n \n# time.sleep(1)\n# pwd = makeMd5('root')\n# insert_time = getTime()\n# res = dbObject.insert(table='user',name='bbbb',pwd=pwd,insert_time=insert_time)\n# print(res)\n \n \n# time.sleep(1)\n# pwd = makeMd5('111111')\n# insert_time = getTime()\n# res = dbObject.insert(table='user',name='cccc',pwd=pwd,insert_time=insert_time)\n# print(res)\n \n \n# #查询数据-单条\n# print('\\n查询数据-单条:')\n# res = dbObject.fetchone(table='user',where=\"name='cccc'\")\n# print(res)\n \n \n# #修改数据\n# print('\\n修改数据:')\n# res = dbObject.update(table='user',where=\"id=1\",name='dddd')\n# print(res)\n \n \n# #删除数据\n# print('\\n删除数据:')\n# res = dbObject.delete(table='user',where=\"id=2\")\n# print(res)\n \n \n# #查询数据-多条\n# print('\\n查询数据-多条:')\n# res = dbObject.fetchall(table='user',order=\"id desc\") # cursor.fetchmany(3)取3行\n# print(res,type(res))\n# if res:\n# for value in res:\n# print('name:%s,date:%s'%(value['name'],timeFormat(value['insert_time'])))\n","sub_path":"备份/2019-02-26/tools/mysql_conn.py","file_name":"mysql_conn.py","file_ext":"py","file_size_in_byte":11206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"558394226","text":"# 17. Write a program that computes the net amount of a bank account based a transaction log from\n# console input. The transaction log format is shown as following:\n\nd=0\nw=0\nl=[]\nwhile True:\n x=input()\n if x:\n if x[0]=='D':\n dipct=x[2: ]\n d+=int(dipct)\n elif x[0]=='W':\n withdrw=x[2: ]\n w+=int(withdrw)\n else:\n break\ntransaction=d-w\nprint(transaction)","sub_path":"100_Basic_Programs/program_17.py","file_name":"program_17.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"446873307","text":"\nfrom locust import events\nfrom locust.runners import locust_runner, SLAVE_REPORT_INTERVAL, DistributedLocustRunner, STATE_HATCHING\nfrom collections import deque\nfrom locust.stats import StatsEntry, RequestStats\nimport math\nimport logging\nimport gevent\nfrom . import runners\n\nlogger = logging.getLogger(__name__)\n\n# The time window in seconds that current_percentile use data from\nPERCENTILE_TIME_WINDOW = 15.0\n\n# Are we running in distributed mode or not?\nis_distributed = isinstance(locust_runner, DistributedLocustRunner)\n\nresponse_times = deque([])\n\ndef on_request_success_ramping(**kwargs):\n '''logger.info('success ramping')'''\n response_time = kwargs.get('response_time', '')\n '''logger.info('{} : {}'.format('response time', response_time))'''\n if is_distributed:\n response_times.append(response_time)\n else:\n response_times.append(response_time)\n\n # remove from the queue\n rps = runners.locust_runner.stats.aggregated_stats(\"Total\").current_rps\n current_users = runners.locust_runner.user_count\n '''logger.info('{} : {}'.format('rps', rps))'''\n '''logger.info('{} : {}'.format('users', current_users))'''\n if len(response_times) > rps*PERCENTILE_TIME_WINDOW:\n for i in range(len(response_times) - int(math.ceil(rps*PERCENTILE_TIME_WINDOW))):\n response_times.popleft()\n\ndef on_report_to_master_ramping(client_id, data):\n global response_times\n data[\"current_responses\"] = response_times\n response_times = []\n\ndef on_slave_report_ramping(client_id, data):\n if \"current_responses\" in data:\n response_times.append(data[\"current_responses\"])\n\n # remove from the queue\n slaves = locust_runner.slave_count\n response_times_per_slave_count = PERCENTILE_TIME_WINDOW/SLAVE_REPORT_INTERVAL\n if len(response_times) > slaves * response_times_per_slave_count:\n response_times.popleft()\n\ndef register_listeners():\n events.report_to_master += on_report_to_master_ramping\n events.slave_report += on_slave_report_ramping\n events.request_success += on_request_success_ramping\n\ndef remove_listeners():\n events.report_to_master.__isub__(on_report_to_master_ramping)\n events.slave_report.__isub__(on_slave_report_ramping)\n events.request_success.__isub__(on_request_success_ramping)\n\ndef current_percentile(percent):\n if is_distributed:\n # Flatten out the deque of lists and calculate the percentile to be returned\n return percentile(sorted([item for sublist in response_times for item in sublist]), percent)\n else:\n return percentile(sorted(response_times), percent)\n\ndef percentile(N, percent, key=lambda x:x):\n \"\"\"\n Find the percentile of a list of values.\n\n @parameter N - is a list of values. Note N MUST BE already sorted.\n @parameter percent - a float value from 0.0 to 1.0.\n @parameter key - optional key function to compute value from each element of N.\n\n @return - the percentile of the values\n \"\"\"\n if not N:\n return 0\n k = (len(N)-1) * percent\n f = math.floor(k)\n c = math.ceil(k)\n if f == c:\n return key(N[int(k)])\n d0 = key(N[int(f)]) * (c-k)\n d1 = key(N[int(c)]) * (k-f)\n return d0+d1\n\ndef start_ramping(hatch_rate=None, max_locusts=1000, hatch_stride=100,\n percent=0.95, response_time_limit=2000, acceptable_fail=0.05,\n precision=200, start_count=0, calibration_time=15):\n \n locust_runner.running_type = runners.RAMP\n\n register_listeners()\n \n def ramp_up(clients, hatch_stride, boundery_found=False):\n while True:\n if locust_runner.state != STATE_HATCHING:\n if locust_runner.num_clients >= max_locusts:\n logger.info(\"Ramp up halted; Max locusts limit reached: %d\" % max_locusts)\n return ramp_down(clients, hatch_stride)\n\n gevent.sleep(calibration_time)\n fail_ratio = runners.locust_runner.stats.aggregated_stats(\"Total\").fail_ratio\n if fail_ratio > acceptable_fail:\n logger.info(\"Ramp up halted; Acceptable fail ratio %d%% exceeded with fail ratio %d%%\" % (acceptable_fail*100, fail_ratio*100))\n return ramp_down(clients, hatch_stride)\n\n p = current_percentile(percent)\n if p >= response_time_limit:\n logger.info(\"Ramp up halted; Percentile response times getting high: %d\" % p)\n return ramp_down(clients, hatch_stride)\n\n if boundery_found and hatch_stride <= precision:\n logger.info(\"Sweet spot found! Ramping stopped at %i locusts\" % (locust_runner.num_clients))\n return remove_listeners()\n\n logger.info(\"Ramping up...\")\n if boundery_found:\n hatch_stride = max((hatch_stride/2),precision)\n clients += hatch_stride\n locust_runner.start_hatching(clients, locust_runner.hatch_rate)\n gevent.sleep(1)\n\n def ramp_down(clients, hatch_stride):\n while True:\n if locust_runner.state != STATE_HATCHING:\n if locust_runner.num_clients < max_locusts:\n gevent.sleep(calibration_time)\n fail_ratio = runners.locust_runner.stats.aggregated_stats(\"Total\").fail_ratio\n if fail_ratio <= acceptable_fail:\n p = current_percentile(percent)\n if p <= response_time_limit:\n if hatch_stride <= precision:\n logger.info(\"Sweet spot found! Ramping stopped at %i locusts\" % (locust_runner.num_clients))\n return remove_listeners()\n\n logger.info(\"Ramping up...\")\n hatch_stride = max((hatch_stride/2),precision)\n clients += hatch_stride\n locust_runner.start_hatching(clients, locust_runner.hatch_rate)\n return ramp_up(clients, hatch_stride, True)\n\n logger.info(\"Ramping down...\")\n hatch_stride = max((hatch_stride/2),precision)\n clients -= hatch_stride\n if clients > 0:\n locust_runner.start_hatching(clients, locust_runner.hatch_rate)\n else:\n logger.warning(\"No responses met the ramping thresholds, check your ramp configuration, locustfile and \\\"--host\\\" address\")\n logger.info(\"RAMPING STOPPED\")\n return remove_listeners()\n gevent.sleep(1)\n\n if hatch_rate:\n locust_runner.hatch_rate = hatch_rate\n if start_count > 0:\n locust_runner.start_hatching(start_count, hatch_rate)\n logger.info(\"RAMPING STARTED\")\n ramp_up(start_count, hatch_stride)","sub_path":"locust/ramping.py","file_name":"ramping.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"33435278","text":"import os\nimport time\n#import itertools\nimport tensorflow as tf\nimport bot_model\nimport bot_hparams\nimport bot_inputs\n\ntf.flags.DEFINE_string(\"input_dir\", None, \"Directory containing input data files 'train.tfrecords' and 'validation.tfrecords'\")\ntf.flags.DEFINE_string(\"model_dir\", None, \"Directory to store model checkpoints (defaults to ./runs)\")\ntf.flags.DEFINE_string(\"model_impl\", \"dual_encoder\", \"Model implement, 'dual_encoder', 'dual_encoder_diff', 'dual_encoder_attention_cell', 'bilstm'\")\ntf.flags.DEFINE_integer(\"loglevel\", tf.logging.INFO, \"Tensorflow log level\")\ntf.flags.DEFINE_integer(\"num_epochs\", 5, \"Number of training Epochs. Defaults to indefinite.\")\ntf.flags.DEFINE_integer(\"eval_every\", 500, \"Evaluate after this many train steps\")\ntf.flags.DEFINE_integer(\"train_steps\", None, \"train_steps,or None.\")\ntf.flags.DEFINE_integer(\"eval_steps\", 200, \"eval_steps,or None. Because fo the bug, needs to match the validation set.\")\nFLAGS = tf.flags.FLAGS\n#if FLAGS.model_impl==\"dual_encoder\":\n# from models.dual_encoder import dual_encoder_model\n#elif FLAGS.model_impl==\"dual_encoder_diff\":\n# from models.dual_encoder_diff import dual_encoder_model\n#elif FLAGS.model_impl==\"dual_encoder_attention_cell\":\n# from models.dual_encoder_attention_cell import dual_encoder_model\nexec(\"from models.{} import dual_encoder_model as model_impl\".format(FLAGS.model_impl))\n\nTIMESTAMP = int(time.time())\n\nif FLAGS.model_dir:\n MODEL_DIR = FLAGS.model_dir\nelse:\n MODEL_DIR = os.path.abspath(os.path.join(\"./runs\", str(TIMESTAMP)))\n\nTRAIN_FILE = os.path.abspath(os.path.join(FLAGS.input_dir, \"train.tfrecords\"))\nVALIDATION_FILE = os.path.abspath(os.path.join(FLAGS.input_dir, \"validation.tfrecords\"))\n\ntf.logging.set_verbosity(FLAGS.loglevel)\n\n#class mySaverListener(tf.train.CheckpointSaverListener):\n# def before_save(self, session, global_step_value):\n# print('the loss is: ')\n# print(tf.get_variable('mean loss'))\n \n# def after_save(self, session, global_step_value):\n# print('\n\ndef main(unused_argv):\n hparams = bot_hparams.create_hparams()\n\n run_config=tf.contrib.learn.RunConfig(\n model_dir=MODEL_DIR)\n \n model_fn = bot_model.create_model_fn(\n hparams,\n model_impl=model_impl)#hide in exec())\n\n def myEstimator(run_config):\n return tf.estimator.Estimator(\n model_fn=model_fn,\n #model_dir=MODEL_DIR,\n \t\t\tconfig=run_config)\n\n train_input_fn = bot_inputs.create_input_fn(\n mode=tf.estimator.ModeKeys.TRAIN,\n file_pattern=[TRAIN_FILE],\n batch_size=hparams.batch_size,\n num_epochs=FLAGS.num_epochs)\n\n eval_input_fn = bot_inputs.create_input_fn(\n mode=tf.estimator.ModeKeys.EVAL,\n file_pattern=[VALIDATION_FILE],\n batch_size=hparams.eval_batch_size,\n num_epochs=1)\n\n# saver=tf.train.Saver()\n\n# saverHook=tf.CheckpointSaverHook(\n# checkpoint_dir=MODEL_DIR,\n# save_steps=1000, #\n# saver=saver)\n\n def experiment_fn(run_config, hparams):\n return tf.contrib.learn.Experiment(\n estimator=myEstimator(run_config), # Estimator\n train_input_fn=train_input_fn, # First-class function\n eval_input_fn=eval_input_fn, # First-class function\n train_steps=FLAGS.train_steps, # Minibatch steps\n min_eval_frequency=FLAGS.eval_every, # Eval frequency\n #train_monitors=[train_input_hook], # Hooks for training\n #eval_hooks=[eval_input_hook], # Hooks for evaluation\n eval_steps=FLAGS.eval_steps ## Use evaluation feeder until its empty\n )\n \n learn_runner=tf.contrib.learn.learn_runner\n learn_runner.run(\n experiment_fn=experiment_fn, # First-class function\n run_config=run_config, # RunConfig\n schedule=\"train_and_evaluate\", # What to run\n hparams=hparams # HParams\n )\n \nif __name__ == \"__main__\":\n tf.app.run()","sub_path":"lstm/bot_train.py","file_name":"bot_train.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"111092288","text":"import json\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\nfrom django.urls import reverse\nfrom ..models import MenuItem\nfrom ..api.serializers import MenuItemSerializer\n\n\nclass MenuItemListViewTest(APITestCase):\n \"\"\" Test module for MenuItem List View \"\"\"\n\n def setUp(self):\n # Unnecessary, default objects are made via data migration\n pass\n\n def test_get_all_menu_items(self):\n response = self.client.get(reverse(\"menu-list-view\"))\n menu_items = MenuItem.objects.all()\n serializer = MenuItemSerializer(menu_items, many=True)\n # Assert all items from data migration are getting made\n self.assertEqual(menu_items.count(), 6)\n # Assert endpoint returns ok\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n # assert data is correct\n self.assertEqual(response.data, serializer.data)\n\n def test_menu_items_search(self):\n search_query = \"enchilada\"\n response = self.client.get(reverse(\"menu-list-view\"), {\"search\": search_query})\n menu_items = MenuItem.objects.filter(name__icontains=search_query)\n serializer = MenuItemSerializer(menu_items, many=True)\n # Assert correct number of items are being returned\n self.assertEqual(menu_items.count(), 2)\n # Assert endpoint returns ok\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n # assert data is correct\n self.assertEqual(response.data, serializer.data)\n\n def test_menu_items_ordering(self):\n ordering = [\"name\", \"-name\", \"price\", \"-price\"]\n for o in ordering:\n response = self.client.get(reverse(\"menu-list-view\"), {\"ordering\": o})\n menu_items = MenuItem.objects.all().order_by(o)\n serializer = MenuItemSerializer(menu_items, many=True)\n # Assert correct number of items are being returned\n self.assertEqual(menu_items.count(), 6)\n # Assert endpoint returns ok\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n # assert data is correct\n self.assertEqual(response.data, serializer.data)\n","sub_path":"back_end/menu/test/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"581918292","text":"from django.shortcuts import render\nfrom datetime import datetime\n\n# Create your views here.\ndef video(request, tvno):\n tv_list = [\n {'name': '明天再擱來', 'tvcode': 'D3cLm-AuMU0'},\n {'name': '愛我你會死', 'tvcode': 'j7mNwY6IJmQ'},\n {'name': '浪流連', 'tvcode': '3Y0Ut5ozaKs'},\n {'name': '我跟你卡好', 'tvcode': 'iTl5_n5saQU'}\n ]\n now = datetime.now()\n tvno = tvno\n tv = tv_list[tvno]\n return render(request, 'video.html', locals())\n","sub_path":"video/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"568092085","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"This file contains tests for the mrt_installer.py file.\n\nFor speciifics on each test, see the docstrings under each function.\nNote that if tests are failing, the self.start and self.end may need\nupdating to be more recent. Possibly same with the api_param_mods.\n\"\"\"\n\n__authors__ = [\"Justin Furuness\", \"Nicholas Shpetner\"]\n__credits__ = [\"Justin Furuness\", \"Nicholas Shpetner\"]\n__Lisence__ = \"BSD\"\n__maintainer__ = \"Justin Furuness\"\n__email__ = \"jfuruness@gmail.com\"\n__status__ = \"Development\"\n\n\nimport pytest\nimport os\nfrom .test_mrt_file import Test_MRT_File\nfrom ..mrt_installer import MRT_Installer\nfrom ...utils import utils\n\n\n@pytest.mark.mrt_parser\nclass Test_MRT_Installer:\n \"\"\"Tests all functions within the mrt installer class.\"\"\"\n\n def test_install_dependencies(self):\n \"\"\"Tests installation of dependencies\n Should be able to be called twice and not error\n Should test both bgpscanner and bgpdump to ensure they don't error\n -potentially borrow test from test_mrt_file for this\n \"\"\"\n bin_pkgs = [\"meson\",\n \"cmake\"]\n dpkg_pkgs = [\"zlib1g-dev\",\n \"libbz2-dev\",\n \"liblzma-dev\",\n \"liblz4-dev\"]\n test_installer = MRT_Installer()\n test_installer._install_bgpscanner_deps()\n for pkg in bin_pkgs:\n out = os.popen(\"ls /usr/bin | grep \" + pkg).read()\n assert out is not ''\n for pkg in dpkg_pkgs:\n out = os.popen(\"dpkg -l | grep \" + pkg).read()\n assert out is not ''\n assert os.popen(\"ls /usr/local/bin | grep ninja\").read() is not ''\n\n def test_debug_scaninstall(self):\n test_installer = MRT_Installer()\n test_installer._download_and_modify_bgpscanner()\n\n def test_install_bgpscanner(self):\n \"\"\"Tests installation of bgpscanner and dependencies\n\n First uninstall all dependencies listed.\n Then install all of them\n no files should be leftover\n Should be able to be called twice and not error\n Should test bgpscanner to ensure it doesn't error\n -potentially borrow test from test_mrt_file for this\n\n Should also assert that the lines in bgpscanner are changed\n -not sure how to do this with just an executable\n -potentially create an MRT file that has malformed announcements?\n -if you have trouble with this please contact me\n \"\"\"\n installer = MRT_Installer()\n filetest = Test_MRT_File()\n self.test_install_dependencies()\n installer._install_bgpscanner()\n filetest.test_bgpscanner_regex()\n\n def test_install_bgpdump(self):\n \"\"\"Tests installation of bgpdump and dependencies\n Should be able to be called twice and not error\n Should test bgpdump to ensure it doesn't error\n -potentially borrow test from test_mrt_file for this\n\n \"\"\"\n\n installer = MRT_Installer()\n filetest = Test_MRT_File()\n installer._install_bgpdump()\n print(\"Testing bgpdump\")\n filetest.test_bgpdump_regex()\n","sub_path":"lib_bgp_data/extrapolator/verification_parser/tests/test_mrt_installer.py","file_name":"test_mrt_installer.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"361151554","text":"# -*- coding: utf-8 -*-\n'''\n===============================================================================================\n练习\n请利用SAX编写程序解析Yahoo的XML格式的天气预报,获取天气预报:\n\nhttps://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=xml\n\n参数woeid是城市代码,要查询某个城市代码,可以在weather.yahoo.com搜索城市,浏览器地址栏的URL就包含城市代码。\n===============================================================================================\n'''\n\nfrom xml.parsers.expat import ParserCreate\nfrom urllib import request\n\n\n# ------------------------------------------------------------------------------------------------\n#\ndef parseXml(xml_str):\n # print(xml_str)\n\n class YHWeatherSaxHandler(object):\n def __init__(self):\n self.data = {'forecast': []}\n\n # 主要分析start_element事件,找到包含数据所在的name,从attrs里提取数据\n def start_element(self, name, attrs):\n if name == 'yweather:location':\n self.data['city'] = attrs['city']\n elif name == 'yweather:forecast':\n self.data['forecast'].append({\n 'date': attrs['date'],\n 'high': attrs['high'],\n 'low': attrs['low']\n })\n\n handler = YHWeatherSaxHandler()\n parser = ParserCreate()\n parser.StartElementHandler = handler.start_element\n parser.Parse(xml_str)\n return handler.data\n\n\n# ------------------------------------------------------------------------------------------------\n\n# ==========================================================================================\nif __name__ == '__main__':\n # 测试:\n URL = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=xml'\n\n with request.urlopen(URL, timeout=4) as f:\n data = f.read()\n\n result = parseXml(data.decode('utf-8'))\n assert result['city'] == 'Beijing'\n pass\n","sub_path":"notes/xmlModules.py","file_name":"xmlModules.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"118761138","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\n\nimport pandas as pd\n\ndf = pd.read_csv(\n 'https://gist.githubusercontent.com/chriddyp/'\n 'c78bf172206ce24f77d6363a2d754b59/raw/'\n 'c353e8ef842413cae56ae3920b8fd78468aa4cb2/'\n 'usa-agricultural-exports-2011.csv')\n\nb = df.loc[0, :].values\n\napp = dash.Dash()\n\n\ndef generate_table(df, max_rows=10):\n return html.Table(\n [html.Tr([html.Th(col) for col in df.columns])] +\n\n [html.Tr(\n [html.Td(i) for i in df.loc[k, :]] # We turn each value\n # of each row of the dataframe into an html.Td element\n ) for k in range(0, max_rows)]\n )\n\n\napp.layout = html.Div(style={\"backgroundColor\": \"#111111\", \"color\":\n \"#7FBFDD\", \"textAlign\": \"center \"},\n children=[\n html.H1(children=\"Creating a Dataframe table\"),\n\n html.Div(style={\n \"textAlign\": \"center\"},children=generate_table(\n df))\n ]\n )\n\nif __name__ == \"__main__\":\n app.run_server()\n","sub_path":"table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"329412796","text":"from __future__ import absolute_import, unicode_literals\n\n\nfrom gevent.pywsgi import WSGIServer\n\nfrom socketio.handler import SocketIOHandler\nfrom socketio.session import Session\n\nimport urlparse\n\nfrom logging import getLogger\nlogger = getLogger(\"socketio.server\")\n\n\n__all__ = ['SocketIOServer']\n\n\nclass SocketIOServer(WSGIServer):\n \"\"\"A WSGI Server with a resource that acts like an SocketIO.\"\"\"\n\n def __init__(self, *args, **kwargs):\n self._sessions = {}\n self.namespace = kwargs.pop('namespace', 'socket.io')\n self.cors_domain = kwargs.pop('cors', '')\n\n kwargs.pop('policy_server')\n kwargs.setdefault('handler_class', SocketIOHandler)\n super(SocketIOServer, self).__init__(*args, **kwargs)\n\n\n def get_session(self, sid):\n \"\"\"Return an existing or new client Session.\"\"\"\n session = self._sessions.get(sid, None)\n if session is not None:\n session.touch() # Touch the session as used\n return session\n\n def create_session(self, environ):\n \"\"\"\n Create a new session on the server.\n \"\"\"\n handshake_data = {\n \"query\": dict(urlparse.parse_qsl(environ[\"QUERY_STRING\"]))\n }\n session = Session(self, handshake_data)\n self._sessions[session.session_id] = session\n return session\n","sub_path":"socketio/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"336926688","text":"import os\nimport inspect\nimport warnings\nimport aiohttp\n\nfrom aiowinrm.sec.encryption import Encryption\nfrom aiowinrm.errors import InvalidCredentialsError, AIOWinRMException\nfrom aiowinrm.sec.request import PreparedRequest, AioWinRmRequestClass\nfrom aiowinrm.sec.response import AioWinRmResponseClass\n\nHAVE_KERBEROS = False\nHAVE_CREDSSP = False\nHAVE_NTLM = False\n\nKERB_ENCRYPTION_AVAILABLE = False\nNTLM_ENCRYPTION_AVAILABLE = False\n\ntry:\n from aiowinrm.sec.kerberos_ import \\\n HTTPKerberosAuth, \\\n REQUIRED, \\\n OPTIONAL, \\\n DISABLED, \\\n KERB_ENCRYPTION_AVAILABLE\n HAVE_KERBEROS = True\nexcept ImportError:\n pass\n\n\ntry:\n from aiowinrm.sec.ntlm_ import HttpNtlmAuth\n HAVE_NTLM = True\n NTLM_ENCRYPTION_AVAILABLE = True # since hasattr(ntlm_auth, 'session_security') anyway\nexcept ImportError as ie:\n pass\n\n\n\"\"\"\nNOT IMPLEMENTED (yet?)\nplease see requests_credssp for implementation\n\ntry:\n from aiowinrm.sec.credssp_ import HttpCredSSPAuth\n\n HAVE_CREDSSP = True\nexcept ImportError as ie:\n pass\n\"\"\"\n\n\nclass WindowsSession(aiohttp.ClientSession):\n\n def __init__(self,\n endpoint,\n username,\n password,\n realm,\n verify_ssl=True,\n service='HTTP',\n ca_trust_path=None,\n cert_pem=None,\n cert_key_pem=None,\n read_timeout_sec=None,\n kerberos_delegation=False,\n kerberos_hostname_override=None,\n auth_method='auto',\n message_encryption='auto',\n credssp_disable_tlsv1_2=False,\n send_cbt=True,\n keytab=None,\n connector=None,\n loop=None):\n self.endpoint = endpoint\n self.username = username\n self.password = password\n self.realm = realm\n self.service = service\n self.keytab = keytab\n self.ca_trust_path = ca_trust_path\n self.cert_pem = cert_pem\n self.cert_key_pem = cert_key_pem\n self.read_timeout_sec = read_timeout_sec\n self.verify_ssl = verify_ssl\n self.kerberos_hostname_override = kerberos_hostname_override\n self.message_encryption = message_encryption\n self.credssp_disable_tlsv1_2 = credssp_disable_tlsv1_2\n self.send_cbt = send_cbt\n self._server_cert = None\n self.auth_method = auth_method\n assert isinstance(kerberos_delegation, bool)\n self.kerberos_delegation = kerberos_delegation\n\n self.default_headers = {\n 'Content-Type': 'application/soap+xml; charset=utf-8',\n 'User-Agent': 'Python AioWinRM client',\n 'Connection': 'keep-alive'\n }\n\n # validate credential requirements for various auth types\n if self.auth_method != 'kerberos':\n if self.auth_method == 'certificate' or (\n self.auth_method == 'ssl' and (self.cert_pem or self.cert_key_pem)):\n if not self.cert_pem or not self.cert_key_pem:\n raise InvalidCredentialsError('both cert_pem and cert_key_pem must be specified for cert auth')\n if not os.path.exists(self.cert_pem):\n raise InvalidCredentialsError('cert_pem file not found (%s)' % self.cert_pem)\n if not os.path.exists(self.cert_key_pem):\n raise InvalidCredentialsError('cert_key_pem file not found (%s)' % self.cert_key_pem)\n\n else:\n if not self.username:\n raise InvalidCredentialsError('auth method %s requires a username' % self.auth_method)\n if self.password is None:\n raise InvalidCredentialsError('auth method %s requires a password' % self.auth_method)\n\n\n # Used for encrypting messages\n self.encryption = None # The Pywinrm Encryption class used to encrypt/decrypt messages\n if self.message_encryption not in ['auto', 'always', 'never']:\n raise AIOWinRMException(f'invalid message_encryption arg: {self.message_encryption} '\n f\"Should be 'auto', 'always', or 'never'\")\n\n self.auth = None\n super(WindowsSession, self).__init__(connector=connector,\n loop=loop,\n response_class=AioWinRmResponseClass,\n request_class=AioWinRmRequestClass)\n\n async def build_auth(self):\n # not using env vars\n\n encryption_available = False\n\n if self.auth_method == 'kerberos':\n if not HAVE_KERBEROS:\n raise AIOWinRMException('requested auth method is kerberos, '\n 'but requests_kerberos is not installed')\n\n man_args = dict(\n mutual_authentication=REQUIRED,\n )\n opt_args = dict(\n delegate=self.kerberos_delegation,\n force_preemptive=True,\n principal=self.username,\n hostname_override=self.kerberos_hostname_override,\n sanitize_mutual_error_response=False,\n service=self.service,\n send_cbt=self.send_cbt\n )\n kerb_args = self._get_args(man_args, opt_args, HTTPKerberosAuth.__init__)\n self.auth = HTTPKerberosAuth(**kerb_args)\n encryption_available = KERB_ENCRYPTION_AVAILABLE\n elif self.auth_method in ['certificate', 'ssl']:\n if self.auth_method == 'ssl' and not self.cert_pem and not self.cert_key_pem:\n # 'ssl' was overloaded for HTTPS with optional certificate auth,\n # fall back to basic auth if no cert specified\n user = f'{self.username}@{self.realm}' if self.realm else self.username\n self.auth = aiohttp.BasicAuth(user, self.password)\n else:\n self.cert = (self.cert_pem, self.cert_key_pem)\n self.default_headers['Authorization'] = \\\n 'http://schemas.dmtf.org/wbem/wsman/1/wsman/secprofile/https/mutual'\n elif self.auth_method == 'ntlm':\n if not HAVE_NTLM:\n raise AIOWinRMException('requested auth method is ntlm, but ntlm is not installed')\n user = self.username if '\\\\' in self.username else f'{self.realm}\\\\{self.username}'\n man_args = dict(\n username=user,\n password=self.password\n )\n opt_args = dict(\n send_cbt=self.send_cbt\n )\n ntlm_args = self._get_args(man_args, opt_args, HttpNtlmAuth.__init__)\n self.auth = HttpNtlmAuth(**ntlm_args)\n # check if requests_ntlm has the session_security attribute available for encryption\n encryption_available = hasattr(self.auth, 'session_security')\n # TODO: ssl is not exactly right here- should really be client_cert\n elif self.auth_method in ['basic', 'plaintext']:\n user = f'{self.username}@{self.realm}' if self.realm else self.username\n self.auth = aiohttp.BasicAuth(user, self.password)\n elif self.auth_method == 'credssp':\n if not HAVE_CREDSSP:\n raise AIOWinRMException('requests auth method is credssp, but requests-credssp is not installed')\n \"\"\"\n self.auth = HttpCredSSPAuth(username=self.username, password=self.password,\n disable_tlsv1_2=self.credssp_disable_tlsv1_2)\n encryption_available = hasattr(self.auth, 'wrap') and hasattr(self.auth, 'unwrap')\n \"\"\"\n else:\n raise AIOWinRMException('unsupported auth method: %s' % self.auth_method)\n\n # Will check the current config and see if we need to setup message encryption\n if self.message_encryption == 'always' and not encryption_available:\n raise AIOWinRMException(\n \"message encryption is set to 'always' but the selected auth method \"\n f'{self.auth_method} does not support it')\n elif encryption_available:\n if self.message_encryption == 'always':\n await self.setup_encryption()\n await self.setup_encryption()\n elif self.message_encryption == 'auto' \\\n and not self.endpoint.lower().startswith('https'):\n await self.setup_encryption()\n\n async def setup_encryption(self):\n \"\"\"\n Security context doesn't exist, sending blank message to initialise context\n \"\"\"\n\n prepared_request = PreparedRequest(url=self.endpoint,\n headers=self.default_headers.copy(),\n data=None)\n if callable(self.auth):\n self.auth(prepared_request)\n response = await self._send_prepared_request(prepared_request)\n if hasattr(self.auth, 'handle_response'):\n await self.auth.handle_response(response)\n self.encryption = Encryption(self.auth, self.auth_method)\n\n async def _send_prepared_request(self, prepared_request):\n \"\"\"\n After the request has been prepared this will send the request\n and check whether there is some decryption to be done\n\n :param prepared_request:\n :return:\n \"\"\"\n assert isinstance(prepared_request, PreparedRequest)\n assert 'Connection' in prepared_request.headers\n\n # basic auth is handled inside aiohttp rest is handled here\n aio_auth = self.auth if isinstance(self.auth, aiohttp.BasicAuth) else None\n\n resp = await self.post(url=prepared_request.url,\n data=prepared_request.data,\n headers=prepared_request.headers,\n auth=aio_auth)\n return await self.handle_encryption(resp)\n\n async def handle_encryption(self, response):\n \"\"\"\n Handles decrypting the response if encryption is enabled\n\n :param response:\n :return:\n \"\"\"\n response_content = await response.read()\n if self.encryption:\n if 'Content-Type' not in response.headers:\n raise Exception('Expected content-type in encrypted response')\n content_type = response.headers['Content-Type']\n decrypted = self.encryption.parse_encrypted_response(\n content_type=content_type,\n response_content=response_content,\n host=response.host)\n response.set_content(decrypted)\n return response\n\n def _get_args(self, mandatory_args, optional_args, function):\n argspec = set(inspect.getargspec(function).args)\n function_args = dict()\n for name, value in mandatory_args.items():\n if name in argspec:\n function_args[name] = value\n else:\n raise Exception('Function %s does not contain mandatory arg '\n '%s, check installed version with pip list'\n % (str(function), name))\n\n for name, value in optional_args.items():\n if name in argspec:\n function_args[name] = value\n else:\n warnings.warn('Function {function} does not contain optional arg'\n f' {name}, check installed version with pip list')\n\n return function_args\n\n async def winrm_request(self, url, data):\n \"\"\"\n Sets up auth and runs the request.\n If needed it will also decrypt the message.\n\n :param url:\n :param data:\n :return:\n \"\"\"\n if not self.auth:\n await self.build_auth()\n\n if self.encryption:\n prepared_request = self.encryption.prepare_encrypted_request(self.endpoint, data)\n else:\n prepared_request = PreparedRequest(url, headers=self.default_headers, data=data)\n\n resp = await self._send_prepared_request(prepared_request)\n if hasattr(self.auth, 'handle_response'):\n resp = await self.auth.handle_response(resp)\n return resp","sub_path":"aiowinrm/sec/windows_session.py","file_name":"windows_session.py","file_ext":"py","file_size_in_byte":12318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"168991921","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n\nimport os\nimport json\nimport jsonschema\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-s\", \"--src\", default=\"src\", help=\"Directory with data files (default: src/)\")\n parser.add_argument(\"-v\", \"--verbose\", action='store_true', help=\"Increase verbosity\")\n args = parser.parse_args()\n\n data_dir = args.src\n\n with open('schema.json') as schema_file:\n json_schema = json.load(schema_file)\n\n for file in [file for file in sorted(os.listdir(data_dir)) if file.endswith('.json')]:\n if args.verbose:\n print(\"[!] %s\" % file)\n\n with open(os.path.join(data_dir, file)) as json_file:\n try:\n json_data = json.load(json_file)\n except ValueError as e:\n raise jsonschema.ValidationError(\"%s in %s\" % (e, file)) from e\n\n for primarie in json_data:\n try:\n jsonschema.validate(primarie, json_schema)\n except jsonschema.exceptions.ValidationError as e:\n raise jsonschema.ValidationError(\"File: %s\" % file) from e\n","sub_path":"test/runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"476242776","text":"from imageboard.errors import *\nfrom imageboard.helpers import *\nfrom imageboard.models import Board\n\n__all__ = [\n 'api_boards_list',\n 'api_board_detail',\n 'api_board_create',\n 'api_board_update',\n 'api_board_delete'\n]\n\n\nasync def api_boards_list(request):\n return JSONResponse(await Board.get_all())\n\n\nasync def api_board_detail(request):\n try:\n return JSONResponse(await Board.get(argv(request, 'board_id', cast=int)))\n except NotFound:\n return JSONNotFound()\n\n\nasync def api_board_create(request):\n data = await request.json()\n\n try:\n name = data['name']\n except KeyError:\n return JSONBadRequest()\n\n try:\n return JSONCreated(await Board.create(name=name))\n except Conflict:\n return JSONConflict()\n except AssertionError:\n return JSONBadRequest()\n\n\nasync def api_board_update(request):\n data = await request.json()\n\n try:\n return JSONCreated(await Board.update(argv(request, 'board_id', cast=int),\n name=data.get('name')))\n except NotFound:\n return JSONNotFound()\n except Conflict:\n return JSONConflict()\n except AssertionError:\n return JSONBadRequest()\n\n\nasync def api_board_delete(request):\n try:\n return JSONDeleted(await Board.delete(argv(request, 'board_id', cast=int)))\n except NotFound:\n return JSONNotFound()\n except Conflict:\n return JSONConflict()\n","sub_path":"imageboard/handlers/boards.py","file_name":"boards.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"643759444","text":"from flask_cors import CORS\nfrom flask.logging import create_logger\nfrom flask import Flask, jsonify, request, render_template, url_for\nimport os\nimport time\n\napp = Flask(__name__)\nLOG = create_logger(app)\napp.secret_key = \"super secret key\"\nCORS(app)\n\n@app.route(\"/\")\ndef home():\n return render_template('index.html')\n\n@app.route(\"/api\")\ndef default_route():\n LOG.debug('this is a DEBUG message')\n LOG.info('this is an INFO message')\n LOG.warning('this is a WARNING message')\n LOG.error('this is an ERROR message')\n LOG.critical('this is a CRITICAL message')\n return jsonify('hello world')\n\n@app.route(\"/api/health\", methods=[\"GET\"])\ndef get_health():\n stats = \"{'status':'completed','platform':'healthy'}\"\n return jsonify(stats)\n\n\n@app.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers',\n 'Content-Type,Authorization')\n response.headers.add('Access-Control-Allow-Methods',\n 'GET,PUT,POST,DELETE,OPTIONS')\n return response\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True, port=80)\n","sub_path":"Main/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"73257412","text":"class Solution:\n def findMaximumXOR(self, nums: List[int]) -> int:\n L = len(bin(max(nums))) - 2\n nums = [[(num >> i) & 1 for i in range(L)][::-1] for num in nums]\n maxXor, trie = 0, {}\n for num in nums:\n currentNode, xorNode, currentXor = trie, trie, 0\n for bit in num:\n currentNode = currentNode.setdefault(bit, {})\n toggledBit = 1 - bit\n if toggledBit in xorNode:\n currentXor = (currentXor << 1) | 1\n xorNode = xorNode[toggledBit]\n else:\n currentXor = currentXor << 1\n xorNode = xorNode[bit]\n maxXor = max(maxXor, currentXor)\n return maxXor","sub_path":"LeetCode/Trie/Maximum XOR of Two Numbers in an Array.py","file_name":"Maximum XOR of Two Numbers in an Array.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439413263","text":"from django.contrib.gis.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\n\n\nclass TipoDenunciaManager(models.GeoManager):\n\tdef tipoDenunciasArround(self,geom):\n\t\tparceiros = Parceiro.objects.filter(cobertura__contains=geom).values_list('interesse__pk', flat=True)\n\t\treturn TipoDenuncia.objects.filter(pk__in=parceiros)\n\n\n\nclass TipoDenuncia(models.Model):\n\tnome = models.CharField(max_length=100)\n\tsigla = models.CharField(max_length=3, unique=True)\n\timagem = models.ImageField(upload_to='TipoDenuncia/', blank=True, null=True)\n\tdescricao = models.TextField(max_length=500)\n\tobjects = TipoDenunciaManager()\n\n\tdef __str__(self):\n\t\treturn self.nome\n\n# Create your models here.\nclass DenunciaManager(models.GeoManager):\n\tdef denunciasByUUID(self,uuid):\n\t\treturn Denuncia.objects.filter(device_uuid=uuid)\n\n\tdef denunciasParceiro(self,user):\n\t\tinteresse = Parceiro.objects.filter(pk=user.pk).values_list('interesse__pk', flat=True)\n\t\treturn Denuncia.objects.filter(local__contained=user.cobertura, tipo__in=set(interesse))\n\n\t\t\n\n\nclass Denuncia(models.Model):\n\tRESOLVIDA = 'RE'\n\tANDAMENTO = 'AN'\n\tAGUARDANDO = 'AG'\n\tSTATUS_CHOICES = (\n\t\t(RESOLVIDA, 'Resolvida'),\n\t\t(ANDAMENTO, 'Em Andamento'),\n\t\t(AGUARDANDO, 'Aguardando')\n\t)\n\ttipo = models.ForeignKey(TipoDenuncia)\n\tstatus = models.CharField(max_length=2, choices=STATUS_CHOICES, default=AGUARDANDO)\n\tdatadenuncia = models.DateTimeField(default=timezone.now)\n\tdevice_uuid = models.CharField(max_length=50)\n\tlocal = models.PointField(srid=4326)\n\tdescricao = models.TextField(max_length=1000, blank=True, null=True)\n\timagem = models.FileField(upload_to='denuncia/%Y/%m/%d/', blank=True, null=True)\n\taudio = models.FileField(upload_to='denuncia/%Y/%m/%d/', blank=True, null=True)\n\tvideo = models.FileField(upload_to='denuncia/%Y/%m/%d/', blank=True, null=True)\n\tobjects = DenunciaManager()\n\n\tdef __str__(self):\n\t\treturn self.tipo.sigla + \" - \" + self.descricao[:30]\n\nclass Parceiro(models.Model):\n\tprofile = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)\n\tinteresse = models.ManyToManyField(TipoDenuncia, blank=True)\n\tnome = models.CharField(max_length=50)\n\ttelefone = models.CharField(max_length=10)\n\tcelular = models.CharField(max_length=11)\n\tcobertura = models.MultiPolygonField(srid=4326)\n\tsedes = models.MultiPointField(srid=4326, blank=True, null=True)\n\tobjects = models.GeoManager()\n\n\tdef __str__(self):\n\t\treturn self.nome","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"121219451","text":"from grafo import Vertice, Grafo\t\t\n# main \nvertices = []\ntry:\n f = open(\"entrada.txt\")\n copia = f.read() \nfinally:\n f.close() \n\nfor c in copia: \n\tif(c != '-' and c != ' ' and c != '\\n' and c != '\\t'): \n\t\tif(c not in vertices): \n\t\t\tvertices.append(c) \t\t\t \narestas = [] \nfor i in range(len(copia)): \n\tif(copia[i] == '-'): \n\t\tarestas.append(copia[i-1]+copia[i]+copia[i+1]) \n\nvertices = sorted(vertices) \nvetor_auxiliar = [] \ng = Grafo() \nprint(vertices)\nfor v in vertices: \n\tx = Vertice(v) \n\tg.add_vertice(x) \n\tvetor_auxiliar.append(x) \n\n## adiciona vetores com vertices e arestas no grafo\t \ng.vetor_auxiliar = vetor_auxiliar \ng.arestasaux = arestas\t \n\n# print(str(len(g.vertices)))\n#u = Vertice('U')\n#g.add_vertice(u) \n#v = Vertice('V')\n#g.add_vertice(v) \n#w = Vertice('W')\n#g.add_vertice(w) \n#x = Vertice('X')\n#g.add_vertice(x) \n#y = Vertice('Y')\n#g.add_vertice(y) \n#z = Vertice('Z')\n#g.add_vertice(z) \n\n#vetor_auxiliar.append(u)\n#vetor_auxiliar.append(v) \n#vetor_auxiliar.append(w) \n#vetor_auxiliar.append(x) \n#vetor_auxiliar.append(y) \n#vetor_auxiliar.append(z)\n#g.add_vertice(Vertice('B')) \n#cria um vetor de vertices de A té D\n#g.add_vetor_vertices('A','C') \n\n#cria o vetor de arestas\n# insere tais arestas no grafo \n#arestas = ['1-2','2-1'] \ng.add_vetor_arestas(arestas) \n#mostra o grafo\n#g.print_grafo() \n# procura o grau de algum vertice no grafo \n#g.get_grau('C') \n# verifica se dois vertices são adjacentes\n#g.sao_adjacentes('C','C') \n# mostra uma lista de vertices adjacentes a este vertice\n#g.get_adjacentes('A') \n# todos vertices se ligam com todos \n#g.is_completo() \n#conexo = g.is_conexo() \n\n#if(conexo == 1): \n#\tprint('É conexo') \n#g.is_arvore() \n\n# fecho transitivo direto de um vértice do grafo \n## = conjunto de vertices que se chega a partir \n## deste vertice, lembrando que o grafo é digrafo \n#g.ftd_vertice('B') \n \n# fecho transitivo indireto de um vértice do grafo \n## é o conjunto de vertices que chegam nesse grafo \n## por algum caminho existente \n#g.fti_vertice('B')\n#g.get_grau_entrada('A')\n#g.get_grau_saida('A')\n#g.get_grau_entrada('A') \n\n#g.getOrdem() \n#g.getVertices() \n \n \n# busca em largura \n#g.busca_em_largura('1')\t \n\n# busca em profundidade\t \n#g.busca_em_profundidade() \n#for v in vetor_auxiliar: \n#\tv.mudar_cor('Branco')\t\t \n\n#g.print_grafo()\nmaiores = [] \nfor v in vetor_auxiliar: \n# realiza a busca em largura e pega altura desse nó\n\tdistanciam = g.busca_em_largura(v) \n# limpa as cores dos vertices\n\tfor d in vetor_auxiliar: \n\t\td.mudar_cor('Branco') \n\tmaiores.append(distanciam) \n\t#print(distanciam)\nprint(maiores)\t \nmenor = 1 \ncount = 0\nfor m in maiores: \n\tcount += 1 \n\tif(m <= menor and m != 0): \n\t\tmenor = m \n\t\tindice = count \n\nprint('A menor distância entre as maiores é :')\t\t\t \nprint(menor)\t \t \nprint('Então o vértice escolhido para o posto é:')\nprint(vetor_auxiliar[indice-1].name)","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"188246842","text":"#!/usr/bin/python3\r\n\r\nimport pymysql\r\n\r\n\r\ndef sqlwrite(tablenum,list):\r\n db = pymysql.connect(\"localhost\", \"Aries\", \"aries\", \"pystadb\")\r\n cursor = db.cursor()\r\n\r\n if tablenum == 1:\r\n table = \"structure\"\r\n for i in range(19):\r\n sql = \"INSERT INTO \" + table + \"(year,total,young,mid,old) \\\r\n VALUES (%s,%s,%s,%s,%s)\" % \\\r\n (list[i][0], list[i][1], list[i][2], list[i][3], list[i][4])\r\n try:\r\n # 执行sql语句\r\n cursor.execute(sql)\r\n # 提交到数据库执行\r\n db.commit()\r\n except:\r\n # 如果发生错误则回滚\r\n db.rollback()\r\n\r\n elif tablenum == 2:\r\n table = \"consumption\"\r\n for i in range(9):\r\n sql = \"INSERT INTO \" + table + \"(year,allmoney,ruralmoney,urbanmoney,allindex,ruralindex,urbanindex) \\\r\n VALUES (%s,%s,%s,%s,%s,%s,%s)\" % \\\r\n (list[i][0], list[i][1], list[i][2], list[i][3], list[i][4],\r\n list[i][5], list[i][6])\r\n try:\r\n # 执行sql语句\r\n cursor.execute(sql)\r\n # 提交到数据库执行\r\n db.commit()\r\n except:\r\n # 如果发生错误则回滚\r\n db.rollback()\r\n\r\n # 关闭数据库连接\r\n db.close()\r\n\r\n\r\ndef sqlread(table, name, info):\r\n db = pymysql.connect(\"localhost\", \"Aries\", \"aries\", \"pystadb\")\r\n cursor = db.cursor()\r\n\r\n sql = \"SELECT * FROM %s \\\r\n WHERE %s = %s\" % (table, name, info)\r\n try:\r\n cursor.execute(sql)\r\n results = cursor.fetchall()\r\n except:\r\n print(\"Error: unable to fetch data\")\r\n\r\n db.close()\r\n return results\r\n\r\n\r\ndef sqlclear(table):\r\n db = pymysql.connect(\"localhost\", \"Aries\", \"aries\", \"pystadb\")\r\n cursor = db.cursor()\r\n if table == 1:\r\n name = \"structure\"\r\n elif table == 2:\r\n name = \"consumption\"\r\n\r\n sql = \"DELETE FROM \"+name+\" WHERE year > 0\"\r\n try:\r\n cursor.execute(sql)\r\n db.commit()\r\n except:\r\n db.rollback()\r\n\r\n db.close()\r\n\r\n\r\n","sub_path":"dbop.py","file_name":"dbop.py","file_ext":"py","file_size_in_byte":2199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"428959674","text":"from jinja2 import Environment, FileSystemLoader\nfrom os import path, listdir, makedirs\nfrom shutil import rmtree\n\n\ndef render_file(output_path, body):\n makedirs('output/{}'.format(output_path), exist_ok=True)\n with open('output/{}/Dockerfile'.format(output_path), 'w') as rendered:\n rendered.write(body)\n\n\ndef jinja2_generator(template_name, **kwargs):\n return Environment(loader=FileSystemLoader('templates')).get_template(template_name).render(kwargs)\n\n\nif __name__ == '__main__':\n php_versions = [7.2] # render php versions\n templates = listdir(path.join('templates'))\n for template in templates:\n rmtree('output') if path.exists('output') else print('output path created')\n for version in php_versions:\n template_name = template.split('.')[-2]\n dockerfile = jinja2_generator(template, php_version=version)\n render_file('{}/{}'.format(version, template_name), dockerfile)\n","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"299486656","text":"from store import Store\nimport pathlib\n\n\nclass UserMenu:\n def __init__(self):\n self.store = Store()\n self.menu_items = {\"1\": self.process_web_orders, \"2\": self.check_inventory}\n\n def print_options(self):\n print(\"Main Menu\")\n print(\"1. Process Web Orders\")\n print(\"2. Check Inventory\")\n print(\"3. Exit\")\n\n def main_menu(self):\n while True:\n self.print_options()\n choice = \"\"\n while True:\n choice = input()\n if choice == \"3\" or choice in self.menu_items:\n break\n print(f\"{choice} is not a valid choice\")\n if choice == \"3\":\n break\n self.menu_items[choice]()\n\n print(\"Closing program...\")\n\n def process_web_orders(self):\n print(\"Please input the path of your order file\")\n while True:\n choice = pathlib.Path(input())\n if not choice.is_dir() and choice.exists():\n break\n print(f\"{choice} is not a valid choice\")\n self.store.process_orders(choice)\n\n def check_inventory(self):\n for item in self.store.check_inventory():\n print(f\"{item[3].value} | {item[0]} | {item[1]} | {item[2]}\")\n\n\nif __name__ == '__main__':\n menu = UserMenu()\n menu.main_menu()\n","sub_path":"Assignments/Assignment2/user_menu.py","file_name":"user_menu.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78884920","text":"# -*- coding: utf-8 -*-\n\nimport pytest\nfrom hamcrest import assert_that, equal_to_ignoring_whitespace, is_\n\nfrom hermes.interventions import InterventionsApi\n\n\nclass TestNegativeInterventionUpdate(object):\n\n @pytest.mark.parametrize('base_q', [0, 100500, \"QWErty\"])\n def test_negative_update_intervention(self, logged_client, config, base_q):\n intrv_id = config['intervention2']['id']\n code, result = InterventionsApi.update_intervention(\n intrv_id=intrv_id, baseline_question_id=base_q)\n assert_that(code, is_(404),\n 'Expected that code is \"%s\", but was \"%s\".' % (404, code))\n err_msg = 'Question #%s not found' % base_q\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that error message is \"%s\", but was \"%s\".' % (\n err_msg, result['error']\n ))\n\n @pytest.mark.parametrize('q_ids', [\n [0],\n [100500],\n [\"QWERTY\"],\n [None]\n ])\n def test_negative_update_interventions_with_q_ids(self, logged_client,\n config, q_ids):\n intrv_id = config['intervention2']['id']\n code, result = InterventionsApi.update_intervention(\n intrv_id=intrv_id, question_ids=q_ids)\n assert_that(code, is_(404),\n 'Expected that code is \"%s\", but was \"%s\".' % (404, code))\n if q_ids[0] is None:\n q_ids[0] = 'nil'\n if q_ids[0] is \"QWERTY\":\n q_ids[0] = '\"QWERTY\"'\n err_msg = 'Questions: [%s] do not exist' % q_ids[0]\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that error is \"%s\", but was \"%s\".' % (\n err_msg, result['error']\n ))\n\n @pytest.mark.parametrize('intrv_id', [0, 100500, None, 'qwerty'])\n def test_update_non_existed_intervention(self, logged_client, intrv_id):\n code, result = InterventionsApi.update_intervention(intrv_id=intrv_id)\n assert_that(code, is_(404),\n 'Expected that code is \"%s\", but was \"%s\".' % (404, code))\n err_msg = 'Unable to find intervention with id: %s' % intrv_id\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that err msg is \"%s\", but was \"%s\".' % (\n err_msg, result['error']\n ))\n\n def test_update_intervention_to_be_without_questions(self, config,\n logged_client):\n code, result = InterventionsApi.update_intervention(\n intrv_id=config['intervention2']['id'], question_ids=[])\n assert_that(code, is_(422),\n 'Expected that code is \"%s\", but was \"%s\".' % (422, code))\n err_msg = 'An intervention must have atleast one question' \\\n ' associated with it.'\n assert_that(result['error'], equal_to_ignoring_whitespace(err_msg),\n 'Expected that err msg is \"%s\", but was \"%s\".' % (\n err_msg, result['error']\n ))\n","sub_path":"hermes_api_tests/tests/a-interventions/test_negative_intervention_update.py","file_name":"test_negative_intervention_update.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190601053","text":"\"\"\"\nCopyright (c) 2017, Jairus Martin.\n\nDistributed under the terms of the MIT License.\n\nThe full license is in the file COPYING.txt, distributed with this software.\n\nCreated on July 10, 2017\n\n@author: jrm\n\"\"\"\nimport os\nimport fnmatch\nfrom setuptools import setup\n\n\ndef find_data_files(dest, *folders):\n matches = {}\n #: Want to install outside the venv volder in the packages folder\n dest = os.path.join('packages', dest)\n\n excluded_types = ['.pyc', '.enamlc', '.apk', '.iml','.zip', '.tar.gz', '.so', '.gif', '.svg']\n excluded_dirs = ['android/build', 'android/captures', 'android/assets',\n 'python-for-android/doc', 'bootstraps/pygame', 'python-for-android/testapps',\n 'python-for-ios/tools/external']\n for folder in folders:\n if not os.path.isdir(folder):\n k = os.path.join(dest, dirpath)\n matches[k].append(os.path.join(dest,folder))\n continue\n for dirpath, dirnames, files in os.walk(folder):\n #: Skip build folders and exclude hidden dirs\n if ([d for d in dirpath.split(\"/\") if d.startswith(\".\")] or\n [excluded_dir for excluded_dir in excluded_dirs if excluded_dir in dirpath]):\n continue\n k = os.path.join(dest, dirpath)\n if k not in matches:\n matches[k] = []\n for f in fnmatch.filter(files, '*'):\n if [p for p in excluded_types if f.endswith(p)]:\n continue\n m = os.path.join(dirpath, f)\n matches[k].append(m)\n return matches.items()\n\n\nsetup(\n name=\"enaml-native-cli\",\n version=\"1.5.5\",\n author=\"CodeLV\",\n author_email=\"frmdstryr@gmail.com\",\n license='MIT',\n url='https://github.com/codelv/enaml-native-cli/',\n description=\"Build native mobile apps in python\",\n scripts=['enaml-native'],\n long_description=open(\"README.md\").read(),\n data_files=find_data_files('enaml-native-cli', 'android', 'ios',\n 'python-for-android', 'python-for-ios'),\n install_requires=[\n 'appdirs', 'colorama>=0.3.3', 'sh==1.12.4', 'jinja2', 'six',\n 'pipdeptree', 'atom', 'ply'\n ],\n setup_requires=['virtualenv'],\n test_requires=['requests', 'py.test', 'pytest-cov', 'pytest-catchlog',\n 'pytest-timeout']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"411270293","text":"import pandas as pd \r\nimport pickle\r\nimport numpy as np \r\n\r\ndef getReunionData():\r\n\tarr = []\r\n\tfor line in open('C:/Users/renu/Desktop/django_projects/beproject/beproject/training.txt', 'r'):\r\n\t\tline = list(map(float, line.split(\",\")))\r\n\t\tarr.append(line)\r\n\r\n# (81714, 230) -> (23, 81714, 10)\r\n\tarr = np.array(arr).reshape(23, 81714, 10)\r\n\tsc = pickle.load(open('C:/Users/renu/Desktop/django_projects/beproject/beproject/my_scaler.pkl','rb'))\r\n\r\n\tdata = []\r\n\tfor single_arr in arr:\r\n\t\tdata.append(sc.transform(single_arr))\r\n\t\r\n\treturn np.array(data)","sub_path":"beproject/getReunionIsland.py","file_name":"getReunionIsland.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"208892183","text":"__author__ = 'Tian'\n'''\nIf an element in a matrix is 0, set its entire row and column to 0\n'''\ndef setZeros(matrix=[[1, 2, 3],[4, 0, 6],[7, 8, 9]]):\n print('Original matrix:')\n printMatrix(matrix)\n m = len(matrix)\n n = len(matrix[0])\n\n row = [False]*m\n col = [False]*n\n\n for i in range(m):\n for j in range(n):\n if matrix[i][j] == 0:\n row[i] = True\n col[j] = True\n\n for i in range(m):\n for j in range(n):\n if row[i] == True or col[j] == True:\n matrix[i][j] = 0\n\n print('\\nAfter change:')\n printMatrix(matrix)\n return matrix\n\ndef printMatrix(matrix):\n n = len(matrix)\n for row in matrix:\n print(row)\n\ndef makeMatrix(n):\n return [[1]*n for x in range(n)]\n\nif __name__ == \"__main__\":\n setZeros()\n","sub_path":"ArraysAndString/setZeros.py","file_name":"setZeros.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"452030283","text":"from selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nimport chromedriver_binary\r\nimport urllib\r\nimport time\r\n##\r\nfrom selenium import webdriver\r\nfrom webdriver_manager.chrome import ChromeDriverManager\r\n\r\nprint ('start...')\r\n\r\nsite = \"https://invest.yandex.ru/catalog/fund/fxwo/\"\r\n\r\nchrome_options = Options()\r\nchrome_options.add_argument(\"--headless\")\r\n\r\ndriver = webdriver.Chrome(options=chrome_options)\r\ndriver = webdriver.Chrome(ChromeDriverManager().install())\r\n#driver = webdriver.Chrome()\r\ndriver.get(site)\r\n\r\n#one_prise = driver.find_element_by_id(\"root\")\r\n#print (one_prise)\r\n#print('нихуя но все же норм')\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\ndef big_broker(price):\r\n price2 = price\r\n def broker(price2):\r\n #селениу��#\r\n site = \"https://invest.yandex.ru/catalog/fund/fxwo/\"\r\n\r\n chrome_options = Options()\r\n chrome_options.add_argument(\"--headless\")\r\n\r\n driver = webdriver.Chrome(options=chrome_options)\r\n driver = webdriver.Chrome(ChromeDriverManager().install())\r\n #driver = webdriver.Chrome()\r\n driver.get(site)\r\n #селениум#\r\n url = 'https://invest.yandex.ru/catalog/fund/fxwo/'\r\n response = requests.get(url)\r\n soup = BeautifulSoup(response.text, 'lxml')\r\n quotes = soup.find('div', class_='_2NhGI8HVO_OG2E2pWl10IY')\r\n for i in quotes:\r\n quotes = i\r\n quotes = quotes.replace('₽','')\r\n quotes = quotes.replace(' ','') # чистим цифры\r\n\r\n newquotes = \"\"\r\n b = 0\r\n for i in quotes:\r\n b +=1\r\n if b < 7 and i != ',': # убираем запятую\r\n newquotes += i\r\n quotes = newquotes # 18440\r\n old_price = int(newquotes)\r\n #print(old_price)\r\n print ('Старая цена' + str(price2))\r\n print ('Новая цена' + str(old_price))\r\n #print (old_price)\r\n if price2 < old_price:\r\n print ('продаю')\r\n sell = driver.ffind_element_by_xpath(\"Icon Icon_svg Icon_type_star-outline Button2-Icon2\").click()\r\n if price2 == old_price:\r\n print ('держу')\r\n if price2 > old_price:\r\n print ('покупаю')\r\n return old_price # выводим спарсенное число\r\n\r\n i = 0\r\n while i < 5:\r\n new_price = broker(price2) # вызываем функцию с новым значением\r\n #print (new_price)\r\n price = new_price\r\n return price # выводим спарсенное число\r\n#print(quotes)\r\nprice = 0\r\nbig = big_broker(price)\r\nprice = big\r\nh = 0\r\nwhile h <3:\r\n big_broker(price) # вызываем главную функцию\r\n h+=1\r\n","sub_path":"broker.py","file_name":"broker.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583151270","text":"\"\"\"\nhttps://leetcode.com/problems/graph-valid-tree\n\nGiven n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge\nis a pair of nodes), write a function to check whether these edges make up a\nvalid tree.\n\nFor example:\n\nGiven n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.\n\nGiven n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.\n\nNote: you can assume that no duplicate edges will appear in edges. Since all\nedges are undirected, [0, 1] is the same as [1, 0] and thus will not appear\ntogether in edges.\n\"\"\"\n\n\nclass Solution(object):\n def validTree_BFS(self, n, edges):\n \"\"\"\n :type n: int\n :type edges: List[List[int]]\n :rtype: bool\n\n There are three solutions: BFS, DFS and union find.\n \"\"\"\n\n # BFS\n if len(edges) != n - 1:\n return False\n neighbors = {i: [] for i in range(n)}\n for v, w in edges:\n neighbors[v] += w,\n neighbors[w] += v,\n\n queue = [0]\n for v in queue:\n queue.extend(neighbors.pop(v, []))\n\n return not neighbors\n\n def validTree_DFS(self, n, edges):\n if len(edges) != n - 1:\n return False\n neighbors = {i: [] for i in range(n)}\n for v, w in edges:\n neighbors[v].append(w)\n neighbors[w].append(v)\n\n def visit(v):\n map(visit, neighbors.pop(v, []))\n\n visit(0)\n return not neighbors\n\n def validTree_UnionFind(self, n, edges):\n if len(edges) != n-1:\n return False\n\n s = range(n)\n\n def find(v):\n return v if s[v] == v else find(s[v])\n\n def union(edge):\n v, w = map(find, edge)\n s[v] = w\n return v != w\n\n return all(map(union, edges))\n\n\nprint(Solution().validTree_UnionFind(5, [[0, 1], [1, 2], [2, 3], [1, 3]]))\n","sub_path":"leetcode/facebook/graph-valid-tree.py","file_name":"graph-valid-tree.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"335316669","text":"\"\"\"\nBasic image sequence functions.\n\"\"\"\n\nfrom ..Template import Template\n\ndef padding(frame, size):\n \"\"\"\n Return the frame with the padding size specified.\n \"\"\"\n return str(int(frame)).zfill(int(size))\n\ndef retimePadding(frame, retime, size):\n \"\"\"\n Return the frame with the padding size specified.\n \"\"\"\n return str(int(frame) + int(retime)).zfill(int(size))\n\n\n# frame padding\nTemplate.registerProcedure(\n 'pad',\n padding\n)\n\n# re-time frame padding\nTemplate.registerProcedure(\n 'retimepad',\n retimePadding\n)\n","sub_path":"src/lib/kombi/Template/procedures/imageSequenceProcedures.py","file_name":"imageSequenceProcedures.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"455601849","text":"#(9) 소수 찾기\n\nfrom itertools import permutations\ndef search(n):\n n_list = set([num for num in range(3, n+1, 2)])\n for i in range(3, n+1, 2):\n if i in n_list:\n n_list -= set([i for i in range(i*2, n+1, i)])\n return n_list | set([2])\n\ndef solution(numbers):\n number_list = set([int(\"\".join(item)) for i in range(7) for item in set(permutations(list(numbers), i + 1))])\n search_number_list = search(pow(10,len(numbers)))\n return len(number_list - (number_list - search_number_list))\n\t","sub_path":"level2/level2_ex09.py","file_name":"level2_ex09.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93401861","text":"import os\n\nnumberOfSections = raw_input( \"How many training sections would you like to break file into?\" )\n\nanswer = raw_input( \"Would you like to use the sliding window technique? (Y/N) \" )\n\nif answer == \"N\":\n\n numberOfTestSections = raw_input( \"How many test sections would you like? \" )\n\nif answer == \"Y\":\n\n numberOfDataPoints = raw_input( \"How many data points would you like for each file \" )\n \ndataSetsFileName = str( raw_input ( \"What is the name of your data set?\" ) ) #Reads in list of files to segments\n\noutputFile = \"adjustedDataSets.dat\" #The file representing the segmented results\ntestOutputFile = \"DataSetsForClassification.dat\" #Files to be used for classification\n\nmodelsOutputFile = \"models.dat\" #the model files output\n\ndataFileIncrementer = 0\n \ntmpDataSetsFile = open( dataSetsFileName, \"r\" ) #used the find the size of the array\nnumberOfOutputFiles = len( tmpDataSetsFile.readlines( ) ) * numberOfSections\n\ndataSetsOutput = open( outputFile, \"w\" )\ndataToClassifyOutput = open( testOutputFile, \"w\" )\n\nmodelsOutput = open( modelsOutputFile, \"w\" )\n\ndataSetsFile = open( dataSetsFileName, 'r' )\n\nos.chdir(\"dataSets\")\n\n \nfor line in sorted( dataSetsFile.readlines() ):\n dataFile = open( (line + \".dat\").replace(\"\\n\",\"\"), 'r' )\n \n numberOfPoints = len( dataFile.readlines() )\n dataFile.seek( 0 ) \n \n #answer = str( raw_input( \"Would you like to use the sliding window technique? (Y/N) \" ) ) \n \n for i in xrange( 0, int( numberOfSections ) ):\n \n output = open( ( line + \"-\" + str( i ) + \".dat \" ).replace( \"\\n\",\"\" ), 'w' )\n \n for j in xrange( 0, int( numberOfPoints ) / ( int( numberOfSections ) + 1 ) ):\n\n output.write( dataFile.readline( ) )\n \n dataSetsOutput.write( \"dataSets\\\\\" + ( line + \"-\" + str( i ) ).replace( \"\\n\", \"\" ) + \"\\n\" ) \n \n os.chdir( \"../\" )\n modelsOutput.write( \"dataSets\\\\\" + ( line + \"-\" + str( i ) + \"-model.dat\" ).replace( \"\\n\", \"\" ) + \"\\n\" )\n os.chdir( \"dataSets\" )\n\n if answer == \"N\":\n \n for i in xrange( 0, int( numberOfTestSections ) ):\n \n if line == \"stand\" :\n \n l = \"stnd\"\n\n else:\n \n l = line\n \n output = open( ( l + \"-test-\" + str( i ) + \".dat \" ).replace( \"\\n\",\"\" ), 'w' )\n \n for j in xrange( 0, ( int( numberOfPoints ) - int( numberOfPoints ) / 2 ) / ( int( numberOfTestSections ) ) ):\n\n output.write( dataFile.readline( ) )\n \n dataToClassifyOutput.write( (l + \"-test-\" + str( i ) + \" \").replace( \"\\n\", \"\" ) )\n \n else:\n \n dataFiles = dataFile.readlines( )\n \n #print dataFiles\n \n startIndex = 0\n endIndex = int( numberOfDataPoints )\n \n #Increments everytime I write out a file name for a format like: test-0, test-1, test-2\n fileIncrementer = 0\n \n numberOfLinesLeft = len( dataFiles )\n \n #Create data files while there is enough remaining points\n while( endIndex <= len( dataFiles ) ):\n \n output = open( ( line + \"-test-\" + str( fileIncrementer ) + \".dat \" ).replace( \"\\n\",\"\" ), 'w' )\n \n for i in xrange( startIndex, endIndex ):\n \n # print i\n output.write( dataFiles[ i ] )\n \n numberOfLinesLeft -= 1\n \n dataToClassifyOutput.write( (line + \"-test-\" + str( fileIncrementer ) + \" \").replace( \"\\n\", \"\" ) )\n fileIncrementer += 1\n \n startIndex += 1\n endIndex += 1\n \n \nmodelsOutput = open ( modelsOutputFile, \"a\" )\n \nmodelsOutput.write( \"t\" )\n","sub_path":"2013_MobileCloudFallDetection/Working TDE GTM Classify Trajectory CMD LINE TOOL/tde_compilation_test_3/fileSegmenter.py","file_name":"fileSegmenter.py","file_ext":"py","file_size_in_byte":3455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"510774372","text":"#-*- coding: utf-8 -*-\n#\n# IEDUtil.py\n# AutoDMG\n#\n# Created by Per Olofsson on 2013-10-31.\n# Copyright (c) 2013 Per Olofsson, University of Gothenburg. All rights reserved.\n#\n\nfrom Foundation import *\nfrom Carbon.File import *\n\nimport os.path\n\n\nclass IEDUtil(NSObject):\n \n VERSIONPLIST_PATH = u\"System/Library/CoreServices/SystemVersion.plist\"\n \n @classmethod\n def readSystemVersion_(cls, rootPath):\n plist = NSDictionary.dictionaryWithContentsOfFile_(os.path.join(rootPath, cls.VERSIONPLIST_PATH))\n name = plist[u\"ProductName\"]\n version = plist[u\"ProductUserVisibleVersion\"]\n build = plist[u\"ProductBuildVersion\"]\n return (name, version, build)\n \n @classmethod\n def getAppVersion(cls):\n bundle = NSBundle.mainBundle()\n version = bundle.objectForInfoDictionaryKey_(u\"CFBundleShortVersionString\")\n build = bundle.objectForInfoDictionaryKey_(u\"CFBundleVersion\")\n return (version, build)\n \n @classmethod\n def resolvePath(cls, path):\n \"\"\"Expand symlinks and resolve aliases.\"\"\"\n fsref, isFolder, wasAliased = FSResolveAliasFile(os.path.realpath(path), 1)\n return fsref.as_pathname().decode(u\"utf-8\")\n\n","sub_path":"AutoDMG/IEDUtil.py","file_name":"IEDUtil.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"201349929","text":"from rest_framework import viewsets\n\nfrom aids.models import Aid\nfrom aids.api.serializers import AidSerializer\nfrom aids.forms import AidSearchForm\n\n\nclass AidViewSet(viewsets.ReadOnlyModelViewSet):\n \"\"\"List all active aids that we know about.\"\"\"\n\n serializer_class = AidSerializer\n\n def get_queryset(self):\n \"\"\"Filter data according to search query.\"\"\"\n\n qs = Aid.objects \\\n .published() \\\n .open() \\\n .select_related('perimeter') \\\n .prefetch_related('financers', 'instructors') \\\n .order_by('perimeter__scale', 'submission_deadline')\n\n filter_form = AidSearchForm(data=self.request.GET)\n filtered_qs = filter_form.filter_queryset(qs)\n return filtered_qs\n","sub_path":"src/aids/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"481797664","text":"#!/usr/bin/env python\n# coding: utf-8\n'''\nFile : dEdX_runRoot.py\nAuthor : Lanjiann\nContact : jiann.lan@cosmic.utah.edu\nDate : 2014 May 26\n\nDescription : Run CERN ROOT to plot dE/dX as indicated by Nerling paper\n'''\n\nfrom __future__ import print_function\nimport errno\nimport os\nimport sys\nimport re\nimport refmt_splitter\n\n\nclass PlotsGenerator(object):\n '''xxx'''\n def __init__(self, done_dir, fitting_dir, longs_dir, plots_dir):\n '''xxx'''\n self.done_dir = done_dir\n self.longs_dir = longs_dir\n self.fitting_dir = fitting_dir\n self.plots_dir = plots_dir\n\n def single_shower_files(self, beginning=r'DAT11', tail=r'long'):\n '''xxx'''\n # Default only plot DAT11xxxx_x.long files for avoding this task take\n # too much time\n return sorted(f for f in os.listdir(self.longs_dir)\n if f.startswith(beginning) and f.endswith(tail))\n\n def mkdir_p(self):\n '''xxx'''\n try:\n os.makedirs(self.plots_dir)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(self.plots_dir):\n pass\n else:\n raise OSError\n\n def extract_fitting_xmax(self, fitting_file):\n '''xxx'''\n pattern = re.compile(r' 2 p1\\s*.*')\n with open(self.fitting_dir + os.sep + fitting_file) as f_obj:\n content = '\\n'.join(f_obj.readlines())\n return pattern.findall(content)[1].split()[2]\n\n def extract_corsika_xmax(self, long_file, num):\n '''xxx'''\n single_shower_num_pattern = re.compile(r'_(\\d)')\n original_fname = single_shower_num_pattern.sub(r'', long_file)\n shower_num = num\n# PARAMETERS = 7.0237E+06 -2.5966E+01 6.1806E+02 9.0391E+01 -6.2527E-02 2.9919E-05\n corsika_xmax_line_pattern = re.compile(r' *PARAMETERS')\n\n with open(self.done_dir + os.sep + original_fname) as f_obj:\n return [l.split()[3:5] for l in f_obj.readlines()\n if corsika_xmax_line_pattern.match(l)][shower_num]\n\n def generate_root_cmd(self, xmax_fitting, xmax_corsika, x0_corsika,\n long_file):\n '''xxx'''\n file_ext_pattern = re.compile(r'long')\n plot_file_name = file_ext_pattern.sub(r'png', long_file)\n longs_fullpath = self.longs_dir + os.sep + long_file\n plots_fullpath = self.plots_dir + os.sep + plot_file_name\n\n command = ('root -l -q -b ' + '\\'plot_dEdX.rcpp' + '(\"' +\n longs_fullpath + '\", \"' +\n plots_fullpath + '\", \"' + xmax_fitting + '\", \"' +\n xmax_corsika + '\", \"' + x0_corsika + '\")\\'')\n return command\n\nif __name__ == \"__main__\":\n ##################################################################\n # LOCAL_DIR = '/scratch/ibrix/chpc_gen/u0752670/corsika'\n LOCAL_DIR = '/Users/lanjiann/Research/___/comparison_diff_obLevel'\n ##################################################################\n dEdX_DIR = LOCAL_DIR + os.sep + 'dEdX'\n DONE_DIR = LOCAL_DIR + os.sep + 'done'\n FITTINGS_DIR = LOCAL_DIR + os.sep + 'Fitting'\n LONGS_DIR = dEdX_DIR + os.sep + 'single_showers'\n PLOTS_DIR = dEdX_DIR + os.sep + 'plots'\n\n plots_gen = PlotsGenerator(DONE_DIR, FITTINGS_DIR, LONGS_DIR, PLOTS_DIR)\n\n LONG_FNAME_PATTERN = re.compile(r'DAT\\d{6}\\.long')\n # single_showers_gen = refmt_splitter.SpliterReformatter(DONE_DIR, LONG_FNAME_PATTERN, '')\n single_showers_gen = refmt_splitter.SpliterReformatter(DONE_DIR, LONG_FNAME_PATTERN, '')\n all_longs = single_showers_gen.long_files()\n\n # with open(\"xmax_info.txt\", \"a\") as all_xmaxes:\n with open(\"xmax_info_orig_oblevel.txt\", \"a\") as all_xmaxes:\n for long_f in all_longs:\n for i in range(10):\n dot_pattern = re.compile(r'\\.')\n single_shower = dot_pattern.sub(r'_'+str(i)+r'.', long_f)\n Xmax_fitting = plots_gen.extract_fitting_xmax(single_shower + '.fit')\n X0_corsika, Xmax_corsika = plots_gen.extract_corsika_xmax(single_shower, i)\n root_cmd = plots_gen.generate_root_cmd(Xmax_fitting, Xmax_corsika,\n X0_corsika, single_shower)\n\n # print(\"{} {} {} {}\".format(re.sub(r'(DAT)(\\d{6})(\\.long)',\n # '\\g<2>', long_f), i, Xmax_fitting, Xmax_corsika),\n # file=all_xmaxes)\n\n if len(sys.argv) == 2 and sys.argv[1] == '-p':\n print(\"{}\".format(root_cmd))\n else:\n os.system(root_cmd)\n","sub_path":"ShowerLibrary/dEdX_runRoot.py","file_name":"dEdX_runRoot.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"224924070","text":"# encoding: utf-8\nfrom __future__ import unicode_literals, print_function\n\nimport os\nimport coverage\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\nfrom django.test.runner import DiscoverRunner\n\nfrom cmdb.models import Server, DataCenter, PkgConfig, PrePackage, Order\n\n\nclass Runner(DiscoverRunner):\n def init_db(self):\n admin = User.objects.create(username=\"admin\")\n admin.set_password(\"123456\")\n admin.save()\n DataCenter.objects.create(name=\"南汇\")\n Server.objects.create(minion_id=\"yy-t-kylin-autodeploy01\", ip=\"192.168.30.148\")\n PkgConfig.objects.create(artifact_id=\"app-website\", version=\"4.0.0-SNAPSHOT\", minion_ids=\"yy-t-kylin-autodeploy01\",\n start_script=\"startup.sh\", stop_script=\"stop.sh\", service_type=\"tomcat\",\n wait_seconds=30, env=\"PRODUCT\")\n Server.objects.create(id=10, minion_id=\"yy-t-act-provider\", hostname=\"yy-t-act-provider\")\n Server.objects.create(minion_id=\"yy-kf-app-mobile\", hostname=\"yy-kf-app-mobile\", memory_total=\"4GB\")\n Server.objects.create(minion_id=\"yy-t-app-mobile\", hostname=\"yy-t-app-mobile\", memory_total=\"8GB\")\n PkgConfig.objects.create(id=10, artifact_id=\"app-mobile\", version=\"4.0.0-SNAPSHOT\",\n minion_ids=\"yy-kf-app-mobile,yy-t-app-mobile\", env=\"PRODUCT\",\n project_dir=\"/data/tomcat-app\", service_type=\"tomcat\", operator=admin)\n PrePackage.objects.create(id=2, artifact_id=\"app-website\", group_id=\"com.niwodai.tech.app.deploy\",\n pkg_type=\"tomcat\", war_type=\"war\", version=\"4.0.0-SNAPSHOT\", liableperson=\"baowen\",\n noticeid=\"3803\", war_time=\"2017-09-28 18:02:54\")\n Order.objects.create(work_no=\"010000\", order_no=\"aa3ccbd8-ca1c-4c0c-be1a-1600f9ea1d42\")\n Order.objects.create(work_no=\"020000\", order_no=\"06058c8a-c46f-47df-9f58-84b6206447e4\")\n\n def setup_databases(self, **kwargs):\n old_config = super(Runner, self).setup_databases(**kwargs)\n self.init_db()\n return old_config\n\n def run_tests(self, test_labels, extra_tests=None, **kwargs):\n apps = filter(lambda name: not name.startswith(\"django.contrib\"), settings.INSTALLED_APPS)\n includes = []\n omits = []\n for app in apps:\n includes.append(os.path.join(app, \"*\"))\n omits.append(os.path.join(app, \"migrations/*\"))\n omits.append(os.path.join(app, \"tests.py\"))\n cov = coverage.coverage(include=includes, omit=omits)\n cov.start()\n result = super(Runner, self).run_tests(test_labels, extra_tests, **kwargs)\n\n cov.stop()\n cov.save()\n cover_percent = cov.report()\n print(cover_percent)\n return result\n","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"40693421","text":"#coding: utf-8\n__author__ = 'Reed'\n\nimport threading\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport queue\nimport time\n\n\nclass BookUrls(threading.Thread):\n def __init__(self, q_page, q_proxy):\n threading.Thread.__init__(self)\n self.q_page = q_page\n self.q_proxy = q_proxy\n self.sign = True\n\n def run(self):\n while 1:\n page_url = self.q_page.get()\n rqt = urllib.request.Request(page_url)\n rqt.add_header('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36')\n\n while 1:\n if self.sign:\n addr = self.q_proxy.get()\n proxy_handler = urllib.request.ProxyHandler({'http': addr})\n opener = urllib.request.build_opener(proxy_handler)\n try:\n page = opener.open(rqt).read().decode('utf-8')\n self.sign = False\n break\n except urllib.request.URLError as r:\n print(r.reason)\n self.sign = True\n q_proxy.task_done()\n continue\n\n soup = BeautifulSoup(page)\n for dd in soup.select('dd'):\n href = dd.select('a')[0].get('href')\n with open('bookurls.txt', 'a') as f:\n f.write(href + '\\n')\n q_page.task_done()\n time.sleep(7)\n\n\nif __name__ == '__main__':\n\n q_page = queue.Queue()\n q_proxy = queue.Queue()\n\n with open('proxy.txt') as f:\n ips = f.read().split('\\n')[:-1]\n for ip in ips:\n q_proxy.put(ip)\n print('Proxy deal Done!')\n time.sleep(5)\n\n pages_lst = ['http://www.douban.com/tag/%E5%B0%8F%E8%AF%B4/book?start=' + str(n) for n in range(0, 71985, 15)]\n for each_page in pages_lst:\n q_page.put(each_page)\n print('Pages deal Done!')\n time.sleep(5)\n\n for i in range(50):\n t = BookUrls(q_page, q_proxy)\n t.setDaemon(True)\n t.start()\n\n q_page.join()\n print('Download bookurls Done!')","sub_path":"DoubanSpider/bookUrls.py","file_name":"bookUrls.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"491488184","text":"class Solution:\n def minPathSum(self, grid: list) -> int:\n len_grid = len(grid)\n if not len_grid:\n return 0\n len_row = len(grid[0])\n for i in range(len_grid):\n for j in range(len_row):\n if i == j == 0:\n continue\n elif i == 0:\n grid[i][j] += grid[i][j - 1]\n elif j == 0:\n grid[i][j] += grid[i - 1][j]\n else:\n grid[i][j] += min(grid[i - 1][j], grid[i][j - 1])\n return grid[len_grid - 1][len_row - 1]\n","sub_path":"Week_06/G20200343040238/LeetCode_64_0238.py","file_name":"LeetCode_64_0238.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"496940668","text":"import caffe2onnx.src.c2oObject as Node\n##-------------------------------------------------LRN-------------------------------------------------------------##\n# Get hyperparameters\ndef getLRNAttri(layer):\n # Get hyperparameters\n # Size\n size = layer.lrn_param.local_size\n # Alpha\n alpha = layer.lrn_param.alpha\n # Beta\n beta = layer.lrn_param.beta\n\n # Hyperparameter dictionary\n dict = {\"alpha\":alpha,\n \"beta\":beta,\n \"bias\":1.0,\n \"size\": size}\n return dict\n\n# Calculate the output dimension\ndef getLRNOutShape(input_shape):\n # Calculate the output dimensionoutput_shape\n output_shape = input_shape # Same as input dimension\n return output_shape\n\n# Build node\ndef createLRN(layer,nodename, inname,outname,input_shape):\n dict = getLRNAttri(layer)\n output_shape = getLRNOutShape(input_shape)\n\n # Build node\n node = Node.c2oNode(layer, nodename, \"LRN\", inname, outname, input_shape, output_shape, dict)\n print(nodename, \" node construction completed\")\n return node","sub_path":"caffe2onnx/src/OPs/LRN.py","file_name":"LRN.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"566031932","text":"import datetime\nfrom pathlib import Path\nfrom unittest.mock import MagicMock\n\nimport pytest\nfrom rich.traceback import Trace\n\nimport briefcase\nfrom briefcase.console import Log\nfrom briefcase.exceptions import BriefcaseError\n\nTRACEBACK_HEADER = \"Traceback (most recent call last)\"\nEXTRA_HEADER = \"Extra information:\"\n\n\n@pytest.fixture\ndef now(monkeypatch):\n \"\"\"monkeypatch the datetime.now inside of briefcase.console.\"\"\"\n now = datetime.datetime(2022, 6, 25, 16, 12, 29)\n datetime_mock = MagicMock(wraps=datetime.datetime)\n datetime_mock.now.return_value = now\n monkeypatch.setattr(briefcase.console, \"datetime\", datetime_mock)\n return now\n\n\ndef test_capture_stacktrace():\n \"\"\"capture_stacktrace sets Log.stacktrace.\"\"\"\n logger = Log()\n assert logger.skip_log is False\n\n try:\n 1 / 0\n except ZeroDivisionError:\n logger.capture_stacktrace()\n\n assert len(logger.stacktraces) == 1\n assert logger.stacktraces[0][0] == \"Main thread\"\n assert isinstance(logger.stacktraces[0][1], Trace)\n assert logger.skip_log is False\n\n\n@pytest.mark.parametrize(\"skip_logfile\", [True, False])\ndef test_capture_stacktrace_for_briefcaseerror(skip_logfile):\n \"\"\"skip_log is updated for BriefcaseError exceptions.\"\"\"\n logger = Log()\n assert logger.skip_log is False\n\n try:\n raise BriefcaseError(error_code=542, skip_logfile=skip_logfile)\n except BriefcaseError:\n logger.capture_stacktrace()\n\n assert len(logger.stacktraces) == 1\n assert logger.stacktraces[0][0] == \"Main thread\"\n assert isinstance(logger.stacktraces[0][1], Trace)\n assert logger.skip_log is skip_logfile\n\n\ndef test_save_log_to_file_do_not_log():\n \"\"\"Nothing is done to save log if no command or --log wasn't passed.\"\"\"\n logger = Log()\n logger.save_log_to_file(command=None)\n\n command = MagicMock()\n logger.save_log = False\n logger.save_log_to_file(command=command)\n command.input.wait_bar.assert_not_called()\n\n # There were no stack traces captured\n assert len(logger.stacktraces) == 0\n\n\ndef test_save_log_to_file_no_exception(tmp_path, now):\n \"\"\"Log file contains everything printed to log; env vars are sanitized; no\n stacktrace if one is not captured.\"\"\"\n command = MagicMock()\n command.base_path = Path(tmp_path)\n command.command = \"dev\"\n command.tools.os.environ = {\n \"GITHUB_KEY\": \"super-secret-key\",\n \"ANDROID_SDK_ROOT\": \"/androidsdk\",\n }\n\n logger = Log(verbosity=2)\n logger.save_log = True\n logger.debug(\"this is debug output\")\n logger.info(\"this is info output\")\n logger.warning(\"this is warning output\")\n logger.error(\"this is error output\")\n logger.print(\"this is print output\")\n logger.print.to_log(\"this is log output\")\n logger.print.to_console(\"this is console output\")\n\n logger.info(\"this is [bold]info output with markup[/bold]\")\n logger.info(\n \"this is [bold]info output with markup and a prefix[/bold]\", prefix=\"wibble\"\n )\n logger.info(\"this is [bold]info output with escaped markup[/bold]\", markup=True)\n logger.info(\n \"this is [bold]info output with escaped markup and a prefix[/bold]\",\n prefix=\"wibble\",\n markup=True,\n )\n logger.save_log_to_file(command=command)\n\n log_filepath = tmp_path / \"logs\" / \"briefcase.2022_06_25-16_12_29.dev.log\"\n\n assert log_filepath.exists()\n with open(log_filepath, encoding=\"utf-8\") as log:\n log_contents = log.read()\n\n assert log_contents.startswith(\"Date/Time: 2022-06-25 16:12:29\")\n assert \">>> this is debug output\" in log_contents\n assert \"this is info output\" in log_contents\n assert \"this is [bold]info output with markup[/bold]\" in log_contents\n assert \"this is info output with escaped markup\" in log_contents\n assert \"this is warning output\" in log_contents\n assert \"this is error output\" in log_contents\n assert \"this is print output\" in log_contents\n assert \"this is log output\" in log_contents\n assert \"this is console output\" not in log_contents\n # Environment variables are in the output\n assert \"ANDROID_SDK_ROOT=/androidsdk\" in log_contents\n assert \"GITHUB_KEY=********************\" in log_contents\n assert \"GITHUB_KEY=super-secret-key\" not in log_contents\n # Environment variables are sorted\n assert log_contents.index(\"ANDROID_SDK_ROOT\") < log_contents.index(\"GITHUB_KEY\")\n\n assert TRACEBACK_HEADER not in log_contents\n assert EXTRA_HEADER not in log_contents\n\n\ndef test_save_log_to_file_with_exception(tmp_path, now):\n \"\"\"Log file contains exception stacktrace when one is captured.\"\"\"\n command = MagicMock()\n command.base_path = Path(tmp_path)\n command.command = \"dev\"\n command.tools.os.environ = {}\n\n logger = Log()\n logger.save_log = True\n try:\n 1 / 0\n except ZeroDivisionError:\n logger.capture_stacktrace()\n logger.save_log_to_file(command=command)\n\n log_filepath = tmp_path / \"logs\" / \"briefcase.2022_06_25-16_12_29.dev.log\"\n\n assert log_filepath.exists()\n with open(log_filepath, encoding=\"utf-8\") as log:\n log_contents = log.read()\n\n assert len(logger.stacktraces) == 1\n assert log_contents.startswith(\"Date/Time: 2022-06-25 16:12:29\")\n assert TRACEBACK_HEADER in log_contents\n assert log_contents.splitlines()[-1].startswith(\"ZeroDivisionError\")\n\n\ndef test_save_log_to_file_with_multiple_exceptions(tmp_path, now):\n \"\"\"Log file contains exception stacktrace when more than one is captured.\"\"\"\n command = MagicMock()\n command.base_path = Path(tmp_path)\n command.command = \"dev\"\n command.tools.os.environ = {}\n\n logger = Log()\n logger.save_log = True\n for i in range(1, 5):\n try:\n 1 / 0\n except ZeroDivisionError:\n logger.capture_stacktrace(f\"Thread {i}\")\n\n logger.save_log_to_file(command=command)\n\n log_filepath = tmp_path / \"logs\" / \"briefcase.2022_06_25-16_12_29.dev.log\"\n\n assert log_filepath.exists()\n with open(log_filepath, encoding=\"utf-8\") as log:\n log_contents = log.read()\n\n assert len(logger.stacktraces) == 4\n assert log_contents.startswith(\"Date/Time: 2022-06-25 16:12:29\")\n assert TRACEBACK_HEADER in log_contents\n for i in range(1, 5):\n assert f\"\\nThread {i} traceback:\\n\" in log_contents\n assert log_contents.splitlines()[-1].startswith(\"ZeroDivisionError\")\n\n\ndef test_save_log_to_file_extra(tmp_path, now):\n \"\"\"Log file extras are called when the log is written.\"\"\"\n command = MagicMock()\n command.base_path = Path(tmp_path)\n command.command = \"dev\"\n\n logger = Log()\n logger.save_log = True\n\n def extra1():\n logger.debug(\"Log extra 1\")\n\n def extra2():\n raise ValueError(\"Log extra 2\")\n\n def extra3():\n logger.debug(\"Log extra 3\")\n\n for extra in [extra1, extra2, extra3]:\n logger.add_log_file_extra(extra)\n logger.save_log_to_file(command=command)\n log_filepath = tmp_path / \"logs\" / \"briefcase.2022_06_25-16_12_29.dev.log\"\n with open(log_filepath, encoding=\"utf-8\") as log:\n log_contents = log.read()\n\n assert EXTRA_HEADER in log_contents\n assert \"Log extra 1\" in log_contents\n assert TRACEBACK_HEADER in log_contents\n assert \"ValueError: Log extra 2\" in log_contents\n assert \"Log extra 3\" in log_contents\n\n\ndef test_save_log_to_file_extra_interrupted(tmp_path, now):\n \"\"\"Log file extras can be interrupted by Ctrl-C.\"\"\"\n command = MagicMock()\n command.base_path = Path(tmp_path)\n command.command = \"dev\"\n\n logger = Log()\n logger.save_log = True\n\n def extra1():\n raise KeyboardInterrupt()\n\n extra2 = MagicMock()\n for extra in [extra1, extra2]:\n logger.add_log_file_extra(extra)\n with pytest.raises(KeyboardInterrupt):\n logger.save_log_to_file(command=command)\n extra2.assert_not_called()\n log_filepath = tmp_path / \"logs\" / \"briefcase.2022_06_25-16_12_29.dev.log\"\n assert log_filepath.stat().st_size == 0\n\n\ndef test_save_log_to_file_fail_to_write_file(capsys):\n \"\"\"User is informed when the log file cannot be written.\"\"\"\n command = MagicMock()\n command.base_path = Path(\"/a-path-that-will-cause-an-OSError...\")\n command.command = \"dev\"\n command.tools.os.environ = {}\n\n logger = Log()\n logger.save_log = True\n\n logger.print(\"a line of output\")\n logger.save_log_to_file(command=command)\n\n last_line_of_output = capsys.readouterr().out.strip().splitlines()[-1]\n assert last_line_of_output.startswith(\"Failed to save log to \")\n\n\ndef test_log_with_context(tmp_path, capsys):\n \"\"\"Log file can be given a persistent context.\"\"\"\n command = MagicMock()\n command.base_path = Path(tmp_path)\n\n logger = Log(verbosity=2)\n logger.save_log = False\n\n logger.info(\"this is info output\")\n with logger.context(\"Deep\"):\n logger.info(\"this is deep context\")\n logger.info(\"prefixed deep context\", prefix=\"prefix\")\n logger.info()\n logger.debug(\"this is deep debug\")\n with logger.context(\"Really Deep\"):\n logger.info(\"this is really deep context\")\n logger.info(\"prefixed really deep context\", prefix=\"prefix2\")\n logger.info()\n logger.debug(\"this is really deep debug\")\n logger.info(\"Pop back to deep\")\n logger.info(\"Pop back to normal\")\n\n assert capsys.readouterr().out == \"\\n\".join(\n [\n \"this is info output\",\n \"\",\n \"Entering Deep context...\",\n \"Deep| --------------------------------------------------------------------\",\n \"Deep| this is deep context\",\n \"Deep| \",\n \"Deep| [prefix] prefixed deep context\",\n \"Deep| \",\n \"Deep| >>> this is deep debug\",\n \"Deep| \",\n \"Deep| Entering Really Deep context...\",\n \"Really Deep| -------------------------------------------------------------\",\n \"Really Deep| this is really deep context\",\n \"Really Deep| \",\n \"Really Deep| [prefix2] prefixed really deep context\",\n \"Really Deep| \",\n \"Really Deep| >>> this is really deep debug\",\n \"Really Deep| -------------------------------------------------------------\",\n \"Deep| Leaving Really Deep context.\",\n \"Deep| \",\n \"Deep| Pop back to deep\",\n \"Deep| --------------------------------------------------------------------\",\n \"Leaving Deep context.\",\n \"\",\n \"Pop back to normal\",\n \"\",\n ]\n )\n\n\ndef test_log_error_with_context_(tmp_path, capsys):\n \"\"\"If an exception is raised in a logging context, the context is cleared.\"\"\"\n command = MagicMock()\n command.base_path = Path(tmp_path)\n\n logger = Log(verbosity=2)\n logger.save_log = False\n\n logger.info(\"this is info output\")\n try:\n with logger.context(\"Deep\"):\n logger.info(\"this is deep context\")\n raise ValueError()\n except ValueError:\n logger.info(\"this is cleanup\")\n\n assert capsys.readouterr().out == \"\\n\".join(\n [\n \"this is info output\",\n \"\",\n \"Entering Deep context...\",\n \"Deep| --------------------------------------------------------------------\",\n \"Deep| this is deep context\",\n \"Deep| --------------------------------------------------------------------\",\n \"Leaving Deep context.\",\n \"\",\n \"this is cleanup\",\n \"\",\n ]\n )\n","sub_path":"tests/console/test_Log.py","file_name":"test_Log.py","file_ext":"py","file_size_in_byte":11555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618148935","text":"from PyQt5 import QtGui\nimport numpy as np\n\n\ndef convertCV2ToQimage(cv_vid, qt_vid):\n \"\"\" `convertCV2ToQimage`\n \n Convierte una imagen en formato de OpenCV (numpy array) a formato Qt\n\n Parametros\n ----------\n - cv_vid : Imagen en formato numpy\n - qt_vid : Imagen de salida en formato Qt\n \"\"\"\n gray_color_table = [QtGui.qRgb(i, i, i) for i in range(256)]\n if cv_vid is None:\n return\n if cv_vid.dtype != np.uint8:\n return\n if len(cv_vid.shape) == 2:\n image = QtGui.QImage(cv_vid, cv_vid.shape[1], cv_vid.shape[0], cv_vid.strides[0], QtGui.QImage.Format_Indexed8)\n image.setColorTable(gray_color_table)\n if len(cv_vid.shape) == 3:\n if cv_vid.shape[2] == 3:\n image = QtGui.QImage(cv_vid, cv_vid.shape[1], cv_vid.shape[0], cv_vid.strides[0],\n QtGui.QImage.Format_RGB888)\n elif cv_vid.shape[2] == 4:\n image = QtGui.QImage(cv_vid, cv_vid.shape[1], cv_vid.shape[0], cv_vid.strides[0],\n QtGui.QImage.Format_ARGB32)\n pixmap = QtGui.QPixmap()\n pixmap.convertFromImage(image.rgbSwapped())\n qt_vid.setPixmap(pixmap)\n","sub_path":"Tarea-7/cvqtmanage.py","file_name":"cvqtmanage.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"196626336","text":"import numpy as np\n\nfrom Config import Config\n\nclass ReplayBuffer(object):\n\n def __init__(self, env_spec, role, id, max_buffer_size=Config.MAX_BUFFER_SIZE):\n self._role = role\n self._id = id\n self._env_spec = env_spec\n self._max_buffer_size = max_buffer_size\n\n self._n_opponent = env_spec.action_space.agent_num - 1\n self._observation_dim = env_spec.observation_space[id].flat_dim\n self._action_dim = env_spec.action_space[id].flat_dim\n # self._opponent_action_dim = env_spec.action_space.opponent_flat_dim(id)\n # self._opponent_observation_dim = env_spec.observation_space.opponent_flat_dim(id)\n self._opponent_action_dim = list()\n for i in range(self._n_opponent + 1):\n if i != self._id:\n self._opponent_action_dim.append(env_spec.action_space[i].flat_dim)\n self._opponent_observation_dim = list()\n for i in range(self._n_opponent + 1):\n if i != self._id:\n self._opponent_observation_dim.append(env_spec.observation_space[i].flat_dim)\n\n self._observations = np.zeros((self._max_buffer_size, self._observation_dim))\n self._next_observations = np.zeros((self._max_buffer_size, self._observation_dim))\n self._actions = np.zeros((self._max_buffer_size, self._action_dim))\n self._expert_actions = np.zeros((self._max_buffer_size, self._action_dim))\n self._opponent_actions = [np.zeros((self._max_buffer_size, act_dim)) for act_dim in self._opponent_action_dim]\n self._opponent_observations = [np.zeros((self._max_buffer_size, obs_dim)) for obs_dim in self._opponent_observation_dim]\n self._opponent_next_observations = [np.zeros((self._max_buffer_size, obs_dim)) for obs_dim in self._opponent_observation_dim]\n\n self._rewards = np.zeros((self._max_buffer_size, ))\n self._terminals = np.zeros((self._max_buffer_size, ))\n\n self._top = 0\n self._size = 0\n\n @property\n def size(self):\n return self._size\n\n def add_sample(self, observation, next_observation,\n action, expert_action, opponent_action,\n opponent_observation,\n opponent_next_observation,\n reward, terminal):\n self._observations[self._top] = observation\n self._next_observations[self._top] = next_observation\n self._actions[self._top] = action\n self._expert_actions[self._top] = expert_action\n for i, act in enumerate(opponent_action):\n self._opponent_actions[i][self._top] = act\n for i, obs in enumerate(opponent_observation):\n self._opponent_observations[i][self._top] = obs\n for i, next_obs in enumerate(opponent_next_observation):\n self._opponent_next_observations[i][self._top] = next_obs\n self._rewards[self._top] = reward\n self._terminals[self._top] = terminal\n\n self._advance()\n\n def _advance(self):\n self._top = (self._top + 1) % self._max_buffer_size\n if self._size < self._max_buffer_size:\n self._size += 1\n\n def random_indices(self, batch_size):\n return np.random.randint(0, self._size, batch_size)\n\n def get_batch_by_indices(self, indices):\n batch = dict(\n observations = self._observations[indices],\n next_observations = self._next_observations[indices],\n actions = self._actions[indices],\n expert_actions = self._expert_actions[indices],\n opponent_actions = [act[indices] for act in self._opponent_actions],\n opponent_observations = [obs[indices] for obs in self._opponent_observations],\n opponent_next_observations = [obs[indices] for obs in self._opponent_next_observations],\n rewards = self._rewards[indices],\n terminals = self._terminals[indices]\n )\n return batch\n\n def random_batch(self, batch_size):\n return self.get_batch_by_indices(self.random_indices(batch_size))\n\n def recent_batch(self, batch_size, opponent_only=True):\n indices = list(range(self._top - batch_size, self._top))\n if opponent_only:\n batch = dict(\n opponent_actions = [act[indices] for act in self._opponent_actions],\n opponent_observations = [obs[indices] for obs in self._opponent_observations],\n )\n else:\n batch = self.get_batch_by_indices(indices)\n return batch\n","sub_path":"replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":4765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571475164","text":"#!/usr/bin/env python3\nimport sys\nsys.setrecursionlimit(10**6)\n\nk = int(input())\n\nquo = k//50\nrem = k % 50\n\nans = [49+quo]*50\n\nfor i in range(rem):\n ans[i] += 50 - (rem-1)\n\nfor i in range(50-rem):\n ans[-i-1] -= rem\n\nprint(50)\nprint(*ans)\n","sub_path":"abc068/d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"243679945","text":"print('Welcome to your shopping/todo list!')\nprint('Type HELP at any time for a list of available commands')\nprint()\n\nitems = []\n\n\ndef add_to_list(item):\n items.append(v)\n\n\ndef show_help():\n print('---- Available Commands -----')\n print('HELP: Shows this help information')\n print('SHOW: Shows your current list')\n print('DONE: Shows your current list then exits')\n\n\ndef show_list():\n print('----- My List -----')\n print('- ' + '\\n- '.join(items))\n\n\nwhile True:\n v = input('Enter something for your list: ')\n\n if v == 'SHOW':\n show_list()\n elif v == 'DONE':\n show_list()\n break\n elif v == 'HELP':\n show_help()\n else:\n add_to_list(v)\n","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"337224103","text":"from django.db import models\n\n\nclass Trip(models.Model):\n name = models.CharField(max_length=140, verbose_name='Name')\n writer = models.ForeignKey('accounts.User', on_delete=models.CASCADE)\n logs = models.ManyToManyField('Log')\n\n\nclass Log(models.Model):\n description = models.TextField()\n pictures = models.ManyToManyField('Pictures')\n location = models.ForeignKey('Location', on_delete=models.PROTECT)\n visited_at = models.DateTimeField()\n\n\nclass Location(models.Model):\n name = models.CharField(max_length=80)\n lat = models.FloatField()\n lng = models.FloatField()\n\n\nclass Pictures(models.Model):\n picture = models.ImageField()\n","sub_path":"travellog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"307831979","text":"# from __future__ import division\nimport stl_path\nfrom trex_stl_lib.api import *\n\nfrom pprint import pprint\nimport argparse\nimport sys\nimport ndr_bench as ndr\n\n\ndef build_streams_for_bench(size, vm, src_start_ip, src_stop_ip, dest_start_ip, dest_stop_ip, direction):\n if vm:\n stl_bench = ndr.STLBench()\n if src_start_ip:\n stl_bench.ip_range['src']['start'] = src_start_ip\n if src_stop_ip:\n stl_bench.ip_range['src']['end'] = src_stop_ip\n if dest_start_ip:\n stl_bench.ip_range['dst']['start'] = dest_start_ip\n if dest_stop_ip:\n stl_bench.ip_range['dst']['end'] = dest_stop_ip\n\n streams = stl_bench.get_streams(size, vm, direction)\n return streams\n\n\n# find NDR benchmark test\n# it maps the ports to sides\n# then it load a predefind profile 'IMIX'\n# and attach it to both sides and inject\n# then searches for NDR according to specified values\ndef ndr_benchmark_test(server, core_mask, pdr, iteration_duration, ndr_results, setup_name, first_run_duration, verbose,\n pdr_error, q_ful_resolution, latency, vm, pkt_size, fe_src_start_ip,\n fe_src_stop_ip, fe_dst_start_ip, fe_dst_stop_ip, drop_rate_interval, output, ports_list):\n passed = True\n if ports_list:\n if len(ports_list) % 2 != 0:\n print(\"illegal ports list\")\n return\n c = STLClient(server=server)\n # connect to server\n c.connect()\n\n # take all the ports\n c.reset()\n\n # map ports - identify the routes\n table = stl_map_ports(c)\n # pprint(table)\n if ports_list:\n dir_0 = [ports_list[i] for i in range(0, len(ports_list), 2)]\n ports = ports_list\n else:\n dir_0 = [table['bi'][0][0]]\n ports = list(table['bi'][0])\n\n # profile_file = os.path.join(stl_path.STL_PROFILES_PATH, 'imix.py') # load IMIX profile\n # profile = STLProfile.load_py(profile_file)\n # streams = profile.get_streams()\n # print(\"Mapped ports to sides {0} <--> {1}\".format(dir_0, dir_1))\n\n streams = build_streams_for_bench(size=pkt_size, vm=vm, src_start_ip=fe_src_start_ip, src_stop_ip=fe_src_stop_ip,\n dest_start_ip=fe_dst_start_ip, dest_stop_ip=fe_dst_stop_ip, direction=0)\n\n if latency:\n burst_size = 1000\n pps = 1000\n pkt = STLPktBuilder(pkt=Ether() / IP(src=\"16.0.0.1\", dst=\"48.0.0.1\") / UDP(dport=12,\n sport=1025) / 'at_least_16_bytes_payload_needed')\n total_pkts = burst_size\n s1 = STLStream(name='rx',\n packet=pkt,\n flow_stats=STLFlowLatencyStats(pg_id=5),\n mode=STLTXSingleBurst(total_pkts=total_pkts,\n pps=pps))\n streams.append(s1)\n # add both streams to ports\n c.add_streams(streams, ports=dir_0)\n # self.stl_client.add_streams(streams, ports=dir_1)\n\n\n config = ndr.NdrBenchConfig(ports=ports, pkt_size=pkt_size, vm=vm, iteration_duration=iteration_duration,\n q_ful_resolution=q_ful_resolution,\n first_run_duration=first_run_duration, pdr=pdr, pdr_error=pdr_error,\n ndr_results=ndr_results,\n latency=latency, core_mask=core_mask,\n verbose=verbose, drop_rate_interval=drop_rate_interval)\n b = ndr.NdrBench(stl_client=c, config=config)\n\n try:\n b.find_ndr()\n if b.config.verbose:\n b.results.print_final(latency)\n # pprint(run_results)\n except STLError as e:\n passed = False\n print(e)\n sys.exit(1)\n\n finally:\n c.disconnect()\n\n if passed:\n print(\"\\nTest has passed :-)\\n\")\n else:\n print(\"\\nTest has failed :-(\\n\")\n\n result = b.results.to_json()\n if output == 'json':\n return result\n\n\nparser = argparse.ArgumentParser(description=\"TRex NDR benchmark tool\")\nparser.add_argument('-s', '--server',\n dest='server',\n help='Remote trex address',\n default='127.0.0.1',\n type=str)\nparser.add_argument('-c', '--core-mask',\n dest='core_mask',\n help='Determines the allocation of cores per port, see Stateless help for more info',\n default=None,\n type=int)\nparser.add_argument('-p', '--pdr',\n dest='pdr',\n help='Allowed percentage of drops. (out of total traffic) [0(NDR)-100]',\n default=0.1,\n type=float)\nparser.add_argument('-t', '--iter-time',\n dest='iteration_duration',\n help='Duration of each run iteration during test. [seconds]',\n default=20.00,\n type=float)\nparser.add_argument('-n', '--ndr-results',\n dest='ndr_results',\n help='calculates the benchmark at each point scaled linearly under NDR [1-10]. '\n 'The results for ndr_results=2 are NDR and NDR/2.',\n default=1,\n type=int)\nparser.add_argument('-na', '--setup-name',\n dest='setup_name',\n help='Name of the setup the benchmark tests',\n default='trex',\n type=str)\nparser.add_argument('-ft', '--first_run_duration_time',\n dest='first_run_duration',\n help='The first run tests for the capability of the device.\\n'\n '100%% operation will be tested after half of the duration.\\n'\n 'Shorter times may lead to inaccurate measurement [seconds]',\n default=20.00,\n type=float)\nparser.add_argument('-v', '--verbose',\n dest='verbose',\n help='When verbose is set, prints test results and iteration to stdout',\n default=False,\n action='store_true')\nparser.add_argument('-x', '--max-iterations',\n dest='max_iterations',\n help='The bench stops when reaching result or max_iterations, the early of the two [int]',\n default=10,\n type=int)\nparser.add_argument('-e', '--pdr-error',\n dest='pdr_error',\n help='The error around the actual result, in percent.\\n'\n '0%% error is not recommended due to precision issues. [percents 0-100]',\n default=1.00,\n type=float)\nparser.add_argument('-q', '--q-full',\n dest='q_ful_resolution',\n help='percent of traffic allowed to be queued when transmitting above dut capability.\\n'\n '0%% q-full resolution is not recommended due to precision issues. [percents 0-100]',\n default=2.00,\n type=float)\nparser.add_argument('-l', '--latency',\n dest='latency',\n help='Specify this option to disable latency calculations.',\n default=True,\n action='store_false')\nparser.add_argument('-fe',\n dest='vm',\n help='choose Field Engine Module: var1,var2,random,tuple,size,cached. default is none',\n default='none',\n type=str)\nparser.add_argument('-size',\n dest='size',\n type=str,\n help='choose packet size/imix. default is 64 bytes',\n default=64)\nparser.add_argument('--fe-src-start-ip', dest='fe_src_start_ip',\n help='when using FE you can define the start and stop ip addresses.'\n 'this is valid only when -fe flag is defined',\n default=None)\nparser.add_argument('--fe-src-stop-ip', dest='fe_src_stop_ip',\n help='when using FE you can define the start and stop ip addresses.'\n 'this is valid only when -fe flag is defined',\n default=None)\nparser.add_argument('--fe-dst-start-ip', dest='fe_dst_start_ip',\n help='when using FE you can define the start and stop ip addresses.'\n 'this is valid only when -fe flag is defined',\n default=None)\nparser.add_argument('--fe-dst-stop-ip', dest='fe_dst_stop_ip',\n help='when using FE you can define the start and stop ip addresses.'\n 'this is valid only when -fe flag is defined',\n default=None)\nparser.add_argument('-d', '--drop-rate-interval', dest='drop_rate_interval',\n help='The tool will search for NDR, when drop occur, the tool searches for ndr between an assumed'\n 'no drop rate within an interval defined by this parameter.[Percents]'\n 'Default value is 10 percent, the tool will search for ndr in an interval of '\n '[assumed-rate - 10 percent, assumed rate + 10 percent]',\n default=10)\nparser.add_argument('-o', '--output', dest='output',\n help='Desired output format. specify json for JSON output.'\n 'Specify yaml for YAML output.'\n 'if this flag is unspecified, output will appear to console if the option -v is present',\n default=None,\n type=str)\nparser.add_argument('--ports', dest='ports_list', help='specify an even list of ports for running traffic on',\n type=int, nargs='*', default=None)\n\nargs = parser.parse_args()\n\n# run the tests\nndr_benchmark_test(args.server, args.core_mask, args.pdr, args.iteration_duration, args.ndr_results, args.setup_name,\n args.first_run_duration, args.verbose,\n args.pdr_error, args.q_ful_resolution, args.latency, args.vm, args.size, args.fe_src_start_ip,\n args.fe_src_stop_ip, args.fe_dst_start_ip, args.fe_dst_stop_ip, args.drop_rate_interval, args.output,\n args.ports_list)\n","sub_path":"scripts/automation/trex_control_plane/stl/examples/stl_ndr_bench_tool.py","file_name":"stl_ndr_bench_tool.py","file_ext":"py","file_size_in_byte":10367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"593167468","text":"import cherrypy\n\nimport email\n\nimport mailbox\n\nimport time\n\nfrom viewattachment import ViewAttachment\n\nimport html_strings\n\nimport utils\n\nclass ViewReadOne(object):\n\n attachment = ViewAttachment()\n\n @cherrypy.expose\n def index(self,username,message_id,sent=\"False\"):\n\n sent = sent.strip('\"')\n\n username = username.strip('\"')\n\n message_id = message_id.strip('\"')\n\n sent_bool = True\n\n if sent == \"False\":\n sent_bool = False\n\n #the default message factory is the rfc822.Message for historical reasons (see https://docs.python.org/2/library/mailbox.html#maildir)\n if sent_bool == False:\n try:\n emails = mailbox.Maildir('/efsemail/mail/vhosts/ecommunicate.ch/'+username+'/',factory=mailbox.MaildirMessage,create=False)\n except mailbox.NoSuchMailboxError:\n raise Exception\n else:\n emails = mailbox.Maildir('/efsemail/mail/vhosts/ecommunicate.ch-sent/'+username+'/',factory=mailbox.MaildirMessage)\n\n em = emails.get_message(message_id)\n\n email_string = \"\"\n\n email_string += \"\"\n\n if sent_bool:\n if 'To' in em:\n if email.utils.parseaddr(em['To'])[0]:\n email_string += \"\"\n else: \n email_string += \"\"\n #email_string = email_string + email.utils.parseaddr(em[1]['From'])[1]+\"
\" \n else:\n if 'From' in em:\n if email.utils.parseaddr(em['From'])[0]:\n email_string += \"\"\n else:\n email_string += \"\"\n #email_string = email_string + email.utils.parseaddr(em[1]['From'])[1]+\"
\"\n if 'Subject' in em: \n email_string += \"\"\n if 'Date' in em:\n email_string += \"\"\n\n attachment_string = \"\"\n\n body_string = \"\"\n\n at_least_one_attachment = False\n\n if em.is_multipart():\n\n for payload in em.get_payload():\n if not payload.is_multipart():\n\n\n if 'X-Attachment-Id' in payload and \"Content-Description\" in payload:\n\n\n if not at_least_one_attachment:\n at_least_one_attachment = True\n\n attachment_string += '\"\n else:\n for subpayload in payload.get_payload():\n if not subpayload.is_multipart():\n if 'Content-Type' in subpayload and ('text/plain' in subpayload['Content-Type'] or 'message/delivery-status' in subpayload['Content-Type'] or 'message/rfc822' in subpayload['Content-Type']):\n body_string += '\"\n else:\n for subsubpayload in subpayload.get_payload():\n if not subsubpayload.is_multipart():\n if 'Content-Type' in subsubpayload and ('text/plain' in subsubpayload['Content-Type'] or 'message/delivery-status' in subsubpayload['Content-Type'] or 'message/rfc822' in subsubpayload['Content-Type']):\n body_string += '\"\n else:\n pass\n else:\n\n body_string += \"\"\n\n if at_least_one_attachment:\n attachment_string += ''\n \n\n email_string += attachment_string\n\n email_string += body_string\n\n email_string += \"
To: \"+email.utils.parseaddr(em['To'])[0]+\"
To: \"+email.utils.parseaddr(em['To'])[1]+\"
From: \"+email.utils.parseaddr(em['From'])[0]+\"
From: \"+email.utils.parseaddr(em['From'])[1]+\"
Subject: \"+em['Subject']+\"
Date: \"+time.strftime(\"%d %b %H:%M\",email.utils.parsedate(em['Date']))+\"
'\n\n attachment_string += ''+payload[\"Content-Description\"]+''\n\n else:\n\n attachment_string += ' '+payload[\"Content-Description\"]+''\n\n else:\n if 'Content-Type' in payload and ('text/plain' in payload['Content-Type'] or 'message/delivery-status' in payload['Content-Type'] or 'message/rfc822' in payload['Content-Type']):\n body_string += '
'+payload.get_payload()+\"
'+subpayload.get_payload()+\"
'+subsubpayload.get_payload()+\"
\"+em.get_payload()+\"
\"\n\n is_mobile = False\n\n if \"User-Agent\" in cherrypy.request.headers and (\"Android\" in cherrypy.request.headers['User-Agent'] or \"iPhone\" in cherrypy.request.headers['User-Agent'] or \"iPad\" in cherrypy.request.headers['User-Agent']):\n is_mobile = True\n\n if is_mobile:\n \n html_string = \"\"\"\n\n\n\"\"\"+html_strings.google_adsense_conversion_tracking_global_site_tag+\"\"\"\n\n\n\n\nEcommunicate\n\n\n\n\n\n\n\n\n\n\n
\n\n
\n\n\n \n \n \n\n\n
\n\n

Ecommunicate

\n\n
\n\n
\n\n
\n\n\"\"\"+email_string+\"\"\"\n\n
\n\n
\n\n\n\n\n\n\n\n\n\n\"\"\"\n\n else:\n \n html_string = \"\"\"\n\n\n\"\"\"+html_strings.google_adsense_conversion_tracking_global_site_tag+\"\"\"\n\n\nEcommunicate\n\n\n\"\"\"+(html_strings.authenticated_header if utils.is_session_authenticated() else html_strings.not_authenticated_header)+\"\"\"\n\n
\n\n

\n
\n\"\"\"+email_string+\"\"\"\n
\n \n \n
\n
\n \n
\n\n\n\n \"\"\"\n\n\n return html_string\n","sub_path":"viewreadone.py","file_name":"viewreadone.py","file_ext":"py","file_size_in_byte":8138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"577034019","text":"import math\ndef isprime(n):\n\tif n==1 or n<=0:\n\t\treturn(False)\n\tj=int(math.sqrt(n))\n\tfor i in range(2,j+1):\n\t\tif n%i==0:\n\t\t\treturn(False)\n\treturn(True)\ndef intreverse(n):\n\tn=str(n)\n\tans=n[-1]\n\tfor i in range(len(n)-2,-1,-1):\n\t\tans=ans+n[i]\n\tn=int(ans)\n\treturn(n)\ndef matched(s):\n\tcount=0\n\tfor i in range(0,len(s)):\n\t\tif s[i]=='(':\n\t\t\tcount+=1\n\t\telif s[i]==')':\n\t\t\tcount-=1\n\t\tif count<0:\n\t\t\treturn(False)\n\tif count==0:\n\t\treturn(True)\n\telse:\n\t\treturn(False)\n\ndef sumprimes(l):\n\tans=0;\n\tfor i in l:\n\t\tif isprime(i):\n\t\t\tans+=i\n\treturn (ans)\n\n\nimport ast\n\ndef tolist(inp):\n inp = \"[\"+inp+\"]\"\n inp = ast.literal_eval(inp)\n return (inp[0],inp[1])\n\ndef parse(inp):\n inp = ast.literal_eval(inp)\n return (inp)\n\nfncall = input()\nlparen = fncall.find(\"(\")\nrparen = fncall.rfind(\")\")\nfname = fncall[:lparen]\nfarg = fncall[lparen+1:rparen]\n\nif fname == \"intreverse\":\n arg = parse(farg)\n print(intreverse(arg))\nelif fname == \"matched\":\n arg = parse(farg)\n print(matched(arg))\nelif fname == \"sumprimes\":\n arg = parse(farg)\n print(sumprimes(arg))\nelse:\n print(\"Function\", fname, \"unknown\")\n","sub_path":"week1.py","file_name":"week1.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"424093674","text":"from collections import defaultdict\nimport logging\nimport os\nimport tempfile\nfrom typing import Union\n\nfrom modelforge import Model\n\nfrom ast2vec.df import DocumentFrequencies\nfrom ast2vec.uast import UASTModel\nfrom ast2vec.source import Source\nfrom ast2vec.model2.base import Model2Base\nfrom ast2vec.uast_ids_to_bag import UastIds2Bag\n\n\nclass ToDocFreqBase(Model2Base):\n \"\"\"\n Provides the docfreq state and the function which writes the result.\n It is shared with :class:`Uast2DocFreq` and :class:`MergeDocFreq`.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._df = defaultdict(int)\n self._docs = 0\n\n def finalize(self, index: int, destdir: str):\n model = DocumentFrequencies(log_level=logging.WARNING)\n model.construct(self._docs, self._df.keys(), self._df.values())\n if destdir.endswith(\".asdf\"):\n path = destdir\n else:\n path = os.path.join(destdir, \"docfreq_%d.asdf\" % index)\n model.save(path)\n\n\nclass Uast2DocFreq(ToDocFreqBase):\n \"\"\"\n Calculates document frequencies from models with UASTs.\n \"\"\"\n MODEL_FROM_CLASS = UASTModel\n MODEL_TO_CLASS = DocumentFrequencies\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self._uast2bag = UastIds2Bag(None)\n\n def convert_model(self, model: Model) -> Union[Model, None]:\n contained = set()\n for uast in model.uasts:\n for key in self._uast2bag.uast_to_bag(uast):\n contained.add(key)\n for word in contained:\n self._df[word] += 1\n self._docs += 1\n\n\nclass MergeDocFreq(ToDocFreqBase):\n \"\"\"\n Merges several :class:`DocumentFrequencies` models together.\n \"\"\"\n MODEL_FROM_CLASS = DocumentFrequencies\n MODEL_TO_CLASS = DocumentFrequencies\n\n def convert_model(self, model: Model) -> Union[Model, None]:\n for word, freq in model:\n self._df[word] += freq\n self._docs += model.docs\n\n\ndef uast2df_entry(args):\n converter = Uast2DocFreq(num_processes=args.processes)\n with tempfile.TemporaryDirectory(dir=args.tmpdir, prefix=\"source2uast\") as tmpdir:\n converter.convert(args.input, tmpdir, pattern=args.filter)\n joiner = MergeDocFreq(num_processes=1)\n joiner.convert(tmpdir, args.output,\n pattern=\"%s*.asdf\" % DocumentFrequencies.NAME)\n","sub_path":"ast2vec/model2/uast2df.py","file_name":"uast2df.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"136686617","text":"# MySQL\r\nimport pymysql\r\nimport os\r\n\r\n# Parametros para ingresar a la BBDD en MySQL\r\nDB_HOST = \"localhost\" # Nombre del host\r\nDB_USER = \"root\" # Nombre del usuario puesto en MySQL server\r\nDB_PASS = \"1234\" # Password de la conexion\r\nDB_NAME = \"PRUEBAS\" # Schema o database , no olvidar esto!!!\r\n\r\n# Funcion de conexion a BBDD y consultas\r\n\r\n\r\ndef conexionBBDD(consulta=\"\"):\r\n try:\r\n miConexion = pymysql.connect(\r\n host=DB_HOST, user=DB_USER, password=DB_PASS, db=DB_NAME)\r\n miCursor = miConexion.cursor()\r\n try:\r\n miCursor.execute(consulta)\r\n except:\r\n print(\"Error en la consulta\")\r\n if consulta.upper().startswith(\"SELECT\"):\r\n filas = miCursor.fetchall()\r\n for i in filas:\r\n print(i)\r\n if consulta.upper().startswith(\"SHOW\"):\r\n filas = miCursor.fetchall()\r\n for i in filas:\r\n print(i)\r\n else:\r\n miConexion.commit()\r\n miCursor.close()\r\n miConexion.close()\r\n except:\r\n print(\"Error al conectarse a la DDBB\")\r\n\r\n\r\ndef crearDatabase():\r\n # Crear la base de datos\r\n try:\r\n crearbase = \"\"\"CREATE DATABASE IF NOT EXISTS PRUEBAS\"\"\"\r\n miConexion = pymysql.connect(\r\n host=DB_HOST, user=DB_USER, password=DB_PASS)\r\n miCursor = miConexion.cursor()\r\n miCursor.execute(crearbase)\r\n miConexion.commit()\r\n miCursor.close()\r\n miConexion.close()\r\n print(\"DDBB creada con exito\")\r\n except:\r\n print(\"Error con la DDBB MySQL\")\r\n\r\n\r\ndef crearTabla():\r\n # Crear tabla\r\n try:\r\n creartabla = \"\"\"CREATE TABLE IF NOT EXISTS PERSONAS(DNI INT(8) PRIMARY KEY,NOMBRE VARCHAR(20),APELLIDO VARCHAR(20),SUELDO FLOAT)\"\"\"\r\n conexionBBDD(creartabla)\r\n print(\"Tabla creada con exito\")\r\n except:\r\n print(\"Error al crear la tabla\")\r\n\r\n\r\ndef insertarRegistro():\r\n # Insertar registros a la tabla\r\n try:\r\n\r\n nom = input(\"Ingrese nombre: \")\r\n ape = input(\"Ingrese apellido: \")\r\n dni = input(\"Ingrese DNI: \")\r\n sueldo = input(\"Ingrese sueldo: \")\r\n insertardato = \"INSERT INTO PERSONAS VALUES('\" + dni + \\\r\n \"','\" + nom + \"','\" + ape + \"','\" + sueldo + \"');\"\r\n conexionBBDD(insertardato)\r\n except:\r\n print(\"Error en el ingreso de datos\")\r\n\r\n\r\ndef mostrarTabla():\r\n # Mostrar tabla y obtencion de datos\r\n mostrartabla = \"SELECT * FROM PERSONAS ORDER BY DNI;\"\r\n conexionBBDD(mostrartabla)\r\n\r\n\r\ndef eliminarTabla():\r\n # Eliminar tabla\r\n try:\r\n borrartabla = \"DROP TABLE IF EXISTS PERSONAS;\"\r\n conexionBBDD(borrartabla)\r\n print(\"Tabla eliminada con exito\")\r\n except pymysql.Error as error:\r\n print(\"Error al eliminar tabla \" + error)\r\n\r\n\r\ndef mostrarRegistro():\r\n # Mostrar un solo registro\r\n try:\r\n dni = input(\"Ingrese DNI:\")\r\n mostrar = \"SELECT * FROM PERSONAS WHERE DNI='\" + dni + \"'\"\r\n conexionBBDD(mostrar)\r\n except pymysql.Error as error:\r\n print(\"Error en la busqueda de datos \" + error)\r\n\r\n\r\ndef actualizarRegistro():\r\n # Actualizar registro\r\n actualizardato = \"\"\"UPDATE PERSONAS SET NOMBRE=\"Joaquin\" WHERE NOMBRE=\"Santiago\";\"\"\"\r\n conexionBBDD(actualizardato)\r\n\r\n\r\ndef eliminarDatabase():\r\n # Elimino la base de datos\r\n eliminarbase = \"\"\"DROP DATABASE IF EXISTS PRUEBAS\"\"\"\r\n conexionBBDD(eliminarbase)\r\n\r\n\r\ndef mostrarDatabase():\r\n # Muestra base de datos\r\n mostrarbase = \"\"\"SHOW DATABASES\"\"\"\r\n conexionBBDD(mostrarbase)\r\n\r\n\r\ndef vaciarTabla():\r\n # Vacia la tabla\r\n vaciartable = \"\"\"TRUNCATE TABLE PERSONAS\"\"\"\r\n conexionBBDD(vaciartable)\r\n\r\n\r\nswitch = {\r\n 1: crearDatabase,\r\n 2: crearTabla,\r\n 3: insertarRegistro,\r\n 4: mostrarTabla,\r\n 5: mostrarRegistro,\r\n 6: mostrarDatabase,\r\n 7: actualizarRegistro,\r\n 8: vaciarTabla,\r\n 9: eliminarTabla,\r\n 10: eliminarDatabase\r\n}\r\n\r\n\r\ndef ejecutarFuncion(op):\r\n funcion = switch.get(op)\r\n return funcion()\r\n\r\n\r\n# Menu\r\nwhile True:\r\n print(\"Elija una opcion:\")\r\n print(\"1- Crear DDBB PRUEBAS\")\r\n print(\"2- Crear Tabla PERSONAS\")\r\n print(\"3- Insertar registros a la tabla\")\r\n print(\"4- Mostrar tabla\")\r\n print(\"5- Mostrar registro de la tabla por DNI\")\r\n print(\"6- Mostrar bases de datos\")\r\n print(\"7- Actualizar registro de la tabla\")\r\n print(\"8- Vaciar tabla\")\r\n print(\"9- Eliminar tabla\")\r\n print(\"10- Eliminar DDBB PRUEBAS\")\r\n print(\"0- Salir del programa\")\r\n opcion = int(input(\"Ingrese el valor elegido: \"))\r\n if(opcion > 0 and opcion <= 10):\r\n ejecutarFuncion(opcion)\r\n elif(opcion == 0):\r\n break\r\n else:\r\n print(\"Opcion erronea\")\r\n input(\"Presiona una tecla para continuar\")\r\n os.system('cls')\r\n","sub_path":"BBDD MySQL.py","file_name":"BBDD MySQL.py","file_ext":"py","file_size_in_byte":4817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"326165224","text":"import functools\nimport sys\nfrom typing import List\n\nfrom alignment.data_structure.eval_data_structure import Alignment2D, RelatedBinaryAnswer, \\\n convert_answer\nfrom tlm.qtype.partial_relevance.related_answer_data_path_helper import load_related_eval_answer, \\\n get_related_binary_save_path, save_json_at\n\n\ndef discretize_and_save(dataset_name, method):\n answers: List[Alignment2D] = load_related_eval_answer(dataset_name, method)\n cutoff = 0.5\n\n def convert(score):\n if score >= cutoff:\n return 1\n else:\n return 0\n\n convert_answer_fn = functools.partial(convert_answer, convert)\n new_answers: List[RelatedBinaryAnswer] = list(map(convert_answer_fn, answers))\n save_path = get_related_binary_save_path(dataset_name, method)\n save_json_at(new_answers, save_path)\n\n\ndef main():\n dataset_name = sys.argv[1]\n method = sys.argv[2]\n discretize_and_save(dataset_name, method)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/tlm/qtype/partial_relevance/runner/related_prediction/discretize.py","file_name":"discretize.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"156813369","text":"\n'''\n test suite for mongoDB\n'''\n\n#pylint: disable=too-many-statements\n#pylint: disable=invalid-name\n#pylint: disable=too-many-locals\n#pylint: disable=no-self-use\n#pylint: disable=unnecessary-pass\n#pylint: disable=pointless-string-statement\n#pylint: disable=unused-import\n\nimport sys\nimport logging\nfrom unittest import TestCase\n#from database import import_data, show_available_products\n#from database import show_rentals, dbs_cleanup\nimport database\n\nlogging.basicConfig()\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(logging.DEBUG)\n\nclass TestImportDataToDb(TestCase):\n '''test import data files to db'''\n def test_import_data(self):\n '''test importing data files'''\n LOGGER.info('Test import_data')\n measured_db = database.MeasuredDB()\n\n pathspec = \"csv_files_9\"\n result_count, result_errors = measured_db.import_data(pathspec,\n 'product_file.csv',\n 'customer_file.csv',\n 'rentals_file.csv')\n LOGGER.info('test_import_data, result_count = %s, result_errors = %s',\n str(result_count), str(result_errors))\n self.assertEqual(result_count, (9, 9, 9))\n self.assertEqual(result_errors, (0, 0, 0))\n measured_db.dbs_cleanup()\n\n pathspec = \"csv_files_90\"\n result_count, result_errors = measured_db.import_data(pathspec,\n 'product_file.csv',\n 'customer_file.csv',\n 'rentals_file.csv')\n LOGGER.info('test_import_data, result_count = %s, result_errors = %s',\n str(result_count), str(result_errors))\n self.assertEqual(result_count, (90, 90, 90))\n self.assertEqual(result_errors, (0, 0, 0))\n measured_db.dbs_cleanup()\n\n pathspec = \"csv_files_900\"\n result_count, result_errors = measured_db.import_data(pathspec,\n 'product_file.csv',\n 'customer_file.csv',\n 'rentals_file.csv')\n LOGGER.info('test_import_data, result_count = %s, result_errors = %s',\n str(result_count), str(result_errors))\n self.assertEqual(result_count, (906, 906, 906))\n self.assertEqual(result_errors, (0, 0, 0))\n\n # err check filenotfound\n result_count, result_errors = measured_db.import_data('csv_files',\n 'product_file.csvXXX',\n 'customer_file.csvXXX',\n 'rentals_file.csvXXX')\n LOGGER.info('test_import_data, result_count = %s, result_errors = %s',\n str(result_count), str(result_errors))\n self.assertEqual(result_count, (0, 0, 0))\n self.assertEqual(result_errors, (1, 1, 1))\n\n LOGGER.info('test_import_data completed')\n\n\nclass xTestsDatabase(TestCase):\n ''' test suite database '''\n measured_db = database.MeasuredDB()\n\n def setUp(self):\n ''' test setup '''\n LOGGER.info('setup start')\n\n dropped_status = self.measured_db.dbs_cleanup()\n LOGGER.info('test setup, dbs cleanup status = %s', dropped_status)\n\n ''' import data files '''\n LOGGER.info('setup import data file to database')\n self.measured_db.import_data('csv_files',\n 'product_file.csv',\n 'customer_file.csv',\n 'rentals_file.csv')\n\n LOGGER.info('test setup completed')\n\n def test_show_available_products(self):\n '''testing show_available_products function'''\n pass\n LOGGER.info('test show products with quantities available')\n result_dict = self.measured_db.show_available_products()\n expected_dict = {'pid001': {'description': 'sofa',\n 'product_type': 'livingroom',\n 'quantity_available': '5'},\n 'pid002': {'description': 'washer',\n 'product_type': 'laundry',\n 'quantity_available': '4'},\n 'pid004': {'description': 'edger',\n 'product_type': 'garage',\n 'quantity_available': '2'},\n 'pid005': {'description': 'desk',\n 'product_type': 'office',\n 'quantity_available': '1'}}\n self.assertEqual(result_dict, expected_dict)\n LOGGER.info('available products are %s', result_dict)\n LOGGER.info('test show_available_products tests completed')\n\n\n def test_show_rentals(self):\n ''' test show rentals '''\n LOGGER.info('test start show_rentals')\n expected_data = {'cid001': {'name': 'JohnSmith', 'address': '111 Broad St.',\n 'phone_number': '111-222-3333',\n 'email': 'JohnSmith@gmail.com'},\n 'cid004': {'name': 'BettySims', 'address': '444 First St.',\n 'phone_number': '444-555-6666',\n 'email': 'BettySims@gmail.com'}}\n result_dict = self.measured_db.show_rentals('pid001')\n self.assertEqual(result_dict, expected_data)\n LOGGER.info('test show_rentals customer who rented product %s, are %s',\n 'pid001', result_dict)\n LOGGER.info('test show_rentals completed')\n\n pass\n\n\n def test_dbs_cleanup(self):\n '''test drop dbs'''\n pass\n result_status = self.measured_db.dbs_cleanup()\n expected_status = 'databases dropped'\n self.assertEqual(result_status, expected_status)\n","sub_path":"students/mmancini/lesson10/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":6244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"529854910","text":"from multiprocessing import Pool\nimport bots\nimport logging\nimport sqlite3\nimport sys\nimport traceback\n\nimport praw\nimport time\nfrom requests import get\nfrom bots._helpers import SIGNATURE\n\n\"\"\"TODO: fix links inside \"\"\"\n\n# Set up logging\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s [%(levelname)-5.5s] %(message)s\",\n handlers=[\n logging.FileHandler(\"reddit.log\"),\n logging.StreamHandler(sys.stdout)\n ])\n\n# DB\nconn = sqlite3.connect(\"reddit.db\")\nc = conn.cursor()\nc.execute(\"CREATE TABLE IF NOT EXISTS comments (id text primary key, replied INTEGER DEFAULT 0)\")\n\n\ndef get_comments(callsigns=[\"mediapedia\", \"mediabot\"]):\n \"\"\"\n Gets comments from pushshift API.\n - callsigns: list of strings to search for\n \"\"\"\n\n comments = []\n\n for callsign in callsigns:\n api_url = \"https://api.pushshift.io/reddit/comment/search?q={}\".format(\n callsign)\n comments += get(api_url).json()[\"data\"]\n return comments\n\n\ndef was_processed(comment):\n \"\"\"\n Returns True if the comment has been processed.\n \"\"\"\n c.execute(\n \"SELECT id FROM comments WHERE id='{}'\".format(comment[\"id\"]))\n return bool(c.fetchone())\n\n\ndef reply(reddit_comment, reply):\n \"\"\"\n Replies to comment _reddit_comment_ with _reply_.\n\n On a loop to deal with reddit API limitations.\n \"\"\"\n\n while True:\n try:\n if not reddit_comment.body: # deleted\n return\n if len(reply) > 9000:\n reddit_comment.reply(\"Reply too long for reddit.\" + SIGNATURE)\n reddit_comment.reply(reply)\n c.execute(\n \"UPDATE comments SET replied='1' WHERE id='{}'\".format(reddit_comment.id))\n conn.commit()\n logging.info(\"Replied\")\n return\n except praw.exceptions.APIException as e:\n if e.field != \"ratelimit\":\n raise e\n logging.error(e)\n time.sleep(30)\n\n\ndef process_comment(comment, reddit):\n \"\"\"\n Processes comment, replies using reddit bot.\n \"\"\"\n reddit_comment = reddit.comment(id=comment[\"id\"])\n comment_replies = []\n\n c.execute(\n \"INSERT INTO comments (id) VALUES ('{}')\".format(comment[\"id\"]))\n conn.commit()\n if comment[\"body\"].count(\"!mediabot\") + comment[\"body\"].count(\"!mediapedia\") > 4:\n reply(reddit_comment,\n \"You have exceeded the maximum number of calls per coment (5).\\n\\n\" + SIGNATURE)\n return\n\n for bot in bots.bots:\n comment_replies += bot.run(comment)\n\n reply_text = \"\\n\\n ***\".join(comment_replies) + SIGNATURE\n reply(reddit_comment, reply_text)\n\n\ndef run_bot(reddit):\n \"\"\"\n Main loop\n \"\"\"\n comments = get_comments()\n comments = [comment for comment in comments if not was_processed(comment)]\n if comments:\n logging.info(\"{} new comments\".format(len(comments)))\n for comment in comments:\n process_comment(comment, reddit)\n\n\ndef main():\n reddit = praw.Reddit(\"mediapedia\")\n while True:\n try:\n run_bot(reddit)\n except Exception as E:\n if E == KeyboardInterrupt:\n sys.exit()\n traceback.print_exc()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"reddit_bot.py","file_name":"reddit_bot.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"322566999","text":"from random import randint, sample\nimport pdb\n\npdb.set_trace()\n\nganadores = sorted(sample(range(1, 49 + 1), 6))\n\ncomp = randint(1, 49)\nreint = randint(0, 9)\n\nprint('Números ganadores:', ganadores)\nprint('Complementario:', comp)\nprint('Reintegro:', reint)\n","sub_path":"module2/basics/primitiva.py","file_name":"primitiva.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"358145205","text":"class Test(object):\n\n # # Constructor. __init__ will have double underscore.\n def __init__(self, val):\n self.val = val\n\n # Called when iteration is initialized \n def __iter__(self):\n self.x = 10\n return self\n\n # To move to next element\n def __next__(self):\n # Stores current value of x .\n x = self.x\n # Stop iteration if limit is reached \n if x > self.val:\n raise StopIteration\n # Else increment and return old value \n self.x = x + 1\n return x\n\n \nfor i in Test(15):\n print(i, end=\" \")\n# raise stop iteration signal.\nfor i in Test(5):\n print(i, end=\" \")","sub_path":"PythonBasics/com/vijay/basics/GeekForGeeks/ItrTest2.py","file_name":"ItrTest2.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"612797084","text":"import traceback\n\nfrom flask import make_response, render_template\nfrom flask_restful import Resource, reqparse\nfrom models.usuario import UserModel\nfrom flask_jwt_extended import create_access_token\nfrom werkzeug.security import safe_str_cmp\nfrom flask_jwt_extended import jwt_required, get_jwt\nfrom blacklist import BLACKLIST\n\n# Variavel de requisicao\natributos = reqparse.RequestParser()\natributos.add_argument('login',\n type=str,\n required=True,\n help='The field login cannot be left blank.')\natributos.add_argument('senha',\n type=str,\n required=True,\n help='The field senha cannot be left blank.')\natributos.add_argument('email', type=str)\natributos.add_argument('ativado', type=bool)\n\n\n\nclass User(Resource):\n # /usuarios/{user_id}\n def get(self, user_id):\n user = UserModel.find_user(user_id)\n if user is not None:\n return user.json(), 200\n return {'message': 'User not found'}, 404\n\n @jwt_required()\n def delete(self, user_id):\n user = UserModel.find_user(user_id)\n\n if user:\n try:\n user.delete_user()\n except:\n return {'message': 'An internal error ocurred trying to delete'}, 500\n\n return {'message': 'User deleted.'}, 200\n return {'message': 'User not found'}, 404\n\nclass UserRegister(Resource):\n # /cadastro\n\n def post(self):\n dados = atributos.parse_args()\n if not dados.get('email') or dados.get('email') is None:\n return {\"message\": \"The field 'email' cannot be left blank.\"}, 400\n\n if UserModel.find_by_email(dados['email']):\n return {\"message\": \"The email '{}' already exists.\".format(dados['email'])}, 400\n\n # Se o login existe\n if UserModel.find_by_login(dados['login']):\n return {\"message\":\"The login '{}' already exists\".format(dados['login'])}\n\n user = UserModel(**dados)\n user.ativado = False\n\n try:\n user.save_user()\n user.send_confirmation_email()\n except:\n user.delete_user()\n traceback.print_exc()\n return {\"message\": \"An internal error server has ocurred.\"}, 500\n return {'message':'User created succesfully.'}, 201\n\n\nclass UserLogin(Resource):\n\n @classmethod\n def post(cls):\n dados = atributos.parse_args()\n\n user = UserModel.find_by_login(dados['login'])\n\n if user and safe_str_cmp(user.senha, dados['senha']):\n if user.ativado:\n token_acesso = create_access_token(identity=user.user_id)\n return {'access_toke': token_acesso}, 200\n return {'message': \"User not confirmed. Please check the user's e-mail.\"}, 401\n return {'message':'The username or password is incorrect.'}, 401\n\n\nclass UserLogout(Resource):\n\n @jwt_required()\n def post(self):\n jwt_id = get_jwt()['jti'] # JWT Token Identifier\n BLACKLIST.add(jwt_id)\n return {'message':'Logged out successfully'}, 200\n\nclass UserConfirm(Resource):\n # raiz_do_site/confirmacao/user_id\n @classmethod\n def get(cls, user_id):\n user = UserModel.find_user(user_id)\n\n if not user:\n return {\"message\":\"User id '{}' not found.\".format(user_id)}, 404\n\n user.ativado = True\n user.save_user()\n # return {\"message\": \"User '{}' confirmed successfully.\".format(user_id)}, 200\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template('user_confirm.html', email=user.email, usuario=user.login),\n 200, headers)\n\n\n","sub_path":"resources/usuario.py","file_name":"usuario.py","file_ext":"py","file_size_in_byte":3729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"644544825","text":"import json\nfrom datetime import datetime\n\n# date format in data.json\ndate_format = \"%Y-%m-%d\"\n\n\n# list of the rentals\nrentals = []\n\n# find the car corresponding to the rental\ndef find_car(rental):\n return [car for car in data['cars'] if car['id'] == rental['car_id']][0]\n\n# find options corresponding to the rental\ndef find_option(rental):\n return [option for option in data['options'] if option['rental_id'] == rental['id'][0]]\n\n# compute the number of days of a rental\ndef number_of_days(rental):\n return (datetime.strptime(rental['end_date'], date_format) - datetime.strptime(rental['start_date'], date_format)).days + 1\n\n# compute the price of a rental\ndef compute_price(rental):\n car = find_car(rental)\n rental_days = number_of_days(rental)\n\n price_per_day = car['price_per_day']\n\n # compute the distance component of the price\n distance_component = rental['distance']*car['price_per_km']\n\n # compute the time component of the price\n if rental_days > 10:\n time_component = price_per_day + 3*(0.9*price_per_day) + 6*(0.7*price_per_day) + (rental_days-10)*(0.5*price_per_day)\n elif rental_days > 4:\n time_component = price_per_day + 3*(0.9*price_per_day) + (rental_days-4)*(0.7*price_per_day)\n elif rental_days > 1:\n time_component = price_per_day + (rental_days-1)*(0.9*price_per_day)\n else:\n time_component = price_per_day\n\n return int(time_component+distance_component)\n\n# compute the details of the commission\ndef compute_commission(rental):\n price = compute_price(rental)\n price_fee = price\n commission = 0.3*price\n insurance_fee = 0.5*commission\n assistance_fee = 100*number_of_days(rental)\n drivy_fee = commission - (insurance_fee+assistance_fee)\n\t\n\t#compite the details of option\n option = find_option(rental)\n type = []\n for option in option:\n type = option['type']\n for type in type:\n if type == \"gps\":\n price+=500\n price_fee+=500\n elif type ==\"baby_seat\":\n price+=200\n price_fee+=200\n elif type==\"additional_insurance\":\n price=price+1000\n drivy_fee+=1000\n\n return {'price_fee':int(price_fee), 'insurance_fee': int(insurance_fee), 'assistance_fee': int(assistance_fee), 'drivy_fee': int(drivy_fee)}\t\t\n\n# compute the actions for each actor\ndef compute_actions(rental):\n price = compute_price(rental)\n commission_details = compute_commission(rental)\n commission = sum(commission_details.values())\n\n driver = {\"who\": \"driver\", \"type\": \"debit\", \"amount\": price}\n owner = {\"who\": \"owner\", \"type\": \"credit\", \"amount\": commission_details['price_fee'] - commission}\n insurance = {\"who\": \"insurance\", \"type\": \"credit\", \"amount\": commission_details['insurance_fee']}\n assistance = {\"who\": \"assistance\", \"type\": \"credit\", \"amount\": commission_details['assistance_fee']}\n drivy = {\"who\": \"drivy\", \"type\": \"credit\", \"amount\": commission_details['drivy_fee']}\n\n return [driver, owner, insurance, assistance, drivy]\n\n# open data.json\nwith open('data.json') as data_file:\n data = json.load(data_file)\n\n# for each rental, compute the actions and put it in the list\nfor rental in data['rentals']:\n rentals.append({'id': rental['id'], 'option':type ,'actions': compute_actions(rental)})\n\n# write result.json\nwith open('result.json', 'w') as outfile:\n json.dump({'rentals': rentals}, outfile, indent=2)\n","sub_path":"level5.py","file_name":"level5.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"231843130","text":"from process import get_data\nfrom torchtext import data\n\ndef get_some_batch():\n \"Batch 하나 가져오기\"\n data_path = \"dataset/\"\n file_name = \"train.\"\n\n txt_en, train_en = get_data(file_path = data_path + file_name + 'en',\n field_name = 'en')\n\n train_loader = data.Iterator(train_en, batch_size = 3,\n device = None, # if using GPU, type \"cuda\" \n repeat = False)\n\n for batch in train_loader:\n break\n\n a = batch.en\n return a[1]\n\nfrom embedding import Embeddings, PositionalEncoding\n\ndef emb_pe(b, n_vocab = 30000):\n \n emb = Embeddings(d_model = 128, vocab = 25000)\n\n x = emb(b).unsqueeze(0)\n\n PE = PositionalEncoding(d_model = 128, dropout = .1)\n\n return PE(x)\n\n ","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"107020787","text":"#!/usr/bin/env python\n\n# Copyright 2019 Alvaro Bartolome\n# See LICENSE for details.\n\nimport random\nimport pkg_resources\nimport os\n\n\ndef get_random():\n \"\"\"\n This function selects a random User-Agent from the `user-agent-list` txt file, in order to avoid \n the limitations of the requests that are going to be sent to GitHub. The User-Agent is specified \n on the headers of the requests and is different for every request.\n\n Returns:\n :obj:`str` - user_agent:\n The returned :obj:`str` is the name of a random User-Agent, which will be passed on the \n headers of a request so to avoid restrictions due to the use of multiple requests from the \n same User-Agent.\n \n Raises:\n IOError: raised when `user_agent_list.txt` file was unable to retrieve or errored.\n FileNotFoundError: raised if `user_agent_list.txt` file has not been found.\n\n \"\"\"\n\n resource_package = __name__\n resource_path = '/'.join(('resources', 'user_agent_list.txt'))\n file_ = pkg_resources.resource_filename(resource_package, resource_path)\n\n if os.path.exists(file_):\n with open(file_, 'r') as f:\n content = f.read(1)\n\n if content:\n lines = f.readlines()\n\n return str(random.choice(lines)).replace(\"\\n\", \"\")\n else:\n raise IOError(\"unable to retrieve a random user agent!\")\n else:\n raise FileNotFoundError(\"user agents file not found!\")\n","sub_path":"rankhub/user_agent.py","file_name":"user_agent.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"557639795","text":"from __future__ import unicode_literals\nimport unittest\n\nfrom wdeploy.project_builder_loader import BaseProjectBuilder, \\\n ProjectBuilderNotFoundError\nfrom wdeploy.test import BaseTestCase\n\n__author__ = 'pahaz'\n\n\nclass TestProjectBuilderLoader(BaseTestCase):\n @unittest.skip(\"Docker Builder loaded defore. Check it!\")\n def test_raise_not_found(self):\n loader = self.make_project_builder_loader()\n info = self.mock_project_info()\n with self.assertRaises(ProjectBuilderNotFoundError):\n print(loader.get_builder_for_project(info, {}))\n\n @unittest.skip(\"Docker Builder loaded defore. Check it!\")\n def test_load_my_builder(self):\n FAKE_PROJECT_NAME = 'random-name'\n\n loader = self.make_project_builder_loader()\n info = self.mock_project_info(name=FAKE_PROJECT_NAME)\n\n class __MyBuilder(BaseProjectBuilder):\n is_called = False\n\n @classmethod\n def make_ProjectBuilder_or_None(cls, info, options):\n cls.is_called = True\n if info.name == FAKE_PROJECT_NAME:\n return cls(info, options)\n\n make_image_name = build = make_project_runner = lambda x: x\n\n Builder = loader.get_builder_for_project(info, {})\n self.assertEqual(__MyBuilder.is_called, True)\n self.assertIsInstance(Builder, __MyBuilder)\n self.assertEqual(__MyBuilder.class_brothers[0], __MyBuilder)\n","sub_path":"packages/wdeploy/test/test_project_builder_loader.py","file_name":"test_project_builder_loader.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"605372837","text":"# in your django app's models.py file\n\"\"\"\nUSAGE: these functions allow you to pull the\nX/Y coordinates of a geotagged photo.\nIn a Django HTML template, you can use it like this:\n {{ photo.lat }}, {{ photo.lon }} \"\"\"\n\nfrom PIL import Image as PImage\nfrom PIL.ExifTags import TAGS, GPSTAGS\n\nclass Photo(models.Model):\n # ... rest of model here ...\n #\n def lat(self):\n image = PImage.open(self.image)\n exif_data = get_exif(image)\n self.lat, self.lon = get_lat_lon(exif_data)\n return self.lat\n\n def lon(self):\n image = PImage.open(self.image)\n exif_data = get_exif(image)\n self.lat, self.lon = get_lat_lon(exif_data)\n return self.lon\n\n# latitude/longitude functions\n# # # # # # # # # # # # # # # # #\ndef get_exif(image):\n \"\"\" input 'image' must be an image opened w/ PIL.\n Returns a dictionary from the exif data of the\n PIL Image. Also converts the GPS Tags\"\"\"\n exif_data = {}\n info = image._getexif()\n if info:\n for tag, value in info.items():\n decoded = TAGS.get(tag, tag)\n if decoded == \"GPSInfo\":\n gps_data = {}\n for t in value:\n sub_decoded = GPSTAGS.get(t, t)\n gps_data[sub_decoded] = value[t]\n exif_data[decoded] = gps_data\n else:\n exif_data[decoded] = value\n return exif_data\n\ndef _get_if_exist(data, key):\n if key in data:\n return data[key]\n return None\n\ndef _convert_to_degress(value):\n \"\"\"Helper function to convert the GPS coordinates\n stored in the EXIF to degress in float format\"\"\"\n d0 = value[0][0]\n d1 = value[0][1]\n d = float(d0) / float(d1)\n\n m0 = value[1][0]\n m1 = value[1][1]\n m = float(m0) / float(m1)\n\n s0 = value[2][0]\n s1 = value[2][1]\n s = float(s0) / float(s1)\n\n return d + (m / 60.0) + (s / 3600.0)\n\ndef get_lat_lon(exif_data):\n lat = None\n lon = None\n\n if \"GPSInfo\" in exif_data:\n gps_info = exif_data[\"GPSInfo\"]\n\n gps_latitude = _get_if_exist(gps_info, \"GPSLatitude\")\n gps_latitude_ref = _get_if_exist(gps_info, 'GPSLatitudeRef')\n gps_longitude = _get_if_exist(gps_info, 'GPSLongitude')\n gps_longitude_ref = _get_if_exist(gps_info, 'GPSLongitudeRef')\n\n if gps_latitude and gps_latitude_ref \\\n and gps_longitude and gps_longitude_ref:\n lat = _convert_to_degress(gps_latitude)\n if gps_latitude_ref != \"N\":\n lat = 0 - lat\n lon = _convert_to_degress(gps_longitude)\n if gps_longitude_ref != \"E\":\n lon = 0 - lon\n\n return lat, lon","sub_path":"django/geotagged_data.py","file_name":"geotagged_data.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"388208142","text":"import sys\n# import xbmc\n# import xbmcgui\n# import xbmcaddon\nimport os\nimport subprocess\nfrom time import sleep\nfrom subprocess import call\n\nimport requests\nimport json\nimport urllib\nimport ConfigParser\n\n\ndef checkIfMovie():\n isTVorMovieQuery = {'jsonrpc': '2.0', 'method': 'Player.GetItem', 'params': {'properties': ['showtitle', 'season', 'episode'], 'playerid': 1}, 'id': 'VideoGetItem'}\n response = json.loads(xbmc.executeJSONRPC(json.dumps(isTVorMovieQuery)))\n if response['result']['item']['season'] == -1:\n return True\n else:\n return False\n\n\ndef getLightState(name, type='label'):\n \"\"\" This function checks what lights are in the group and what color they are currently set to \"\"\"\n if name == 'all':\n getAvaliableLights = requests.get(lifxCloud + '/' + name, headers=header)\n else:\n getAvaliableLights = requests.get(lifxCloud + '/' + urllib.quote(type + ':' + name), headers=header)\n\n if getAvaliableLights.status_code == requests.codes.ok:\n avaliableLights = json.loads(getAvaliableLights.text)\n info = []\n for light in avaliableLights:\n info.append({'id': light['id'], 'label': light['label'], 'power': light['power'], 'hue': light['color']['hue'], 'saturation': light['color']['saturation'],\n 'brightness': light['brightness']})\n return info\n return False\n\n\ndef restoreLights(LightStates, duration=1):\n \"\"\" This function's purpose is to set the lights to a given HSK from what they once were\"\"\"\n for light in LightStates:\n if light['power'] == 'on':\n power = 'true'\n option = {'color': 'hsb:' + str(light['hue']) + ',' + str(light['saturation']) + ',' + str(light['brightness']), 'duration': duration, 'power': power}\n chooseBulb = lifxCloud + '/' + urllib.quote('id:') + light['id'] + '/color.json'\n requests.put(chooseBulb, json=option, headers=header)\n else:\n power = 'false'\n turnOff(name=light['id'], type='id', duration=duration)\n continue\n\n\ndef turnOff(name, type='label', duration=1):\n \"\"\" This function turns off a given group or light \"\"\"\n powerCommand = lifxCloud + '/' + urllib.quote(type + ':' + name) + '/power.json'\n option = {'state': 'off', 'duration': duration}\n requests.put(powerCommand, json=option, headers=header)\n return\n\n\ndef loadConfig ():\n global header\n global bulbs\n global setColor\n global config\n\n confpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'lifx.cfg')\n config = ConfigParser.RawConfigParser()\n config.readfp(open(confpath))\n\n apiKey = config.get('Authentication', 'apiKey')\n apiKey = 'Bearer ' + apiKey\n header = {'content-type': 'application/json', 'authorization': apiKey}\n\n bulbs = {'type': config.get('Bulbs', 'type'), 'set': config.get('Bulbs', 'set')}\n bulbURL = urllib.quote(bulbs['type'] + ':' + bulbs['set'])\n setColor = lifxCloud + bulbURL + '/color.json'\n\nlifxCloud = 'https://api.lifx.co/v1beta1/lights/'\n\nloadConfig()\n\npreVideolightState = []\n\nclass XBMCPlayer(xbmc.Player):\n\n def __init__(self, *args):\n pass\n\n def onPlayBackStarted(self):\n global preVideolightState\n loadConfig()\n preVideolightState = getLightState(type=bulbs['type'], name=bulbs['set'])\n if checkIfMovie():\n turnOff(name=bulbs['set'], type=bulbs['type'], duration=config.get('Delay', 'MovieStart'))\n else:\n option = {'color': 'blue brightness:5%', 'duration': config.get('Delay', 'TVStart'), 'power_on': 'true'}\n r = requests.put(setColor, json=option, headers=header)\n\n def onPlayBackResumed(self):\n global preVideolightState\n loadConfig()\n preVideolightState = getLightState(type=bulbs['type'], name=bulbs['set'])\n if checkIfMovie():\n turnOff(name=bulbs['set'], type=bulbs['type'], duration=config.get('Delay', 'Pause'))\n else:\n option = {'color': 'blue brightness:5%', 'duration': config.get('Delay', 'UnPause'), 'power_on': 'true'}\n r = requests.put(setColor, json=option, headers=header)\n\n def onPlayBackEnded(self):\n restoreLights(preVideolightState, duration=config.get('Delay', 'EndPlay'))\n\n def onPlayBackPaused(self):\n restoreLights(preVideolightState, duration=config.get('Delay', 'Pause'))\n\n def onPlayBackStopped(self):\n restoreLights(preVideolightState, duration=config.get('Delay', 'EndPlay'))\n\nplayer = XBMCPlayer()\n\nwhile(not xbmc.abortRequested):\n xbmc.sleep(100)","sub_path":"service.NateKodi.LIFX/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":4577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"441306624","text":"# Copyright The IETF Trust 2021, 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# We always check result.is_json, so result.json will never return None.\n# pyright: reportOptionalSubscript=false\n\n__author__ = 'Richard Zilincik'\n__copyright__ = 'Copyright The IETF Trust 2021, All Rights Reserved'\n__license__ = 'Apache License, Version 2.0'\n__email__ = 'richard.zilincik@pantheon.tech'\n\nimport json\nimport os\nimport unittest\nfrom unittest import mock\n\nfrom api.authentication.auth import auth\nfrom api.yangcatalog_api import app\n\napp_config = app.config\n\n\nclass TestApiInternalClass(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n resources_path = os.path.join(os.environ['BACKEND'], 'tests/resources')\n cls.client = app.test_client()\n with open(os.path.join(resources_path, 'payloads.json'), 'r') as f:\n cls.payloads_content = json.load(f)\n\n @mock.patch('api.views.yc_jobs.run_script.s')\n def test_trigger_ietf_pull(self, run_script_mock: mock.MagicMock):\n run_script_mock.return_value.apply_async.return_value = mock.MagicMock(id=1)\n auth.hash_password(lambda _: 'True')\n auth.get_password(lambda _: 'True')\n result = self.client.get('api/ietf', auth=('admin', 'admin'))\n\n self.assertEqual(result.status_code, 202)\n self.assertTrue(result.is_json)\n data = result.json\n self.assertIn('job-id', data)\n self.assertEqual(data['job-id'], 1)\n\n @mock.patch('api.views.yc_jobs.run_script.s', mock.MagicMock())\n def test_trigger_ietf_pull_not_admin(self):\n auth.hash_password(lambda _: 'True')\n auth.get_password(lambda _: 'True')\n result = self.client.get('api/ietf', auth=('user', 'user'))\n\n self.assertEqual(result.status_code, 401)\n self.assertTrue(result.is_json)\n data = result.json\n self.assertIn('description', data)\n self.assertEqual(data['description'], 'User must be admin')\n\n @mock.patch('api.views.yc_jobs.github_populate.s', mock.MagicMock())\n @mock.patch('utility.message_factory.MessageFactory')\n @mock.patch('utility.repoutil.pull', mock.MagicMock())\n def test_trigger_populate(self, mock_message_factory: mock.MagicMock):\n body = {\n 'commits': [\n {\n 'added': ['vendor/cisco/nx/9.2-2/platform-metadata.json'],\n 'modified': ['vendor/cisco/xe/1651/platform-metadata.json'],\n },\n ],\n }\n result = self.client.post('api/check-platform-metadata', json=body)\n\n self.assertEqual(result.status_code, 200)\n self.assertTrue(result.is_json)\n data = result.json\n self.assertIn('info', data)\n self.assertEqual(data['info'], 'Success')\n mock_message_factory.return_value.send_new_modified_platform_metadata.call_args.assert_called_with(\n 'vendor/cisco/nx/9.2-2',\n 'vendor/cisco/xe/1651',\n )\n\n @mock.patch('api.views.yc_jobs.github_populate.s', mock.MagicMock())\n @mock.patch('utility.message_factory.MessageFactory', mock.MagicMock())\n @mock.patch('utility.repoutil.pull', mock.MagicMock())\n def test_trigger_populate_empty(self):\n result = self.client.post('api/check-platform-metadata')\n\n self.assertEqual(result.status_code, 200)\n self.assertTrue(result.is_json)\n data = result.json\n self.assertIn('info', data)\n self.assertEqual(data['info'], 'Success')\n\n @mock.patch('builtins.open', mock.mock_open(read_data='{\"test\": true}'))\n @mock.patch('os.path.exists')\n def test_get_statistics(self, mock_exists: mock.MagicMock):\n mock_exists.return_value = True\n result = self.client.get('api/get-statistics')\n\n self.assertEqual(result.status_code, 200)\n\n @mock.patch('os.path.exists')\n def test_get_statistics_not_generated(self, mock_exists: mock.MagicMock):\n mock_exists.return_value = False\n result = self.client.get('api/get-statistics')\n\n self.assertEqual(result.status_code, 404)\n self.assertEqual(result.content_type, 'application/json')\n data = result.json\n self.assertIn('description', data)\n self.assertEqual(data['description'], 'Statistics file has not been generated yet')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_api_internal.py","file_name":"test_api_internal.py","file_ext":"py","file_size_in_byte":4857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420589650","text":"import tqdm\nimport argparse\nimport logging\nimport os\nimport json\nimport torch\nimport random\nimport numpy as np\n\nfrom classifier.classifier_bert import Classifier\nfrom s2s_ft.modeling import BertForSequenceToSequence\n\nfrom retriever import Retriever\nfrom transformers import BertConfig, BertTokenizer\nfrom s2s_ft.configuration_unilm import UnilmConfig\nfrom s2s_ft.tokenization_unilm import UnilmTokenizer\n\nfrom s2s_ft.config import BertForSeq2SeqConfig\nfrom train import self_training\nfrom dataloader import NoExpDataset, ClassifierDataset, GeneratorDataset, ValidDataset\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n\n # parser.add_argument(\"--train_source_file\", default=None, type=str, required=True,\n # help=\"Training data contains source\")\n # parser.add_argument(\"--train_target_file\", default=None, type=str, required=True,\n # help=\"Training data contains target\")\n parser.add_argument(\"--labeled_data\", default=None, type=str, required=True,\n help=\"Labeled training data (json format) for training.\")\n parser.add_argument(\"--unlabeled_data\", default=None, type=str, required=True,\n help=\"Unlabeled training data (json format) for training.\")\n parser.add_argument(\"--exp_data\", default=None, type=str, required=True,\n help=\"Training data with exps(json format) for training.\")\n parser.add_argument(\"--valid_data\", default=None, type=str, required=True,\n help=\"Valid data (json format) for training.\")\n parser.add_argument(\"--test_data\", default=None, type=str, required=True,\n help=\"test data (json format) for training.\")\n parser.add_argument(\"--num_labels\", default=2, type=int, required=True,\n help=\"Lebels to be classified\")\n parser.add_argument(\"--label_to_id\", default=None, type=str,\n help=\"label_to_id files for RE task\")\n parser.add_argument(\"--output_dir\", default=None, type=str, required=True,\n help=\"The output directory where the model checkpoints and predictions will be written.\")\n\n parser.add_argument(\"--log_dir\", default=None, type=str,\n help=\"The output directory where the log will be written.\")\n\n # Other parameters\n parser.add_argument(\"--config_name\", default=None, type=str,\n help=\"Pretrained config name or path if not the same as model_name\")\n parser.add_argument(\"--tokenizer_name\", default=None, type=str,\n help=\"Pretrained tokenizer name or path if not the same as model_name\")\n parser.add_argument(\"--cache_dir\", default=None, type=str,\n help=\"Where do you want to store the pre-trained models downloaded from s3\")\n\n parser.add_argument(\"--max_source_seq_length\", default=128, type=int,\n help=\"The maximum total source sequence length after WordPiece tokenization. Sequences \"\n \"longer than this will be truncated, and sequences shorter than this will be padded.\")\n parser.add_argument(\"--max_target_seq_length\", default=64, type=int,\n help=\"The maximum total target sequence length after WordPiece tokenization. Sequences \"\n \"longer than this will be truncated, and sequences shorter than this will be padded.\")\n\n parser.add_argument(\"--cached_train_features_file\", default=None, type=str,\n help=\"Cached training features file\")\n parser.add_argument(\"--train_from_scratch\", action='store_true',\n help=\"whether initialize the model at beginning of every step\")\n parser.add_argument(\"--do_lower_case\", action='store_true',\n help=\"Set this flag if you are using an uncased model.\")\n\n parser.add_argument(\"--per_gpu_train_batch_size\", default=8, type=int,\n help=\"Batch size per GPU/CPU for training.\")\n parser.add_argument(\"--learning_rate\", default=5e-5, type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument('--gradient_accumulation_steps', type=int, default=1,\n help=\"Number of updates steps to accumulate before performing a backward/update pass.\")\n parser.add_argument(\"--weight_decay\", default=0.01, type=float,\n help=\"Weight decay if we apply some.\")\n parser.add_argument(\"--adam_epsilon\", default=1e-8, type=float,\n help=\"Epsilon for Adam optimizer.\")\n parser.add_argument(\"--max_grad_norm\", default=1.0, type=float,\n help=\"Max gradient norm.\")\n parser.add_argument(\"--label_smoothing\", default=0.1, type=float,\n help=\"Max gradient norm.\")\n parser.add_argument(\"--num_training_steps\", default=-1, type=int,\n help=\"set total number of training steps to perform\")\n parser.add_argument('--num_classifier_epochs_per_iters', type=int, default=10,\n help=\"Training epochs when initlizing.\")\n parser.add_argument('--num_generator_epochs_per_iters', type=int, default=10,\n help=\"Training epochs when initlizing.\")\n parser.add_argument('--num_iters', type=int, default=5,\n help=\"Training epochs when initlizing.\")\n parser.add_argument('--num_selftrain_iters', type=int, default=10,\n help=\"Training epochs when initlizing.\")\n parser.add_argument(\"--num_warmup_steps\", default=0, type=int,\n help=\"Linear warmup over warmup_steps.\")\n\n parser.add_argument(\"--random_prob\", default=0.1, type=float,\n help=\"prob to random replace a masked token\")\n parser.add_argument(\"--keep_prob\", default=0.1, type=float,\n help=\"prob to keep no change for a masked token\")\n\n parser.add_argument('--logging_steps', type=int, default=50,\n help=\"Log every X updates steps.\")\n parser.add_argument('--save_steps', type=int, default=1500,\n help=\"Save checkpoint every X updates steps.\")\n parser.add_argument(\"--no_cuda\", action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument('--seed', type=int, default=42,\n help=\"random seed for initialization\")\n\n parser.add_argument('--beam_size', type=int, default=1,\n help=\"Beam size for searching\")\n parser.add_argument('--num_samples_per_iter', type=int, default=300,\n help=\"Beam size for searching\")\n\n parser.add_argument(\"--local_rank\", type=int, default=-1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument('--fp16', action='store_true',\n help=\"Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit\")\n parser.add_argument('--fp16_opt_level', type=str, default='O1',\n help=\"For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3'].\"\n \"See details at https://nvidia.github.io/apex/amp.html\")\n parser.add_argument('--server_ip', type=str, default='', help=\"Can be used for distant debugging.\")\n parser.add_argument('--server_port', type=str, default='', help=\"Can be used for distant debugging.\")\n parser.add_argument('--pos_shift', action='store_true',\n help=\"Using position shift for fine-tuning.\")\n args = parser.parse_args()\n return args\n\n\ndef get_model_and_tokenizer(args):\n model_config = UnilmConfig.from_pretrained(\n args.config_name if args.config_name else 'unilm-base-cased',\n cache_dir=args.cache_dir if args.cache_dir else None)\n config = BertForSeq2SeqConfig.from_exist_config(\n config=model_config, label_smoothing=args.label_smoothing,\n max_position_embeddings=args.max_source_seq_length + args.max_target_seq_length)\n\n logger.info(\"Model config for seq2seq: %s\", str(config))\n\n generator_tokenizer = UnilmTokenizer.from_pretrained(\n args.tokenizer_name if args.tokenizer_name else 'unilm-base-cased',\n do_lower_case=args.do_lower_case, cache_dir=args.cache_dir if args.cache_dir else None)\n\n generator = BertForSequenceToSequence.from_pretrained(\n 'unilm-base-cased', config=config, model_type='unilm',\n reuse_position_embedding=True,\n cache_dir=args.cache_dir if args.cache_dir else None)\n generator.to(args.device)\n\n classifier_tokenizer = BertTokenizer.from_pretrained('bert-base-cased')\n config = BertConfig.from_pretrained('bert-base-cased')\n config.num_labels = args.num_labels\n classifer = Classifier.from_pretrained('bert-base-cased', config=config)\n classifier_tokenizer.add_tokens(['#obj#', '#/obj#', '#subj#', '#/subj#'])\n classifer.resize_token_embeddings(len(classifier_tokenizer))\n classifer.to(args.device)\n\n logger.info(\"Initialize retriever.\")\n retriever = Retriever(args, classifier_tokenizer)\n return generator, classifer, classifier_tokenizer, generator_tokenizer, retriever\n\n\ndef prepare(args):\n # Setup distant debugging if needed\n if args.server_ip and args.server_port:\n # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script\n import ptvsd\n print(\"Waiting for debugger attach\")\n ptvsd.enable_attach(address=(args.server_ip, args.server_port), redirect_output=True)\n ptvsd.wait_for_attach()\n\n os.makedirs(args.output_dir, exist_ok=True)\n json.dump(args.__dict__, open(os.path.join(\n args.output_dir, 'train_opt.json'), 'w'), sort_keys=True, indent=2)\n\n # Setup CUDA, GPU & distributed training\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n args.n_gpu = torch.cuda.device_count()\n else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n torch.distributed.init_process_group(backend='nccl')\n args.n_gpu = 1\n args.device = device\n args.batch_size = args.per_gpu_train_batch_size * args.n_gpu\n # Setup logging\n logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN)\n logger.warning(\"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s\",\n args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), args.fp16)\n\n # Set seed\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n\n if args.n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n logger.info(\"Training/evaluation parameters %s\", args)\n\n # Before we do anything with models, we want to ensure that we get fp16 execution of torch.einsum if args.fp16 is set.\n # Otherwise it'll default to \"promote\" mode, and we'll get fp32 operations. Note that running `--fp16_opt_level=\"O2\"` will\n # remove the need for this code, but it is still valid.\n if args.fp16:\n try:\n import apex\n apex.amp.register_half_function(torch, 'einsum')\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use fp16 training.\")\n\n\ndef main():\n args = get_args()\n prepare(args)\n generator, classifier, classifier_tokenizer, generator_tokenizer, retriever = get_model_and_tokenizer(args)\n\n noexpdataset = NoExpDataset(classifier_tokenizer, args.device)\n noexpdataset.load_labeled(args.labeled_data, label_to_id=args.label_to_id)\n noexpdataset.load_unlabeled(args.unlabeled_data, label_to_id=args.label_to_id)\n\n valid_dataset = ValidDataset(classifier_tokenizer, args.device)\n valid_dataset.load_init(args.test_data, label_to_id=args.label_to_id)\n test_dataset = ValidDataset(classifier_tokenizer, args.device)\n test_dataset.load_init(args.test_data, label_to_id=args.label_to_id)\n generator_dataset = GeneratorDataset(generator_tokenizer, args)\n generator_dataset.load_init(args.exp_data, label_to_id=args.label_to_id)\n classifier_dataset = ClassifierDataset(classifier_tokenizer, retriever)\n classifier_dataset.load_init(args.exp_data, label_to_id=args.label_to_id)\n\n self_training(generator, classifier, classifier_tokenizer, generator_tokenizer, noexpdataset, generator_dataset, classifier_dataset, valid_dataset, test_dataset, retriever, args)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"EST_re/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62481528","text":"\"\"\"\nRun DQN on grid world.\n\"\"\"\nimport math\nfrom os.path import join\n\nimport gym\nimport copy\n\nfrom gym_minigrid.envs.deer_diverse import DeerDiverseEnv\nfrom gym_minigrid.envs.lava import LavaEnv\nfrom gym_minigrid.envs.monsters import MonstersEnv\nfrom gym_minigrid.envs.tools import ToolsEnv\nfrom rlkit.core.logging import get_repo_dir\nfrom rlkit.samplers.data_collector.path_collector import LifetimeMdpPathCollector, MdpPathCollectorConfig\nfrom rlkit.torch.dqn.double_dqn import DoubleDQNTrainer\nfrom rlkit.torch.sac.policies import SoftmaxQPolicy\nfrom torch import nn as nn\nimport rlkit.util.hyperparameter as hyp\nfrom rlkit.exploration_strategies.base import \\\n PolicyWrappedWithExplorationStrategy\nfrom rlkit.exploration_strategies.epsilon_greedy import EpsilonGreedy, EpsilonGreedySchedule, EpsilonGreedyDecay\nfrom rlkit.policies.argmax import ArgmaxDiscretePolicy\nfrom rlkit.torch.dqn.dqn import DQNTrainer\nfrom rlkit.torch.networks import Mlp\nimport rlkit.torch.pytorch_util as ptu\nfrom rlkit.data_management.env_replay_buffer import EnvReplayBuffer\nfrom rlkit.launchers.launcher_util import setup_logger, run_experiment\nfrom rlkit.samplers.data_collector import MdpPathCollector\nfrom rlkit.torch.torch_rl_algorithm import TorchBatchRLAlgorithm, TorchLifetimeRLAlgorithm\n\n# from variants.dqn.dqn_medium_mlp_task_partial_variant import variant as algo_variant, gen_network\nfrom variants.dqn_lifetime.dqn_medium8_mlp_task_partial_variant import variant as algo_variant, gen_network#_num_obj as gen_network\n\n\ndef schedule(t):\n print(t)\n return max(1 - 5e-4 * t, 0.05)\n\n\ndef experiment(variant):\n from rlkit.envs.gym_minigrid.gym_minigrid import envs\n\n expl_env = DeerDiverseEnv(\n **variant['env_kwargs']\n )\n eval_env = DeerDiverseEnv(\n **variant['env_kwargs']\n )\n obs_dim = expl_env.observation_space.low.size\n action_dim = eval_env.action_space.n\n layer_size = variant['algo_kwargs']['layer_size']\n lifetime = variant['env_kwargs'].get('time_horizon', 0) == 0\n\n qf = gen_network(variant['algo_kwargs'], action_dim, layer_size)\n target_qf = gen_network(variant['algo_kwargs'], action_dim, layer_size)\n\n qf_criterion = nn.MSELoss()\n eval_policy = ArgmaxDiscretePolicy(qf)\n # eval_policy = SoftmaxQPolicy(qf)\n expl_policy = PolicyWrappedWithExplorationStrategy(\n EpsilonGreedyDecay(expl_env.action_space, variant['algo_kwargs']['eps_decay_rate'], 1, 0.1),\n eval_policy,\n )\n if lifetime:\n eval_policy = expl_policy\n # expl_policy = PolicyWrappedWithExplorationStrategy(\n # EpsilonGreedy(expl_env.action_space, 0.5),\n # eval_policy,\n # )\n if eval_env.time_horizon == 0:\n collector_class = LifetimeMdpPathCollector if lifetime else MdpPathCollector\n else:\n collector_class = MdpPathCollectorConfig\n eval_path_collector = collector_class(\n eval_env,\n eval_policy,\n # render=True\n )\n expl_path_collector = collector_class(\n expl_env,\n expl_policy\n )\n trainer = DoubleDQNTrainer(\n qf=qf,\n target_qf=target_qf,\n qf_criterion=qf_criterion,\n **variant['algo_kwargs']['trainer_kwargs']\n )\n replay_buffer = EnvReplayBuffer(\n variant['algo_kwargs']['replay_buffer_size'],\n expl_env\n )\n algo_class = TorchLifetimeRLAlgorithm if lifetime else TorchBatchRLAlgorithm\n algorithm = algo_class(\n trainer=trainer,\n exploration_env=expl_env,\n evaluation_env=eval_env,\n exploration_data_collector=expl_path_collector,\n evaluation_data_collector=eval_path_collector,\n replay_buffer=replay_buffer,\n **variant['algo_kwargs']['algorithm_kwargs']\n )\n algorithm.to(ptu.device)\n algorithm.train()\n\n\nif __name__ == \"__main__\":\n \"\"\"\n NOTE: Things to check for running exps:\n 1. Mode (local vs ec2)\n 2. algo_variant, env_variant, env_search_space\n 3. use_gpu \n \"\"\"\n exp_prefix = 'diverse-deer-envshaping'\n n_seeds = 1\n mode = 'ec2'\n use_gpu = False\n\n env_variant = dict(\n # sweep this\n deer_move_prob=0.5,\n # shaping params (dynamism just has med throughout, with diff deer move probs)\n deer_dists=[{'easy': 0, 'medium': 0, 'hard': 1}, {'easy': 0, 'medium': 0, 'hard': 1}],\n # shaping period param\n deer_dist_period=1,\n grid_size=10,\n agent_start_pos=None,\n health_cap=1000,\n gen_resources=True,\n fully_observed=False,\n task='make food',\n make_rtype='dense-fixed',\n fixed_reset=False,\n only_partial_obs=True,\n init_resources={\n # 'metal': 1,\n # 'wood': 1\n 'axe': 2,\n 'deer': 2\n },\n default_lifespan=0,\n fixed_expected_resources=True,\n end_on_task_completion=False,\n time_horizon=0,\n replenish_low_resources={\n 'axe': 2,\n 'deer': 2\n }\n )\n env_search_space = copy.deepcopy(env_variant)\n env_search_space = {k: [v] for k, v in env_search_space.items()}\n env_search_space.update(\n deer_move_prob=[\n 0.1, 0.2, 0.3\n ],\n deer_dists=[\n # start and end distributions\n [{'easy': 0.1, 'medium': 0.0, 'hard': 0}, {'easy': 0, 'medium': 0, 'hard': 1}],\n [{'easy': 0.75, 'medium': 0.25, 'hard': 0}, {'easy': 0, 'medium': 0, 'hard': 1}],\n [{'easy': 0.5, 'medium': 0.5, 'hard': 0}, {'easy': 0, 'medium': 0, 'hard': 1}]\n ],\n deer_dist_period=[\n # 1 is unshaped\n 1, int(1e3), int(1e4), int(1e5)\n ],\n # reward shaping\n make_rtype=[\n 'sparse', 'dense-fixed', 'waypoint', #'one-time',\n ],\n # reset / reset free\n time_horizon=[\n 0, 200\n ]\n )\n\n algo_variant = dict(\n algorithm=\"DQN\",\n version=\"diverse deer - env shaping\",\n layer_size=16,\n replay_buffer_size=int(5E5),\n eps_decay_rate=1e-5,\n algorithm_kwargs=dict(\n num_epochs=2500,\n num_eval_steps_per_epoch=6000,\n num_trains_per_train_loop=500,\n num_expl_steps_per_train_loop=500,\n min_num_steps_before_training=200,\n max_path_length=math.inf,\n batch_size=64,\n validation_envs_pkl=join(get_repo_dir(), 'examples/continual/env_shaping/diverse_deer/validation_envs/env_shaping_validation_envs_2020_02_05_06_58_29.pkl'),\n validation_rollout_length=200,\n validation_period=10,\n # store visit count array for heat map\n viz_maps=True,\n viz_gap=100\n ),\n trainer_kwargs=dict(\n discount=0.99,\n learning_rate=1E-4,\n grad_clip_val=5\n ),\n inventory_network_kwargs=dict(\n # shelf: 8 x 8\n input_size=64,\n output_size=16,\n hidden_sizes=[16, 16],\n ),\n full_img_network_kwargs=dict(\n # 5 x 5 x 8\n input_size=200,\n output_size=32,\n hidden_sizes=[64, 64]\n ),\n num_obj_network_kwargs=dict(\n # num_objs: 8\n input_size=8,\n output_size=8,\n hidden_sizes=[8]\n )\n )\n algo_search_space = copy.deepcopy(algo_variant)\n algo_search_space = {k: [v] for k, v in algo_search_space.items()}\n algo_search_space.update(\n # insert sweep params here\n )\n\n env_sweeper = hyp.DeterministicHyperparameterSweeper(\n env_search_space, default_parameters=env_variant,\n )\n algo_sweeper = hyp.DeterministicHyperparameterSweeper(\n algo_search_space, default_parameters=algo_variant,\n )\n\n for exp_id, env_vari in enumerate(env_sweeper.iterate_hyperparameters()):\n for algo_vari in algo_sweeper.iterate_hyperparameters():\n variant = {'algo_kwargs': algo_vari, 'env_kwargs': env_vari}\n for _ in range(n_seeds):\n run_experiment(\n experiment,\n exp_prefix=exp_prefix,\n mode=mode,\n variant=variant,\n use_gpu=use_gpu,\n region='us-east-2',\n num_exps_per_instance=3,\n snapshot_mode='gap',\n snapshot_gap=10,\n instance_type='c4.xlarge',\n spot_price=0.07\n )\n","sub_path":"experiments/continual/env_shaping/diverse_deer/dqn.py","file_name":"dqn.py","file_ext":"py","file_size_in_byte":8486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172115810","text":"import requests\n\n#r = requests.get(create_url(\"San Francisco\"))\n#print (r.status_code)\n\n\n\ndef main():\n forecast = Forecast(\"Austin\")\n print(forecast.one_max)\n\n# creates a request URL\ndef create_url(city, type, param):\n base = \"http://api.openweathermap.org/data/2.5/\" + type + \"?q=\"\n key = \"2c03335f9552691480c68fd9bc03d907\"\n return base + city + param + \"&appid=\" + key\n\n# current weather\nclass Weather(object):\n\n def __init__(self, city):\n\n # Request\n self.r = requests.get(create_url(city, \"weather\", \"\"))\n self.data = self.r.json()\n\n # Response\n self.desc_main = self.data[\"weather\"][0][\"main\"]\n self.temp = self.data[\"main\"][\"temp\"]\n self.temp_min = self.data[\"main\"][\"temp_min\"]\n self.temp_max = self.data[\"main\"][\"temp_max\"]\n self.humidity = self.data[\"main\"][\"humidity\"]\n self.city_name = self.data[\"name\"] + \", \" + self.data[\"sys\"][\"country\"]\n\n# 7 day weather forecast\nclass Forecast(object):\n\n def __init__(self, city):\n # Request\n self.r = requests.get(create_url(city, \"forecast/daily\", \"&mode=json&units=metric&cnt=7\"))\n self.data = self.r.json()\n\n #Response\n self.one_max = self.data[\"list\"][0][\"temp\"][\"max\"]\n self.one_min = self.data[\"list\"][0][\"temp\"][\"min\"]\n self.one_humidity = self.data[\"list\"][0][\"humidity\"]\n\n self.two_max = self.data[\"list\"][1][\"temp\"][\"max\"]\n self.two_min = self.data[\"list\"][1][\"temp\"][\"min\"]\n self.two_humidity = self.data[\"list\"][1][\"humidity\"]\n\n self.three_max = self.data[\"list\"][2][\"temp\"][\"max\"]\n self.three_min = self.data[\"list\"][2][\"temp\"][\"min\"]\n self.three_humidity = self.data[\"list\"][2][\"humidity\"]\n\n self.four_max = self.data[\"list\"][3][\"temp\"][\"max\"]\n self.four_min = self.data[\"list\"][3][\"temp\"][\"min\"]\n self.four_humidity = self.data[\"list\"][3][\"humidity\"]\n\n self.five_max = self.data[\"list\"][4][\"temp\"][\"max\"]\n self.five_min = self.data[\"list\"][4][\"temp\"][\"min\"]\n self.five_humidity = self.data[\"list\"][4][\"humidity\"]\n\n self.six_max = self.data[\"list\"][5][\"temp\"][\"max\"]\n self.six_min = self.data[\"list\"][5][\"temp\"][\"min\"]\n self.six_humidity = self.data[\"list\"][5][\"humidity\"]\n\n self.seven_max = self.data[\"list\"][6][\"temp\"][\"max\"]\n self.seven_min = self.data[\"list\"][6][\"temp\"][\"min\"]\n self.seven_humidity = self.data[\"list\"][6][\"humidity\"]\n\n\nif __name__==\"__main__\":\n main()\n","sub_path":"working/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439523127","text":"\"\"\"console module for the cli.\"\"\"\nimport subprocess as su\n\nimport click\n\nimport iocage.lib.ioc_common as ioc_common\nimport iocage.lib.ioc_json as ioc_json\nimport iocage.lib.ioc_list as ioc_list\nimport iocage.lib.ioc_start as ioc_start\n\n__rootcmd__ = True\n\n\n@click.command(name=\"console\", help=\"Login to a jail.\")\n@click.argument(\"jail\")\n@click.option(\"--force\", \"-f\", default=False, is_flag=True)\ndef cli(jail, force):\n \"\"\"\n Runs jexec to login into the specified jail. Accepts a force flag that\n will attempt to start the jail if it is not already running.\n \"\"\"\n jails, paths = ioc_list.IOCList(\"uuid\").list_datasets()\n\n _jail = {tag: uuid for (tag, uuid) in jails.items() if\n uuid.startswith(jail) or tag == jail}\n\n if len(_jail) == 1:\n tag, uuid = next(iter(_jail.items()))\n path = paths[tag]\n\n iocjson = ioc_json.IOCJson(path)\n conf = iocjson.json_load()\n login_flags = conf[\"login_flags\"].split()\n exec_fib = conf[\"exec_fib\"]\n status, _ = ioc_list.IOCList().list_get_jid(uuid)\n elif len(_jail) > 1:\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\"Multiple jails found for {jail}\"\n })\n for t, u in sorted(_jail.items()):\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\" {u} ({t})\"\n })\n exit(1)\n else:\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\"{jail} not found!\"\n })\n exit(1)\n\n if not status and not force:\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\"{uuid} ({tag}) is not running!\"\n })\n exit(1)\n\n if not status and force:\n ioc_common.logit({\n \"level\" : \"INFO\",\n \"message\": f\"{uuid} ({tag}) is not running, starting jail.\"\n })\n if conf[\"type\"] == \"jail\":\n ioc_start.IOCStart(uuid, jail, path, conf, silent=True)\n status = True\n elif conf[\"type\"] == \"basejail\":\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": \"Please run \\\"iocage migrate\\\" before trying to\"\n f\" start {uuid} ({tag})\"\n })\n exit(1)\n elif conf[\"type\"] == \"template\":\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": \"Please convert back to a jail before trying to\"\n f\" start {uuid} ({tag})\"\n })\n exit(1)\n else:\n ioc_common.logit({\n \"level\" : \"ERROR\",\n \"message\": f\"{conf['type']} is not a supported jail type.\"\n })\n exit(1)\n\n if status:\n su.Popen([\"setfib\", exec_fib, \"jexec\", f\"ioc-{uuid}\", \"login\"] +\n login_flags).communicate()\n","sub_path":"iocage/cli/console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172570735","text":"class Solution(object):\n def intToRoman(self, num):\n \"\"\"\n :type num: int\n :rtype: str\n \"\"\"\n ROM = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']\n NUM = [1000,900,500,400,100,90,50,40,10,9,5,4,1]\n res = ''\n for d,r in zip(NUM,ROM):\n res += r * (num//d)\n num %= d\n return res\n\n","sub_path":"verizon/leetcode12.py","file_name":"leetcode12.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"613819407","text":"__author__ = 'Julian Jaffe'\n\nimport unittest\nimport time, sys\nimport dbqueries\nfrom common import cspace\nfrom os import path\nfrom cspace_django_site import settings\n\n\nclass ConnectorTestCase(unittest.TestCase):\n def test_connection(self):\n self.assertEqual(dbqueries.testDB(dbqueries.cursor), \"OK\")\n\n def test_setQuery(self):\n config = cspace.getConfig(path.join(settings.BASE_PARENT_DIR, 'config'), \"toolbox\")\n institution = config.get('info','institution')\n qualifier = ''\n location = ''\n updateType = 'inventory'\n query = dbqueries.setquery('inventory', location, qualifier)\n self.assertEqual('SELECT' in query, True)\n\n def test_getlocations(self):\n elapsedtime = time.time()\n location = '1001'\n locations = dbqueries.getlocations(location, location, 3, 'bedlist')\n elapsedtime = time.time() - elapsedtime\n sys.stderr.write('all objects: %s :: %s\\n' % (location, elapsedtime))\n # self.assertEqual(len(locations), 0)\n self.assertEqual(len(locations) > 0, True)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ucjeps/apps/adhocreporting/test_dbconnector.py","file_name":"test_dbconnector.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"114013927","text":"#############jim_es_vector_search.py#############\r\n\r\nimport os\r\nimport re\r\nimport csv\r\nimport time\r\nimport pandas\r\nimport hashlib\r\nfrom os import listdir\r\nfrom os.path import isfile, join\r\n\r\nfrom elasticsearch import Elasticsearch,helpers\r\n\r\n'''\r\n\r\nbuild_vector_index(\r\n\tindex_name = \"logo\",\r\n\tvector_fields = [{\r\n\t\t\"vector_name\":\"logo_embedding\",\r\n\t\t\"vector_dim\":3\r\n\t\t}],\r\n\tes_session = es_session,\r\n\tvector_field_name = 'logo_embedding',\r\n\t)\r\n\r\n'''\r\n\r\ndef build_vector_index(\r\n\tindex_name,\r\n\tes_session,\r\n\tvector_fields = [],\r\n\tgeo_point_fields = [],\r\n\t):\r\n\tproperties = {}\r\n\tfor v in vector_fields:\r\n\t\tproperties[v['vector_name']] = {\"type\": \"dense_vector\", \"dims\": v['vector_dim']}\r\n\tfor g in geo_point_fields:\r\n\t\tproperties[g] = {\"type\": \"geo_point\"}\r\n\tmapping_str = {\r\n\t \"settings\": {\r\n\t \"number_of_shards\": 10,\r\n\t \"number_of_replicas\": 1\r\n\t },\r\n\t \"mappings\": {\r\n\t \"properties\": properties\r\n\t }\r\n\t}\r\n\tes_session.indices.delete(index = index_name, ignore=[400, 404])\r\n\tes_session.indices.create(index = index_name, body=mapping_str)\r\n\r\n\r\n'''\r\n\r\ndata_body = [\r\n\t{'document_id': \"logo1\",\"logo_embedding\":[1.1,2.2,3.3], \"company\":\"google\"},\r\n\t{'document_id': \"logo2\",\"logo_embedding\":[4.4,5.5,6.6], \"company\":None},\r\n\t{'document_id': \"logo3\",\"logo_embedding\":[-1.1,-2.2,-3.3], \"company\":\"facebook\"},\r\n\t]\r\n\r\npandas.DataFrame(data_body).to_json(\r\n\t'logo.json',\r\n\tlines = True,\r\n\torient = 'records',\r\n\t)\r\n\r\ningest_json_to_es_index(\r\n\tjson_file = 'logo.json',\r\n\tes_index = 'logo',\r\n\tes_session = es_session,\r\n\tdocument_id_feild = 'document_id',\r\n\t)\r\n\r\nhttp://localhost:9466/logo/_search?pretty=true\r\n'''\r\n\r\ndef ingest_json_to_es_index(\r\n\tjson_file,\r\n\tes_index,\r\n\tes_session,\r\n\tdocument_id_feild = 'document_id',\r\n\t):\r\n\tdata = pandas.read_json(\r\n\t\tjson_file,\r\n\t\tlines = True,\r\n\t\torient = \"records\",\r\n\t\t)\r\n\tdef insert_record_to_es(r):\r\n\t\ttry:\r\n\t\t\tr1 = r.to_dict()\r\n\t\t\tr1['_index'] = es_index\r\n\t\t\tr1['_id'] = r1[document_id_feild]\r\n\t\t\thelpers.bulk(es_session,[r1])\r\n\t\t\tr['status'] = 'success'\r\n\t\t\treturn r\r\n\t\texcept Exception as e:\r\n\t\t\tr['status'] = e\r\n\t\t\treturn r\r\n\tdata = data.apply(\r\n\t\tinsert_record_to_es, \r\n\t\taxis = 1)\r\n\treturn data\r\n\r\n\r\n'''\r\nsearch_by_vector(\r\n\tindex_name = 'logo',\r\n\tvector_field_name = 'logo_embedding',\r\n\tquery_vector = [1.0,2.2,3.3],\r\n\tes_session = es_session,\r\n\tsimilarity_measure = 'euclidean',\r\n\treturn_entity_max_number = 2,\r\n\t)\r\n'''\r\n\r\ndef search_by_vector(\r\n\tindex_name,\r\n\tvector_field_name,\r\n\tquery_vector,\r\n\tes_session,\r\n\tsimilarity_measure = 'euclidean',\r\n\treturn_entity_max_number = 1,\r\n\treturn_entity_min_score = 0.0):\r\n\tsource = \"1 / (1 + l2norm(params.query_vector, '{}'))\".format(vector_field_name)\r\n\tif similarity_measure == 'cosine':\r\n\t\tsource = \"cosineSimilarity(params.query_vector, '{}') + 1.0\".format(vector_field_name)\r\n\tvector_dim_size = len(query_vector)\r\n\tq_str ={ \r\n\t\t\"size\": vector_dim_size,\r\n\t\t\"query\": {\r\n\t \"script_score\": {\r\n\t \"query\" : {\"match_all\": {}},\r\n\t \"script\": {\r\n\t \"source\": source, \r\n\t \"params\": { \"query_vector\": query_vector}\r\n\t }\r\n\t }\r\n\t }\r\n\t}\r\n\tres = es_session.search(\r\n\t\tindex = index_name, \r\n\t\tbody = q_str,\r\n\t\t)\r\n\toutput = [r for r in res['hits']['hits'] if r['_score'] >= return_entity_min_score]\r\n\toutput = output[0:return_entity_max_number]\r\n\toutput1 = []\r\n\tfor r in output:\r\n\t\tr1 = r['_source']\r\n\t\tr1['score'] = r['_score']\r\n\t\toutput1.append(r1)\r\n\treturn output1\r\n\r\n#############jim_es_vector_search.py#############","sub_path":"jim_es_vector_search.py","file_name":"jim_es_vector_search.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250799902","text":"import sqlite3\nimport sys\nimport os\nimport datetime\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.db import transaction\nfrom django.core.files import File as DJFile\nfrom le_utils.constants import content_kinds\nfrom contentcuration import models\nfrom contentcuration.api import write_file_to_storage\nimport logging as logmodule\nlogging = logmodule.getLogger(__name__)\n\nCHANNEL_TABLE = 'content_channelmetadata'\nNODE_TABLE = 'content_contentnode'\nFILE_TABLE = 'content_file'\nTAG_TABLE = 'content_contenttag'\nNODE_TAG_TABLE = 'content_contentnode_tags'\nLICENSE_TABLE = 'content_license'\nNODE_COUNT = 0\nFILE_COUNT = 0\nTAG_COUNT = 0\n\n\nclass EarlyExit(BaseException):\n def __init__(self, message, db_path):\n self.message = message\n self.db_path = db_path\n\n\nclass Command(BaseCommand):\n\n help = 'Restores a channel based on its exported database (Usage: restore_channel [source-channel-id] [target-channel-id]'\n\n def add_arguments(self, parser):\n\n # ID of channel to read data from\n parser.add_argument('source_id', type=str)\n\n # ID of channel to write data to (can be same as source channel)\n parser.add_argument('target_id', type=str)\n\n def handle(self, *args, **options):\n try:\n # Set up variables for restoration process\n logging.info(\"\\n\\n********** STARTING CHANNEL RESTORATION **********\")\n start = datetime.datetime.now()\n source_id = options['source_id']\n target_id = options.get('target_id') or source_id\n\n # Test connection to database\n logging.info(\"Connecting to database for channel {}...\".format(source_id))\n conn = sqlite3.connect(os.path.join(settings.DB_ROOT, '{}.sqlite3'.format(source_id)))\n cursor = conn.cursor()\n\n # Start by creating channel\n logging.info(\"Creating channel...\")\n channel, root_pk = create_channel(conn, target_id)\n\n # Create nodes mapping to channel\n logging.info(\" Creating nodes...\")\n root = None\n with transaction.atomic():\n root = create_nodes(cursor, target_id)\n\n # Save tree to target tree\n channel.main_tree = root\n channel.save()\n\n # Print stats\n logging.info(\"\\n\\nChannel has been restored (time: {ms}, {node_count} nodes, {file_count} files, {tag_count} tags)\\n\".format(\n ms=datetime.datetime.now() - start,\n node_count=NODE_COUNT,\n file_count=FILE_COUNT,\n tag_count=TAG_COUNT)\n )\n logging.info(\"\\n\\n********** RESTORATION COMPLETE **********\\n\\n\")\n\n except EarlyExit as e:\n logging.warning(\"Exited early due to {message}.\".format(message=e.message))\n self.stdout.write(\"You can find your database in {path}\".format(path=e.db_path))\n\n\ndef create_channel(cursor, target_id):\n \"\"\" create_channel: Create channel at target id\n Args:\n cursor (sqlite3.Connection): connection to export database\n target_id (str): channel_id to write to\n Returns: channel model created and id of root node\n \"\"\"\n id, name, description, thumbnail, root_pk, version = cursor.execute('SELECT id, name, description, thumbnail, root_pk, version FROM {table}'.format(table=CHANNEL_TABLE)).fetchone()\n channel, is_new = models.Channel.objects.get_or_create(pk=target_id)\n channel.name = name\n channel.description = description\n channel.thumbnail = write_to_thumbnail_file(thumbnail)\n channel.version = version\n channel.save()\n logging.info(\"\\tCreated channel {} with name {}\".format(target_id, name))\n return channel, root_pk\n\n\ndef write_to_thumbnail_file(raw_thumbnail):\n \"\"\" write_to_thumbnail_file: Convert base64 thumbnail to file\n Args:\n raw_thumbnail (str): base64 encoded thumbnail\n Returns: thumbnail filename\n \"\"\"\n if raw_thumbnail and isinstance(raw_thumbnail, str) and raw_thumbnail != \"\" and 'static' not in raw_thumbnail:\n with SimpleUploadedFile('temp.png', raw_thumbnail.replace('data:image/png;base64,', '').decode('base64')) as tempf:\n filename = write_file_to_storage(tempf, check_valid=False)\n logging.info(\"\\tCreated thumbnail {}\".format(filename))\n return filename\n\n\ndef create_nodes(cursor, target_id, parent=None, indent=1):\n \"\"\" create_channel: Create channel at target id\n Args:\n cursor (sqlite3.Connection): connection to export database\n target_id (str): channel_id to write to\n parent (models.ContentNode): node's parent\n indent (int): How far to indent print statements\n Returns: newly created node\n \"\"\"\n # Read database rows that match parent\n parent_query = 'parent_id IS NULL'\n if parent:\n parent_query = \"parent_id=\\'{}\\'\".format(parent.node_id)\n\n sql_command = 'SELECT id, title, content_id, description, sort_order, '\\\n 'license_owner, author, license_id, kind FROM {table} WHERE {query};'\\\n .format(table=NODE_TABLE, query=parent_query)\n query = cursor.execute(sql_command).fetchall()\n\n # Parse through rows and create models\n for id, title, content_id, description, sort_order, license_owner, author, license_id, kind in query:\n logging.info(\"{indent} {id} ({title} - {kind})...\".format(indent=\" |\" * indent, id=id, title=title, kind=kind))\n\n # Create new node model\n node = models.ContentNode.objects.create(\n node_id=id,\n title=title,\n content_id=content_id,\n description=description,\n sort_order=sort_order,\n copyright_holder=license_owner,\n author=author,\n license=retrieve_license_name(cursor, license_id),\n kind_id=kind,\n parent=parent,\n )\n\n # Update node stat\n global NODE_COUNT\n NODE_COUNT += 1\n\n # Handle foreign key references (children, files, tags)\n if kind == content_kinds.TOPIC:\n create_nodes(cursor, target_id, parent=node, indent=indent + 1)\n else:\n create_files(cursor, node, indent=indent + 1)\n create_tags(cursor, node, target_id, indent=indent + 1)\n\n return node\n\n\ndef retrieve_license_name(cursor, license_id):\n \"\"\" retrieve_license_name: Get license based on id from exported db\n Args:\n cursor (sqlite3.Connection): connection to export database\n license_id (str): id of license on exported db\n Returns: license model matching the name\n \"\"\"\n # Handle no license being assigned\n if license_id is None or license_id == \"\":\n return None\n\n # Return license that matches name\n name = cursor.execute('SELECT license_name FROM {table} WHERE id={id}'.format(table=LICENSE_TABLE, id=license_id)).fetchone()\n return models.License.objects.get(license_name=name[0])\n\n\ndef create_files(cursor, contentnode, indent=0):\n \"\"\" create_files: Get license\n Args:\n cursor (sqlite3.Connection): connection to export database\n contentnode (models.ContentNode): node file references\n indent (int): How far to indent print statements\n Returns: None\n \"\"\"\n # Parse database for files referencing content node and make file models\n sql_command = 'SELECT checksum, extension, file_size, contentnode_id, '\\\n 'lang_id, preset FROM {table} WHERE contentnode_id=\\'{id}\\';'\\\n .format(table=FILE_TABLE, id=contentnode.node_id)\n\n query = cursor.execute(sql_command).fetchall()\n for checksum, extension, file_size, contentnode_id, lang_id, preset in query:\n filename = \"{}.{}\".format(checksum, extension)\n logging.info(\"{indent} * FILE {filename}...\".format(indent=\" |\" * indent, filename=filename))\n file_path = models.generate_file_on_disk_name(checksum, filename)\n\n try:\n # Save values to new or existing file object\n with open(file_path, 'rb') as fobj:\n file_obj = models.File.objects.create(\n file_on_disk=DJFile(fobj),\n file_format_id=extension,\n file_size=file_size,\n contentnode=contentnode,\n lang_id=lang_id,\n preset_id=preset or \"\",\n )\n\n # Update file stat\n global FILE_COUNT\n FILE_COUNT += 1\n\n except IOError as e:\n logging.warning(\"\\b FAILED (check logs for more details)\")\n sys.stderr.write(\"Restoration Process Error: Failed to save file object {}: {}\".format(filename, os.strerror(e.errno)))\n continue\n\n\ndef create_tags(cursor, contentnode, target_id, indent=0):\n \"\"\" create_tags: Create tags associated with node\n Args:\n cursor (sqlite3.Connection): connection to export database\n contentnode (models.ContentNode): node file references\n target_id (str): channel_id to write to\n indent (int): How far to indent print statements\n Returns: None\n \"\"\"\n # Parse database for files referencing content node and make file models\n sql_command = 'SELECT ct.id, ct.tag_name FROM {cnttable} cnt '\\\n 'JOIN {cttable} ct ON cnt.contenttag_id = ct.id ' \\\n 'WHERE cnt.contentnode_id=\\'{id}\\';'\\\n .format(\n cnttable=NODE_TAG_TABLE,\n cttable=TAG_TABLE,\n id=contentnode.node_id,\n )\n query = cursor.execute(sql_command).fetchall()\n\n # Build up list of tags\n tag_list = []\n for id, tag_name in query:\n logging.info(\"{indent} ** TAG {tag}...\".format(indent=\" |\" * indent, tag=tag_name))\n # Save values to new or existing tag object\n tag_obj, is_new = models.ContentTag.objects.get_or_create(\n pk=id,\n tag_name=tag_name,\n channel_id=target_id,\n )\n tag_list.append(tag_obj)\n\n # Update tag stat\n global TAG_COUNT\n TAG_COUNT += 1\n\n # Save tags to node\n contentnode.tags = tag_list\n contentnode.save()\n","sub_path":"contentcuration/contentcuration/management/commands/restore_channel.py","file_name":"restore_channel.py","file_ext":"py","file_size_in_byte":10321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"229694710","text":"x = int(input('How many people are coming to your wedding?\\n'))\n\nif x <= 50:\n price= 4000\nif x > 50 and x <= 100:\n price= 10000\nif x > 100 and x <= 200:\n price= 15000\nif x > 200:\n price= 20000\n\n\n\n# Your code above here\nprint('Your wedding will cost '+str(price)+' dollars')","sub_path":"exercises/12-How-Much-The-Wedding-Costs/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"223978688","text":"# coding: utf-8\n# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.\n\n# This script provides an example on how to move a compartment to a different compartment\n# This script will\n#\n# * create cp_source_PYSDK under tenancy\n# * create cp_target_PYSDK under tenancy\n# * move cp_source_PYSDK under cp_target_PYSDK\n\nimport oci\n\nconfig = oci.config.from_file()\nidentity = oci.identity.IdentityClient(config)\ntenancy_id = config[\"tenancy\"]\n\n# Create source compartment\ncreate_compartment_response = identity.create_compartment(\n oci.identity.models.CreateCompartmentDetails(\n compartment_id=tenancy_id,\n name='cp_source_PYSDK',\n description='compartment_source'\n )\n)\ncompartment_source_id = create_compartment_response.data.id\nprint('Created source compartment: {}'.format(create_compartment_response.data))\n\n# Create target compartment\ncreate_compartment_response = identity.create_compartment(\n oci.identity.models.CreateCompartmentDetails(\n compartment_id=tenancy_id,\n name='cp_target_PYSDK',\n description='compartment_target'\n )\n)\ncompartment_target_id = create_compartment_response.data.id\nprint('Created target compartment: {}'.format(create_compartment_response.data))\n\nmove_compartment_response = identity.move_compartment(\n compartment_source_id,\n oci.identity.models.MoveCompartmentDetails(\n target_compartment_id=compartment_target_id\n )\n)\n\nprint('Compartment moved successfully')\n","sub_path":"OCI_Python_Scripts/Examples/move_compartment_example.py","file_name":"move_compartment_example.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"652223320","text":"from ansiblelint import AnsibleLintRule\n\n\nclass TaskGetURIRetries(AnsibleLintRule):\n id = 'SHAKEY0001'\n shortdesc = 'All get_uri tasks should use the retries option'\n description = 'All get_uri tasks should use the retries option'\n tags = ['reliability']\n\n def matchtask(self, file, task):\n if task['action']['__ansible_module__'] == 'get_url':\n if 'retries' not in task:\n return True\n else:\n return False\n","sub_path":"demo/lshake.caddy/ansible-lint/TaskGetURIRetries.py","file_name":"TaskGetURIRetries.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"558665899","text":"#!usr/bin/env python3\r\n\"\"\"Create an exmaple iterator class.\"\"\"\r\n\r\n#must implement __iter__() and __next__()\r\n\r\nimport json\r\n\r\nclass ListIterator:\r\n\r\n def __init__(self, list):\r\n self.__list = list\r\n self.__index = -1\r\n\r\n ## give iterator\r\n def __iter__(self):\r\n return self\r\n\r\n def __next__(self):\r\n self.__index += 1\r\n if self.__index >= len(self.__list):\r\n raise StopIteration\r\n return(self.__list[self.__index]) #return next item in the list\r\n\r\n# create a list for testing\r\na = [1, 4, 7, 4, 7, 0, 12]\r\n\r\n#create a list of ListItertor to show how to iterate over it\r\nmyList = ListIterator(a)\r\nit = iter(myList)\r\n\r\n# if you next 1 too many times, an \"index_out_of_range\" will be thrown.\r\n# a StopIteration will be thrown now due to raise in __next__ method\r\ni = 0\r\nwhile i < len(a):\r\n print(next(it))\r\n i += 1\r\nprint('done')\r\n\r\nmyList = ListIterator(a) #reset the list iterator\r\nit = iter(myList) #reset the iterator list\r\n# the loop will iterate over the items\r\nfor i in it:\r\n print(i)\r\n \r\nprint (\"done\")\r\nprint(next(it)) # will throw exception\r\n","sub_path":"vagrant/json_tutorial/python_json_iterator_class.py","file_name":"python_json_iterator_class.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"651285498","text":"#!/usr/bin/env python3\n\nimport os\nimport subprocess\nimport produtil.setup\nimport sys\nimport logging\nimport pytest\nfrom shutil import which\n\nfrom metplus.util import met_util as util\n\n#\n# These are tests (not necessarily unit tests) for the\n# MET Point-Stat Wrapper, PointStatWrapper.py\n# NOTE: This test requires pytest, which is NOT part of the standard Python\n# library.\n# These tests require one configuration file in addition to the three\n# required METplus configuration files: point_stat_test.conf. This contains\n# the information necessary for running all the tests. Each test can be\n# customized to replace various settings if needed.\n#\n\n#\n# -----------Mandatory-----------\n# configuration and fixture to support METplus configuration files beyond\n# the metplus_data, metplus_system, and metplus_runtime conf files.\n#\n\n\n# Add a test configuration\ndef pytest_addoption(parser):\n parser.addoption(\"-c\", action=\"store\", help=\" -c \")\n\n\n# @pytest.fixture\ndef cmdopt(request):\n return request.config.getoption(\"-c\")\n\n\n# ------------------------\ndef dummy():\n assert(True)\n\ndef get_config_obj(metplus_config):\n \"\"\"! Create the configuration object that is used by all tests\"\"\"\n file_list = [\"/path/to/METplus/internal_tests/pytests/produtil\"]\n extra_configs = []\n extra_configs.append(os.path.join(os.path.dirname(__file__), 'produtil_test.conf'))\n config = metplus_config(extra_configs)\n\n return config\n\n\ndef test_getstr_ok(metplus_config):\n \"\"\"! Test that the expected string is retrieved via produtil's getstr\n method\n \"\"\"\n conf_obj = get_config_obj(metplus_config)\n str_value = conf_obj.getstr('config', 'STRING_VALUE')\n expected_str_value = \"someStringValue!#@$%\"\n assert str_value == expected_str_value\n\n\ndef test_getint_ok(metplus_config):\n \"\"\"! Test that the expected int in the produtil_test.conf file has been\n retrieved correctly.\n \"\"\"\n conf_obj = get_config_obj(metplus_config)\n expected_int_value = int(2908887)\n int_value = conf_obj.getint('config', 'INT_VALUE')\n assert int_value == expected_int_value\n\n\n\ndef test_getdir_ok(metplus_config):\n \"\"\"! Test that the directory in the produtil_test.conf file has been\n correctly retrieved.\n \"\"\"\n conf_obj = get_config_obj(metplus_config)\n expected_dir = \"/tmp/some_dir\"\n dir_retrieved = conf_obj.getdir('DIR_VALUE')\n assert dir_retrieved == expected_dir\n\n\ndef test_getdir_compound_ok(metplus_config):\n \"\"\"! Test that directories created from other directories, ie.\n BASE_DIR = /base/dir\n SPECIFIC_DIR = {BASE_DIR}/specific/dir\n\n correctly returns the directory path for SPECIFIC_DIR\n \"\"\"\n expected_specific_dir = \"/tmp/specific_place\"\n conf_obj = get_config_obj(metplus_config)\n specific_dir = conf_obj.getdir('SPECIFIC_DIR')\n assert specific_dir == expected_specific_dir\n\n\ndef test_no_value_as_string(metplus_config):\n \"\"\"! Tests that a key with no value returns an empty string.\"\"\"\n\n conf_obj = get_config_obj(metplus_config)\n expected_unassigned = ''\n unassigned = conf_obj.getstr('config', 'UNASSIGNED_VALUE')\n print(\"unassigned: \", unassigned)\n print(\"expected: \", expected_unassigned)\n assert unassigned == expected_unassigned\n\n\ndef test_no_value_as_list(metplus_config):\n \"\"\"! Tests that a key with no list of strings returns an empty list.\"\"\"\n\n conf_obj = get_config_obj(metplus_config)\n expected_unassigned = []\n unassigned = util.getlist(conf_obj.getstr('config', 'UNASSIGNED_VALUE'))\n assert unassigned == expected_unassigned\n\n\ndef test_new_lines_in_conf(metplus_config):\n \"\"\"! Test that any newlines in the configuration file are handled\n properly\n \"\"\"\n\n conf_obj = get_config_obj(metplus_config)\n expected_string = \\\n \"very long line requiring newline character to be tested 12345\\n67890 end of the line.\"\n long_line = conf_obj.getstr('config', 'NEW_LINES')\n assert long_line == expected_string\n\n\ndef test_get_exe_ok(metplus_config):\n \"\"\"! Test that executables are correctly retrieved.\"\"\"\n conf_obj = get_config_obj(metplus_config)\n expected_exe = which('wgrib2')\n executable = conf_obj.getexe('WGRIB2')\n assert executable == expected_exe\n\n\ndef test_get_bool(metplus_config):\n \"\"\"! Test that boolean values are correctly retrieved.\"\"\"\n conf_obj = get_config_obj(metplus_config)\n bool_val = conf_obj.getbool('config', 'BOOL_VALUE')\n assert bool_val is True\n\n","sub_path":"internal_tests/pytests/produtil/test_produtil.py","file_name":"test_produtil.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"196990869","text":"# topics = [\"数组\", \"滑动窗口\"]\n\n\nclass Solution:\n def equalSubstring(self, s: str, t: str, maxCost: int) -> int:\n \"\"\"\n Sliding Window\n time O(n), space O(n), n 为字符串长度\n \"\"\"\n n = len(s)\n record = [abs(ord(t[i]) - ord(s[i])) for i in range(n)]\n\n # 滑动窗口 求和小于 maxCost 的最长连续子串\n i = j = 0\n total = 0\n res = 0\n while j < n:\n total += record[j]\n\n while total > maxCost:\n res = max(res, j - i)\n total -= record[i]\n i += 1\n\n j += 1\n\n return max(res, j - i)\n","sub_path":"algorithms/[1208]尽可能使字符串相等/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"336341163","text":"# Indexing\n#\n# What are all the employees in a certain department?\n\nrecords = [\n (\"Alice\", \"Engineering\"),\n (\"Bob\", \"Sales\"),\n (\"Carol\", \"Sales\"),\n (\"Dave\", \"Engineering\"),\n (\"Erin\", \"Engineering\"),\n (\"Frank\", \"Engineering\"),\n (\"Grace\", \"Marketing\")\n]\n# build index lookup table O(n)\n# then each lookup will be O(1)\nindex = {}\n\ndef build_index():\n for r in records:\n dept = r[1]\n\n if dept not in index:\n index[dept] = []\n \n index[dept].append(r)\n\nbuild_index()\n\nwhile True:\n dept = input(\"Enter department: \")\n print(index[dept])\n\n\n\n\"\"\"\n# O(n) soliution is to loop thru everything\nfor r in records:\n if r[1] == dept:\n print(r)\n\"\"\"","sub_path":"indexing.py","file_name":"indexing.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"22156209","text":"#! /usr/bin/env python\n\n\"\"\"\n\tRecrée un fichier contenant tous les gènes ayant un fichier .nhx\n\n\tusage:\n\t\t./create_listGenesWithTree.py file_list\n\"\"\"\n\nimport utils.myTools\n\narguments = utils.myTools.checkArgs([(\"liste\", file)], [], __doc__)\n\nwith open(\"liste\") as f:\n for row in f:\n liste = row.split()\n\nwith open(\"human_genes_list_with_tree\", \"w\") as ff:\n for i in range(len(liste)):\n ff.write(liste[i].replace(\".nhx\", \"\") + \"\\n\")\n","sub_path":"create_listGenesWithTree.py","file_name":"create_listGenesWithTree.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"372844215","text":"import argparse\nimport io\n\nfrom .utils import iter_tokens_tags\n\n\ndef main(args):\n with io.open(args.output, 'w') as f:\n for tokens, tags in iter_tokens_tags(args.input):\n f.write('-DOCSTART- -X- O O\\n')\n for token, BIO_tag in zip(tokens, tags):\n f.write(f'{token} -X- _ {BIO_tag}\\n')\n f.write('\\n')\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=f'Convert Label Studio labeling results to format accepted by SpaCy lib')\n parser.add_argument(\n '-i', '--input',\n dest='input',\n help='Input directory, where labeling results are saved (e.g. \"//completions\")'\n )\n parser.add_argument(\n '-o', '--output',\n dest='output',\n help='Output file',\n default='output.conll'\n )\n main(parser.parse_args())\n","sub_path":"backend/converter/text_tagging/spacy_conll2003.py","file_name":"spacy_conll2003.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"119503423","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Author: DBQ(Du Baoqiang)\n\nimport logging,os,sys\n\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom config import settings\n\n\nlogger = logging.getLogger('FTP')\nlogger.setLevel(logging.INFO)\n\nfh = logging.FileHandler(settings.LOGDIR)\nfh.setLevel(logging.INFO)\n\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nfh.setFormatter(formatter)\n\nlogger.addHandler(fh)","sub_path":"day10/FTPServer/lib/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"279053312","text":"# Copyright (c) 2013 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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport mock\n\nfrom mistral.db import api as db_api\nfrom mistral.engine.actions import actions\nfrom mistral.engine.scalable import engine\nfrom mistral.engine import states\nfrom mistral.tests import base\n\n\nENGINE = engine.get_engine()\n\nWB_NAME = \"my_workbook\"\nCONTEXT = None # TODO(rakhmerov): Use a meaningful value.\n\n\n#TODO(rakhmerov): add more tests for errors, execution stop etc.\n\n\nclass TestScalableEngine(base.DbTestCase):\n @mock.patch.object(engine.ScalableEngine, \"_notify_task_executors\",\n mock.MagicMock(return_value=\"\"))\n @mock.patch.object(db_api, \"workbook_get\",\n mock.MagicMock(return_value={\n 'definition': base.get_resource(\"test_rest.yaml\")\n }))\n @mock.patch.object(actions.RestAction, \"run\",\n mock.MagicMock(return_value=\"result\"))\n def test_engine_one_task(self):\n execution = ENGINE.start_workflow_execution(WB_NAME, \"create-vms\",\n CONTEXT)\n\n task = db_api.tasks_get(WB_NAME, execution['id'])[0]\n\n ENGINE.convey_task_result(WB_NAME, execution['id'], task['id'],\n states.SUCCESS, None)\n\n task = db_api.tasks_get(WB_NAME, execution['id'])[0]\n execution = db_api.execution_get(WB_NAME, execution['id'])\n\n self.assertEqual(execution['state'], states.SUCCESS)\n self.assertEqual(task['state'], states.SUCCESS)\n\n @mock.patch.object(engine.ScalableEngine, \"_notify_task_executors\",\n mock.MagicMock(return_value=\"\"))\n @mock.patch.object(db_api, \"workbook_get\",\n mock.MagicMock(return_value={\n 'definition': base.get_resource(\"test_rest.yaml\")\n }))\n @mock.patch.object(actions.RestAction, \"run\",\n mock.MagicMock(return_value=\"result\"))\n def test_engine_multiple_tasks(self):\n execution = ENGINE.start_workflow_execution(WB_NAME, \"backup-vms\",\n CONTEXT)\n\n tasks = db_api.tasks_get(WB_NAME, execution['id'])\n\n ENGINE.convey_task_result(WB_NAME, execution['id'],\n tasks[0]['id'],\n states.SUCCESS, None)\n\n tasks = db_api.tasks_get(WB_NAME, execution['id'])\n\n self.assertIsNotNone(tasks)\n self.assertEqual(2, len(tasks))\n self.assertEqual(tasks[0]['state'], states.SUCCESS)\n\n # Since we mocked out executor notification we expect IDLE\n # for the second task.\n self.assertEqual(tasks[1]['state'], states.IDLE)\n self.assertEqual(states.RUNNING,\n ENGINE.get_workflow_execution_state(WB_NAME,\n execution['id']))\n\n ENGINE.convey_task_result(WB_NAME, execution['id'],\n tasks[1]['id'],\n states.SUCCESS, None)\n\n tasks = db_api.tasks_get(WB_NAME, execution['id'])\n execution = db_api.execution_get(WB_NAME, execution['id'])\n\n self.assertEqual(execution['state'], states.SUCCESS)\n self.assertEqual(tasks[0]['state'], states.SUCCESS)\n self.assertEqual(tasks[1]['state'], states.SUCCESS)\n self.assertEqual(states.SUCCESS,\n ENGINE.get_workflow_execution_state(WB_NAME,\n execution['id']))\n","sub_path":"mistral/tests/unit/engine/scalable/test_engine.py","file_name":"test_engine.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"522748959","text":"import pandas as pd\nimport numpy as np\nimport sys\nimport matplotlib\nmatplotlib.rcParams['pdf.fonttype'] = 42\nmatplotlib.rcParams['ps.fonttype'] = 42\n\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import scale,MinMaxScaler\n\n\ndataname = str(sys.argv[1])\n\n\nscvi = pd.read_table('../' + dataname + '/scvi.res.txt',delim_whitespace=True)\nothers = pd.read_table('../' + dataname + '/others.res.txt',delim_whitespace=True)\nstats = pd.concat([scvi,others])\nmodel_types = stats['model_type']\nstat_names = np.asarray(list(scvi.columns)[1:])\nmodel_types = np.asarray(model_types)\n\nres=[]\nfor x in np.unique(model_types):\n stat = np.mean(np.asarray(stats[model_types==x])[:, 1:], axis=0)\n res.append(stat)\n\nmodel_types = np.unique(model_types)\nres = np.asarray(res)\n\n\nsorted_res=[]\n# model_order = ['vae','scanvi0', 'scanvi', 'scanvi1', 'scanvi2',\n# 'scmap1', 'scmap2', 'readSeurat', 'Combat', 'MNN']\n# model_order = ['vae','scanvi0', 'scanvi', 'scanvi1', 'scanvi2','readSeurat', 'Combat', 'MNN']\n# model_order = ['vae', 'scanvi', 'scanvi1', 'scanvi2','scmap', 'readSeurat', 'Combat', 'MNN']\n\nmodel_order = ['vae', 'scanvi', 'scanvi1', 'scanvi2','readSeurat', 'Combat', 'MNN']\nfor x in model_order:\n sorted_res.append(res[model_types==x,:])\n\nsorted_res = np.asarray(sorted_res)\nsorted_res = sorted_res.squeeze()\n\nscmap = res[model_types=='scmap',:][0]\n# tabs = ['knn_asw','knn_uca','knn_wuca','kmeans_uca','kmeans_wuca','BE','jaccard_score']\n# tabs = ['knn_asw','knn_uca','p_knn_uca','p1_knn_uca','p2_knn_uca','BE','jaccard_score','classifier_acc']\n# tabs = ['kmeans_asw','kmeans_uca','p_kmeans_uca','p1_kmeans_uca','p2_kmeans_uca','BE','jaccard_score','classifier_acc']\ntabs = ['knn_asw','knn_uca','p_knn_uca','p1_knn_uca','p2_knn_uca','BE','jaccard_score','classifier_acc']\n\nfiltered_res = [sorted_res[:, stat_names==x] for x in tabs]\nfiltered_res = np.concatenate(filtered_res,axis=1)\n\nfiltered_res = np.concatenate([filtered_res,np.repeat(-1,len(tabs)).reshape(1,len(tabs))])\nfiltered_res[len(model_order)][3] = scmap[13]\nfiltered_res[len(model_order)][4] = scmap[18]\n\nfiltered_names = np.concatenate(np.asarray( [stat_names[[y in x for x in stat_names]] for y in tabs]))\nfiltered_names[0]='asw'\nrm_values = (filtered_res==-1)\n\n\n\ndef impute(x):\n avg = np.mean(x[x != -1])\n x[x == -1] = avg\n return x\n\n\nfiltered_res = np.apply_along_axis(impute,0,filtered_res)\n\n\n\ndef Heatmap(value_matrix, cololor_matrix, rownames,colnames,title,filename):\n fig, ax = plt.subplots(figsize=(7,7))\n # We want to show all ticks...\n im = ax.imshow(cololor_matrix,aspect='auto')\n ax.set_xticks(np.arange(len(rownames)))\n ax.set_yticks(np.arange(len(colnames)))\n # ... and label them with the respective list entries\n ax.set_xticklabels(rownames)\n ax.set_yticklabels(colnames)\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n # Loop over data dimensions and create text annotations.\n for i in range(len(colnames)):\n for j in range(len(rownames)):\n text = ax.text(j, i, \"{:.2f}\".format(value_matrix[i, j]),\n ha=\"center\", va=\"center\", color=\"w\")\n ax.set_title(title)\n fig.tight_layout()\n plt.savefig(filename, transparent=True)\n\n\nfiltered_res = np.asarray(filtered_res).astype('float')\nscaler = MinMaxScaler()\nscaled_res = scaler.fit_transform(filtered_res)\nscaled_res[rm_values]=np.nan\nfiltered_res[rm_values]=np.nan\nHeatmap(filtered_res,scaled_res,tabs,model_order+['scmap'],dataname,'../'+ dataname + '/'+dataname + '.heatmap.pdf')\n","sub_path":"Additional_Scripts/evaluation_heatmap.py","file_name":"evaluation_heatmap.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"554895198","text":"#!/usr/bin/env python3\nfrom os import listdir\nfrom os.path import isfile, join\nimport os, json\n\nfrom . node import Node\nfrom . strip import Strip\nfrom . plug import Plug\n\nnodes = {}\nstrips = {}\nplugs = {}\n\ndef destroyObjects():\n nodes = {}\n strips = {}\n plugs = {}\n\ndef load_definition_file(file):\n with open(file, 'r') as readFile:\n json_data = json.load(readFile)\n\n for node_data in json_data[\"nodes\"]:\n nodes[node_data[\"id\"]] = Node(node_data)\n\n for strip_data in json_data[\"strips\"]:\n strip = strips[strip_data[\"id\"]] = Strip(strip_data)\n\n node_id = strip.getNodeId()\n nodes[node_id].addStrip(strip)\n\n\n for plug_data in json_data[\"plugs\"]:\n plugs[plug_data[\"id\"]] = Plug(plug_data)\n\n for plug_name in plugs:\n strip_name = plugs[plug_name].getStripId()\n strips[strip_name].addPlug(plugs[plug_name])\n\n\n\ndef get_plug_id_by_adress(plug_address, strip_address, node_address):\n #print(plug,strip,node)\n for plug_id in plugs:\n plug = plugs[plug_id]\n plug_strip = strips[plug.getStripId()]\n plug_node = nodes[plug_strip.getNodeId()]\n if plug.getAddress() == plug_address \\\n and plug_strip.getAddress() == strip_address \\\n and plug_node.getAddress() == node_address:\n return plug.getId()\n return False\n\ndef get_strip_id_by_adress(strip, node):\n for s in strips:\n sid = strips[s].getId()\n nid = nodes[strips[s].getNodeId()].getId()\n if sid == strip and nid == node:\n return s\n return False\n\ndef get_strip_address_by_id(strip_id):\n return strips[strip_id].getAddress()\n\ndef get_node_address_by_id(node_id):\n return nodes[node_id].getAddress()\n\ndef get_plug_adress_by_id(id):\n plug = plugs[id]\n node_id = strips[plug.getStripId()].getNodeId()\n return {\n \"nodeAddress\": get_node_address_by_id(node_id),\n \"stripAddress\": get_strip_address_by_id(plug.getStripId()),\n \"plugAddress\": plug.getAddress()\n }\n\ndef cleanUpObjects():\n strips.clear()\n nodes.clear()\n plugs.clear()\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"12016705","text":"import json \r\nimport os\r\n'''\r\n=====================================================\r\n说明:遍历一个文件夹里的所有文件,生成Json\r\n\t\t\tversion: 1.0\r\n author: XiaoTian\r\n date: 2014/9/9\r\n\t\t\t特点:只有文件,没有路径...\r\n=====================================================\r\n'''\r\n\r\n'''\r\n生成的结果预览:\r\n{\r\n \"Resources\":[\r\n {\r\n \"fonts\":[\r\n \"arial.ttf\",\r\n \"font-ms-export.fnt\",\r\n \"font-ms-export.png\",\r\n \"Marker Felt.ttf\"\r\n ]\r\n },\r\n {\r\n \"picture\":[\r\n \"DH_cat.ExportJson\",\r\n \"DH_cat0.plist\",\r\n \"DH_cat0.png\",\r\n \"DH_dog.ExportJson\",\r\n \"DH_dog0.plist\",\r\n \"DH_dog0.png\",\r\n \"DH_ji.ExportJson\",\r\n \"DH_ji0.plist\",\r\n ]\r\n },\r\n {\r\n \"sound\":[\r\n {\r\n \"123\":[\r\n \"spring.wav\"\r\n ]\r\n },\r\n \"backmusic.mp3\",\r\n \"button.wav\",\r\n \"cat.wav\",\r\n \"chicken.wav\",\r\n \"claps1.mp3\",\r\n ]\r\n }\r\n ]\r\n}\r\n\r\n'''\r\n\r\n'''\r\n=====================================================\r\n 函数定义区\r\n 以后要集成到 一个库里,好调用\r\n=====================================================\r\n'''\r\n\r\n'''迭代生成目录树,用dict保存'''\r\ndef createDict(nowpath,root):\r\n FolderName = getFolderName(nowpath)\r\n FileList = []\r\n pathList = os.listdir(nowpath)\r\n for i, item in enumerate(pathList):\r\n dirpath = os.path.join(nowpath, item)\r\n if isDir(dirpath): #Folder\r\n rootChild = {}\r\n createDict(dirpath,rootChild)\r\n FileList.append(rootChild)\r\n else: #File\r\n FileList.append(item)\r\n root[FolderName] = FileList \r\n\r\n'''判断是否为目录'''\r\ndef isDir(path):\r\n if os.path.isdir(path):\r\n return True\r\n return False\r\n\r\n\r\n'''返回json格式数据'''\r\ndef getJson(root):\r\n return json.dumps(root)\r\n\r\n'''返回 当前程序运行路径'''\r\ndef getRunPath():\r\n return os.getcwd()\r\n\r\n'''返回一个路径的文件名,如果是er[1],返回的就是 目录名'''\r\ndef getFolderName(path):\r\n er = os.path.split(path)\r\n return er[1]\r\n\r\n''' ====================================================='''\r\n\r\n\r\nFolderName = \"Resources\"\r\npath = os.path.join(getRunPath(), FolderName)\r\n\r\n'''创建字典-dict'''\r\nroot = {}\r\n\r\n'''创建列表-list'''\r\n#root = []\r\n\r\n\r\ncreateDict(path,root)\r\nfjson = getJson(root)\r\nfp = open(\"FlieNameJson.json\",'w')\r\nfp.write(str(fjson))\r\nfp.close()\r\n\r\n\r\n\r\n'''迭代生成目录树,用dict保存\r\ndef createDict(nowpath,root):\r\n pathList = os.listdir(nowpath)\r\n for i, item in enumerate(pathList):\r\n dirpath = os.path.join(nowpath, item)\r\n if isDir(dirpath):\r\n root[item] = {}\r\n createDict(dirpath,root[item])\r\n else:\r\n root[item] = item\r\n'''\r\n\r\n\r\n","sub_path":"Python2/getFlieName2Json/getFlieNameJson-v1.0.py","file_name":"getFlieNameJson-v1.0.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"242158069","text":"\nimport torch\nfrom flask import Flask, jsonify, url_for, render_template, request, redirect, send_from_directory\nfrom werkzeug.utils import secure_filename\nimport ssl\nfrom PIL import Image\nfrom PIL.ExifTags import TAGS,GPSTAGS\n#from GPSPhoto import gpsphoto\n#import io, os, requests\n\napp = Flask(__name__)\n\n\n\nmodel = torch.hub.load('ultralytics/yolov5', 'custom', path = './static/models/best.pt') # default\nmodel.eval()\nmodel.conf = 0.25 # confidence threshold (0-1)\nmodel.iou = 0.45 # NMS IoU threshold (0-1)\n\n\n# nohup python3 -u app.py &\n#tail -f nohup.out\n#종료 lsof -i :5550\n\ndef get_prediction(img_bytes):\n # Inference\n results = model(img_bytes, size=640) # includes NMS\n PATH = 'static/results/'\n results.save(PATH)\n return results\n\nobject_list = list()\n\ndef results_img(results):\n object_list.clear()\n global msg\n print(results.names)\n pred = results.pred\n for i in pred[0]:\n #print(int(i[-1]))\n #print(results.names[int(i[-1])])\n objects = results.names[int(i[-1])]\n object_list.append(objects)\n #detected = object_list\n #detected = copy.deepcopy(object_list)\n \n # if(objects != 'electric_scooter'):\n # msg = '주차하시면안되용!'\n # else:\n # msg = '주차하셔도 좋은 장소 입니다.'\n # return msg\n\n if(any('electric_scooter' in i for i in object_list) != True):\n return '킥보드가 검출되지 않았습니다. 재촬영 해주세요!'\n\n output = any('brailleblock' in i or 'crosswalk' in i or 'fireplug' in i for i in object_list)\n print(output)\n\n if output:\n return \"주차 불가 구역입니다.\" # why? \n else:\n return \"주차 가능한 장소입니다.\"\n\n#print(results.names[int(results.pred[0][0][-1])])\n\n@app.route('/upload')\ndef render_file():\n return render_template('upload.html')\n\n@app.route('/fileUpload', methods = ['GET','POST'])\ndef upload_file():\n global check_msg\n if request.method == 'POST':\n if 'file' not in request.files:\n return redirect(request.url)\n f = request.files['file']\n #저장할 경로 + 파일명\n f.save('/home/dkjh/datacampus/electricscooter/static/photos/' + secure_filename(f.filename)) #file save path to ./static \n print(secure_filename(f.filename))\n \n image = Image.open(request.files['file'].stream)\n #img_bytes = file.read()\n results = get_prediction(image)\n \n #image_names = os.listdir(img_path)\n \n #data = gpsphoto.getGPSData('/home/dkjh/datacampus/electricscooter/static/photos/' + secure_filename(f.filename))\n #print(data)\n #print(data['Latitude'], data['Longitude'])\n #geocode = data['Latitude'], data['Longitude']\n #img_path = '/home/dkjh/datacampus/electricscooter/runs/detect/exp/image0.jpg'\n\n check_msg = results_img(results)\n #return render_template('index.html', geocode = geocode, check = check_msg)\n return render_template('index.html', check = check_msg, obj = object_list)\n\nif __name__ == '__main__':\n ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)\n ssl_context.load_cert_chain(certfile='/usr/local/ssl/server.crt', keyfile='/usr/local/ssl/server.key', password='bluesea34')\n app.run(host='0.0.0.0', port='5550', debug=True, ssl_context=ssl_context)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"499432538","text":"import pandas as pd\nfrom sklearn.cluster import estimate_bandwidth, MeanShift\nfrom sklearn.metrics import silhouette_score, calinski_harabasz_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import normalize\n\nX = pd.read_csv('triple.csv')\nprint(X)\n\nscaler = StandardScaler()\nX_scaled = scaler.fit_transform(X)\n\nX_normalized = normalize(X_scaled)\nX_normalized = pd.DataFrame(X_normalized)\n'''\npca = PCA(n_components=3)\nX_principal = pca.fit_transform(X_normalized)\nX_principal = pd.DataFrame(X_principal)\nX_principal.columns = ['P1', 'P2','P3']\nprint(X_principal.head())\n'''\nX_principal = X_normalized\nX_principal.columns = ['P1', 'P2', 'P3']\n# The following bandwidth can be automatically detected using\nbandwidth = estimate_bandwidth(X_principal, quantile=0.2, n_samples=500)\n\nms = MeanShift(bandwidth=bandwidth, bin_seeding=True)\nms.fit(X_principal)\nlabels = ms.labels_\ncluster_centers = ms.cluster_centers_\n\nlabels_unique = pd.np.unique(labels)\nn_clusters_ = len(labels_unique)\n\nprint(\"number of estimated clusters : %d\" % n_clusters_)\n\nprint('Mean-shift')\nprint(ms.bandwidth)\nprint('轮廓系数:'+str(silhouette_score(X_principal,labels)))\nprint('Calinski-Harabaz Index:'+str(calinski_harabasz_score(X_principal, labels)))\n","sub_path":"data/早期做的/网络/网络/mean-shift.py","file_name":"mean-shift.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"238600305","text":"\n####################################################################################\n# Please consider trying a few more times before referring to this code. \n# Code might be incorrect - TLE / Wrong Answer (especially filenames with _1 , _2)\n# Pedagogical > Pythonic\n####################################################################################\n\n\nI = lambda : map(int, input().split())\nn, q = I()\na = list(I())\n\nif n & (n - 1) != 0:\n # append values till it becomes power of 2\n p = len(bin(n)) - 2\n a += [max(a)] * (2**p - n)\n n = 2 ** p\n\n# build segment tree\nseg = [0] * n + a\n\ndef update(k, x):\n seg[k + n - 1] = x\n p = (k + n - 1) // 2\n while (p > 0):\n seg[p] = min(seg[2 * p], seg[2 * p + 1])\n p = p // 2\n\n# build\nfor i in range(n - 1, 0, -1): \n seg[i] = min(seg[i * 2], seg[i * 2 + 1])\n\ndef range_min(x, y):\n x += n - 1 \n y += n - 1\n\n min_val = seg[x] # just an init\n\n while (x <= y):\n if x % 2 == 1:\n min_val = min(min_val, seg[x])\n x += 1\n if y % 2 == 0:\n min_val = min(min_val, seg[y])\n y -= 1\n\n x = x // 2\n y = y // 2\n\n return min_val\n\n# print(seg)\n\nfor _ in range(q):\n # k, x, y = I()\n # if k == 1:\n # update(x, y)\n # else:\n # print(range_min(x, y))\n\n x, y = I()\n print(range_min(x, y))\n\n\n# I once again ask you to try a few more times before referring here\n","sub_path":"Python_Code/Range_Minimum_Queries_I.py","file_name":"Range_Minimum_Queries_I.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"278695476","text":"#!/usr/bin/env python\nimport rospy\nfrom std_msgs.msg import String\nfrom geometry_msgs.msg import Twist, Vector3\nfrom sensor_msgs.msg import LaserScan\nimport math\n\ny_total = 0\nx_total = 0\n\ndef scan_received(msg, pub):\n\tglobal y_total \n\tglobal x_total\n\ty_total = 0\n\tx_total = 0\n\tfor i in range(360):\n\t\tif msg.ranges[i] > 0 and msg.ranges[i] < 2: #valid range\n\t\t\ty_total = y_total + math.cos(i)*(2-msg.ranges[i]) # negative values go backward\n\t\t\tx_total = x_total + math.sin(i)*(2-msg.ranges[i]) # negative values turns right\t\t\t\t\n\t\ndef approach_wall():\n\tpub = rospy.Publisher('cmd_vel', Twist, queue_size=10)\n\tsub = rospy.Subscriber('scan', LaserScan, scan_received, pub)\n\trospy.init_node('teleop', anonymous=True)\n\tr = rospy.Rate(10) # 10hz\n\t\n\twhile not rospy.is_shutdown():\n\t\tlinear = .1 + -(.2*y_total)\n\t\tang = .2*x_total\n\t\tvelocity_msg = Twist(Vector3(linear, 0.0, 0.0), Vector3(0.0, 0.0, ang))\n\t\tpub.publish(velocity_msg)\n\t\tr.sleep()\n\t\t#print \"linear: \", linear, \" ang: \", ang\n \nif __name__ == '__main__':\n\ttry:\n\t\tapproach_wall()\n\texcept rospy.ROSInterruptException: pass\n\n\n","sub_path":"src/warmup_project/obstacle.py","file_name":"obstacle.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117378492","text":"from django.shortcuts import render\n\n# Create your views here.\n\"\"\"\nビューを作成します。ここが今回のポイントです。plotly.pyで描画したデータをHTMLに出力してテンプレートに渡します。今回は TemplateView を利用します(❶)。\n\nplotly.pyには figure と呼ばれる描画領域を管理するオブジェクトがあり、このオブジェクトからHTML上にグラフを描画したり、Jupyter上にグラフを描画できます。今回は紹介していませんが、 Plotly Express についても同様です。\n\n度々の宣伝ですが、plotly.py(Plotly Express)ついても共著 Python インタラクティブ・データビジュアライゼーション入門 ―Plotly/Dashによるデータ可視化とWebアプリ構築― にて詳しく解説しています。\n\nfigure オブジェクトをHTMLに出力するには to_html メソッドを実行し���す(❷)。plotly.pyは plotly.js が元になったラッパーで、HTMLにはJavaScriptが含まれますが、後述するCDNを利用するため、引数 include_plotlyjs を False にしてJavaScript部分以外を出力します。\n\nplotly.pyのグラフがHTML化できたので、これを TemplateView に追加します(❸)。\n\"\"\"\n\nfrom django.views.generic import TemplateView # ❶\nimport plotly.graph_objects as go\n\n\ndef line_charts():\n fig = go.Figure(\n go.Scatter(x=[1, 2, 3], y=[3, 5, 2]), layout=go.Layout(width=400, height=400)\n )\n return fig.to_html(include_plotlyjs=False) # ❷\n\n\nclass LineChartsView(TemplateView): # ❶\n template_name = \"plot.html\"\n\n def get_context_data(self, **kwargs):\n context = super(LineChartsView, self).get_context_data(**kwargs)\n context[\"plot\"] = line_charts() # ❸\n return context","sub_path":"04_playground/43_django_plotly/test02/mysite/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"311708236","text":"name = input('Как твое имя? : ')\r\nprint(f'Привет {name}, а мое Григорий.')\r\n\r\nage = int(input('А сколько тебе лет? : '))\r\nmy_age = 36\r\n\r\nif age == my_age:\r\n print('Мы ровестники!')\r\nelif age > my_age:\r\n print(f'{name} ты старше меня на {age - my_age} лет.')\r\nelse:\r\n print(f'{name} ты младше меня на {my_age - age} лет.')\r\n\r\nresult = input('Надеюсь я понял задание и сделал все верно? : ')\r\nif result == [\"Да\", \"да\", \"Yes\", \"yes\"]:\r\n print(f'{name} отлично, тогда я перехожу к следующему!')\r\nelse:\r\n print(f'{name} жаль, но я обещаю стараться!)))')\r\n","sub_path":"task_1.py","file_name":"task_1.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"383583466","text":"##\n## Programación en Python\n## ===========================================================================\n##\n## Para el archivo `data.csv`, genera una lista de tuplas que asocien las \n## columnas 0 y 1. Cada tupla contiene un valor posible de la columna 2 y una\n## lista con todas las letras asociadas (columna 1) a dicho valor de la \n## columna 2.\n##\n## Rta/\n## ('0', ['C'])\n## ('1', ['E', 'B', 'D', 'A', 'A', 'E'])\n## ('2', ['A', 'E', 'D'])\n## ('3', ['A', 'B', 'D', 'E', 'E'])\n## ('4', ['E', 'B'])\n## ('5', ['B', 'C', 'D', 'D', 'E', 'E', 'E'])\n## ('6', ['C', 'E', 'A', 'B'])\n## ('7', ['A', 'C', 'E', 'D'])\n## ('8', ['E', 'E', 'A', 'B'])\n## ('9', ['A', 'B', 'E', 'C'])\n##\n## >>> Escriba su codigo a partir de este punto <<<\n##\nArchivo= open (\"data.csv\",\"r\")\nArchivo2=[y.strip() for y in Archivo]\nArchivo2=[r.split('\\t') for r in Archivo2]\nValU1=[]\nfor i in Archivo2:\n encontrado=0\n for r in ValU1:\n if r==i[1]:\n encontrado=1\n if encontrado==0:\n ValU1.append(i[1])\nfor i in sorted(ValU1):\n Letras=[]\n for r in Archivo2:\n if i==r[1]:\n Letras.append(r[0])\n print((i,Letras))\n","sub_path":"03-python=1/q07=1/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"519367249","text":"class foo:\n def __init__(self,name,age):\n self.name=name\n self.age=age\n def detail(self):\n avi = \"姓名:{0};\\t年龄:{1};\\t\".\\\n format(self.name, self.age)\n print(avi)\nobj=foo('python3',99)\nobj.detail()","sub_path":"aid1807习题总结/2/k5.py","file_name":"k5.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"87986712","text":"from django.shortcuts import render, redirect\nfrom service.models import Service, City, ServiceType, ServiceCharge, BookAppointment, PhoneOTP, Career, Contact, CallbackRequest\nfrom math import ceil\nfrom django.forms.models import model_to_dict\n\nfrom django.db.models import Q\nfrom django.conf import settings\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\nfrom django.contrib import messages\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.urls import reverse\nimport http.client\n\nimport json\nimport requests\nimport ast\nimport random\n\nconn = http.client.HTTPConnection(\"2factor.in\")\napi_key = \"aac35574-3852-11eb-83d4-0200cd936042\"\ntemplate_name = \"A2Zhomeservice\"\n\n\n# Create your views here.\ndef index(request):\n all_city = City.objects.all()\n all_services= Service.objects.all()\n n = len(all_services)\n nSlides= n//4 + ceil((n/4) - (n//4))\n allservices=[[all_services, range(1, len(all_services)), nSlides],[all_services, range(1, len(all_services)), nSlides]]\n params={'cities':all_city,'range': range(nSlides), 'no_of_slides':nSlides,'allservices':allservices, 'services':all_services}\n return render(request,\"index.html\", params)\n\n\ndef list_service(request):\n list_services= Service.objects.all()\n n = len(list_services)\n query = request.GET.get(\"search\")\n if query:\n list_services = list_services.filter(\n Q(service_name__icontains=query) |\n Q(city__icontains=query))\n nSlides= n//4 + ceil((n/4) - (n//4))\n params={'range': range(nSlides), 'no_of_slides':nSlides,'services':list_services, }\n return render(request,'list_service.html', params)\n\ndef service_detail(request):\n if request.method ==\"POST\":\n city_id =request.POST['city']\n service_name =request.POST['service']\n # service = Service.objects.get(multiple_city=city_id,service_name=service_name)\n # return render(request, 'service_detail.html', {'service':service})\n service_detail = Service.objects.get(service_name = service_name)\n service_type = ServiceType.objects.filter(service_name = service_detail.id)\n ser_type = []\n for stype in service_type:\n ser_type.append(stype.service_type)\n serv_list = []\n dic_obj = {}\n for charge in service_type:\n service_name = charge.service_type\n service_charge= ServiceCharge.objects.filter(service_charge_name_id=charge.id)\n dic_obj[service_name] = service_charge\n serv_list.append(dic_obj)\n service_charge=[]\n for i in range(len(serv_list)):\n if serv_list[i] not in serv_list[i+1:]:\n service_charge.append(serv_list[i])\n return render(request, 'service.html', {'service_detail':service_detail,'service_type':service_type,'service_charge':service_charge,'ser_type':ser_type})\n\n\ndef service(request, name):\n service_detail = Service.objects.get(service_name = name)\n service_type = ServiceType.objects.filter(service_name = service_detail.id)\n ser_type = []\n for stype in service_type:\n ser_type.append(stype.service_type)\n serv_list = []\n dic_obj = {}\n for charge in service_type:\n service_name = charge.service_type\n service_charge= ServiceCharge.objects.filter(service_charge_name_id=charge.id)\n dic_obj[service_name] = service_charge\n serv_list.append(dic_obj)\n service_charge=[]\n for i in range(len(serv_list)):\n if serv_list[i] not in serv_list[i+1:]:\n service_charge.append(serv_list[i])\n return render(request, 'service.html', {'service_detail':service_detail,'service_type':service_type,'service_charge':service_charge,'ser_type':ser_type})\n\n\ndef booking_confirm(request):\n return render(request,'confirm_booking.html', )\n\ndef contact(request):\n return render(request,'contact.html', )\n\ndef about(request):\n return render(request,'about.html', )\n\ndef career(request):\n return render(request,'career.html', )\n\ndef success(request):\n return render(request,'success.html', )\n\n\ndef mobile_otp_send(request, service_name):\n if request.method == 'POST':\n phone_number =request.POST.get('mobile')\n appointment_date = request.POST.get('date')\n requirement = request.POST.get('requirement')\n\n if phone_number:\n phone = str(phone_number)\n otp = send_otp(phone)\n if otp:\n old = PhoneOTP.objects.filter(phone__iexact = phone)\n if old.exists():\n old = old.first()\n count = old.count\n if count > 5:\n messages.error(request, \"Sending otp error. Limit Exceeded. Please Contact Customer support.\")\n return redirect('index.html')\n\n old.count = count +1\n old.save()\n url=f\"https://2factor.in/API/V1/{api_key}/SMS/{phone_number}/{otp}/{template_name}\"\n conn.request(\"GET\", url)\n res = conn.getresponse()\n data = res.read()\n data=data.decode(\"utf-8\")\n data=ast.literal_eval(data)\n if data[\"Status\"] == 'Success':\n old.otp_session_id = data[\"Details\"]\n old.save()\n print('In validate phone :'+old.otp_session_id)\n messages.success(request, \"OTP sent successfully on your mobile.\")\n return render(request, 'confirm_booking.html',{'requirement':requirement,'phone_number':phone_number,'appointment_date':appointment_date})\n else:\n messages.error(request, \"Sending otp Failed.\")\n return HttpResponseRedirect('/')\n else:\n obj=PhoneOTP.objects.create(\n phone=phone_number,\n otp = otp,\n )\n url=f\"https://2factor.in/API/V1/{api_key}/SMS/{phone_number}/{otp}/{template_name}\"\n conn.request(\"GET\", url)\n res = conn.getresponse()\n data = res.read()\n data=data.decode(\"utf-8\")\n data=ast.literal_eval(data)\n\n if data[\"Status\"] == 'Success':\n obj.otp_session_id = data[\"Details\"]\n obj.save()\n print('In validate phone :'+obj.otp_session_id)\n messages.success(request, \"OTP sent successfully on your mobile.\")\n return render(request, 'confirm_booking.html', {'requirement':requirement,'phone_number':phone_number,'appointment_date':appointment_date} )\n\n else:\n messages.error(request, \"Sending otp Failed.\")\n return redirect('')\n else:\n messages.error(request, \"Sending otp error.\")\n return redirect('')\n else:\n messages.error(request, \"Phone number is not provided.\")\n return HttpResponseRedirect('/')\n return HttpResponseRedirect('/')\n\n\ndef send_otp(phone):\n if phone:\n key = random.randint(999,9999)\n print(key)\n return key\n else:\n return False\n\ndef validate(request, *args, **kwargs):\n if request.method == 'POST':\n name = request.POST.get('name', False)\n email = request.POST.get('email', False)\n address = request.POST.get('address', False)\n landmark = request.POST.get('landmark', False)\n city = request.POST.get('city', False)\n appointment_date = request.POST.get('appointment_date', False)\n print(appointment_date)\n otp_sent = request.POST.get('otp', False)\n phone = request.POST.get('phone_number', False)\n description = request.POST.get('notes', False)\n print(description)\n if otp_sent:\n old = PhoneOTP.objects.filter(phone__iexact = phone)\n if old.exists():\n old = old.first()\n otp_session_id = old.otp_session_id\n validate_otp_url = f\"https://2factor.in/API/V1/{api_key}/SMS/VERIFY/{otp_session_id}/{otp_sent}\"\n\n conn.request(\"GET\", validate_otp_url)\n res = conn.getresponse()\n data = res.read()\n print(data.decode(\"utf-8\"))\n data=data.decode(\"utf-8\")\n data=ast.literal_eval(data)\n if data[\"Status\"] == 'Success':\n old.validated = True\n old.save()\n booking_obj=BookAppointment.objects.create(\n client_name=name,\n mobile = phone,\n email = email,\n address = address,\n landmark = landmark,\n appointment_date = appointment_date,\n description = description\n )\n messages.success(request, \"OTP MATCHED. Your booking order is confirmed.\")\n return render(request, 'success.html')\n\n else:\n messages.error(request, \"OTP Not MATCHED. Enter valid otp.\")\n return redirect('booking_confirm')\n\n else:\n messages.error(request, \"First Proceed via sending otp request.\")\n return redirect('booking_confirm')\n\n else:\n messages.error(request, \"Please provide otp for Validation.\")\n return redirect('booking_confirm')\n return render(request, 'confirm_booking.html')\n\n\ndef create_contact_us(request):\n if request.method == 'POST':\n phone_number =request.POST.get('mobile')\n name = request.POST.get('name')\n email =request.POST.get('email')\n subject = request.POST.get('subject')\n message = request.POST.get('message')\n try:\n contact_obj = Contact.objects.create(\n phone=phone_number,\n name = name,\n body = message,\n email=email,\n service_type=subject\n )\n messages.success(request, \"Message sent successfully.\")\n return HttpResponseRedirect('/')\n except:\n messages.error(request, \"Failed to send message.\")\n return render(request, 'contact.html')\n\n\ndef create_career(request):\n if request.method == 'POST':\n phone_number =request.POST.get('mobile')\n name = request.POST.get('name')\n message = request.POST.get('message')\n try:\n career_obj = Career.objects.create(\n mobile=phone_number,\n name = name,\n message = message\n )\n messages.success(request, \"Message sent successfully.\")\n return HttpResponseRedirect('/')\n except:\n messages.error(request, \"Failed to send message.\")\n return render(request, 'career.html')\n\n\ndef create_callback_request(request, *args, **kwargs):\n if request.method == 'POST':\n phone_number =request.POST.get('phone')\n print(phone_number)\n name = request.POST.get('name')\n print(name)\n callback_timing =request.POST.get('day')\n print(callback_timing)\n message = request.POST.get('message')\n print(message)\n try:\n contact_obj = CallbackRequest.objects.create(\n name = name,\n body = message,\n mobile=phone_number,\n callback_timing=callback_timing\n )\n messages.success(request, \"Message sent successfully.\")\n return HttpResponseRedirect('/')\n except:\n messages.error(request, \"Failed to send message.\")\n return render(request, 'contact.html')\n","sub_path":"home_service/service/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"68584957","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport argparse\nimport numpy as np\nimport cv2 as cv\nimport mediapipe as mp\nimport face_mesh\nimport pose\nimport hands\n\ndraw_color = (241, 252, 102)\n\n\nclass Holistic():\n @classmethod\n def set_args(cls, parser):\n parser.add_argument('--upper_body_only', action='store_true')\n parser.add_argument(\"--min_detection_confidence\",\n help='min_detection_confidence',\n type=float,\n default=0.5)\n parser.add_argument(\"--min_tracking_confidence\",\n help='min_tracking_confidence',\n type=int,\n default=0.5)\n parser.add_argument('--use_brect', action='store_true')\n return parser\n\n\n def __init__(self, args):\n self.upper_body_only_ = args.upper_body_only\n self.min_detection_confidence_ = args.min_detection_confidence\n self.min_tracking_confidence_ = args.min_tracking_confidence\n self.use_brect_ = args.use_brect\n\n mp_holistic = mp.solutions.holistic\n self.holistic_ = mp_holistic.Holistic(\n upper_body_only=self.upper_body_only_,\n min_detection_confidence=self.min_detection_confidence_,\n min_tracking_confidence=self.min_tracking_confidence_,\n )\n\n\n def process(self, process_img):\n results = self.holistic_.process(process_img)\n return results\n\n\n def draw(self, results, display_img):\n if results.face_landmarks is not None:\n # 外接矩形の計算\n brect = face_mesh.calc_bounding_rect(display_img, results.face_landmarks)\n # 描画\n display_img = face_mesh.draw_landmarks(display_img, results.face_landmarks)\n display_img = face_mesh.draw_bounding_rect(self.use_brect_, display_img, brect)\n\n if results.pose_landmarks is not None:\n # 外接矩形の計算\n brect = pose.calc_bounding_rect(display_img, results.pose_landmarks)\n # 描画\n display_img = pose.draw_landmarks(display_img, results.pose_landmarks,\n self.upper_body_only_)\n display_img = pose.draw_bounding_rect(self.use_brect_, display_img, brect)\n\n # Hands\n hand_results = [\n [results.left_hand_landmarks, 'L'],\n [results.right_hand_landmarks, 'R'],\n ]\n for hand_landmarks, handedness_str in hand_results:\n if hand_landmarks is not None:\n # 手の平重心計算\n cx, cy = hands.calc_palm_moment(display_img, hand_landmarks)\n # 外接矩形の計算\n brect = hands.calc_bounding_rect(display_img, hand_landmarks)\n # 描画\n display_img = hands.draw_landmarks(display_img, cx, cy,\n hand_landmarks,\n handedness_str,\n self.upper_body_only_)\n display_img = hands.draw_bounding_rect(self.use_brect_, display_img, brect)\n return display_img\n","sub_path":"holistic.py","file_name":"holistic.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"339525694","text":"#!/usr/bin/python3\n\nimport networkx as nx\nimport numpy as np\nimport sys\nimport datetime\n\ndef ler_grafo(arquivo):\n arq = open(arquivo, 'r')\n texto = arq.readlines()\n G = nx.Graph()\n for linha in texto:\n if(linha[0] == 'c' or linha[0] == 'p'):\n continue\n linha = linha.replace(\"\\n\", \"\")\n partes = linha.split(\" \")\n G.add_edge(partes[1], partes[2])\n\n arq.close()\n\n return G\n\n\ng = ler_grafo(sys.argv[1])\n\nstart = datetime.datetime.now()\nresult = nx.greedy_color(g, strategy='DSATUR', interchange=False)\nend = datetime.datetime.now()\nelapsed = end - start\n\ncores = list(result.values())\n#print(\"Arquivo: \" + str(sys.argv[1]) + \"\\n\")\nif(len(sys.argv) == 3 and sys.argv[2] == 'm'):\n print(';' + str(len(np.unique(cores)))+\";\"+str(int(elapsed.total_seconds()*1000)))\nelse:\n print(\"Numero de cores encontradas: \" + str(len(np.unique(cores))))\n","sub_path":"dsatur.py","file_name":"dsatur.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"451154461","text":"from flask import *\nfrom process import *\nfrom py2neo import *\nimport os\n\napp = Flask(__name__)\ngraph = Graph('http://localhost/db/graph', password='aadi2203')\nselector = NodeSelector(graph)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/askSomething', methods=['POST'])\ndef ask_something():\n tx = graph.begin()\n nodes = list()\n for i in request.json['ques'].split():\n cur = selector.select('WORD', name=i).first()\n print(cur)\n if cur is None:\n node = Node('WORD', name=i)\n nodes.append(node)\n tx.create(node)\n else:\n nodes.append(cur)\n print(nodes)\n for i in range(1, len(nodes)):\n query = 'MATCH (n:WORD {name: \"' + nodes[i-1].properties['name'] + '\"})-[r:NEXT]-(m:WORD {name: \"' + nodes[i].properties['name'] + '\"}) RETURN True'\n if len(graph.run(query).data()) == 0:\n tx.create(Relationship(nodes[i - 1], 'NEXT', nodes[i]))\n tx.commit()\n return json.dumps({'status':'OK', 'value':','.join(string_tokenize(request.json['ques']))})\n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"275753702","text":"import argparse\nimport os\nfrom PIL import Image\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"original_path\",\n type=str,\n help=\"original image's path\"\n )\n parser.add_argument(\n \"--width\",\n type=int,\n help=\"width of output image\"\n )\n parser.add_argument(\n \"--height\",\n type=int,\n help=\"height of output image\"\n )\n parser.add_argument(\n \"--scale\",\n type=float,\n help=\"scale of output image. Don't use --width \"\n \"or --height if you use --scale\")\n parser.add_argument(\n \"--output\",\n type=str,\n help=\"output image's path\"\n )\n return parser.parse_args()\n\n\ndef open_image(path_to_original):\n image = Image.open(path_to_original)\n return image\n\n\ndef get_new_size(old_width, old_height, new_width, new_height, scale):\n if scale is not None:\n return int(old_width * scale), int(old_height * scale)\n if new_width and new_height:\n return new_width, new_height\n if new_width:\n return new_width, int(old_height * new_width / old_width)\n if new_height:\n return int(old_width * new_height / old_height), new_height\n\n\ndef resize_image(image, new_file_full_path, new_width, new_height):\n image = image.resize((new_width, new_height))\n image.save(new_file_full_path)\n\n\ndef make_output_full_path(orig_path, out_path, width, height):\n orig_name, extension = os.path.splitext(orig_path)\n return \"{0}__{1}x{2}{3}\".format(\n os.path.join(out_path, os.path.split(orig_name)[1]),\n width,\n height,\n extension\n )\n\n\ndef get_arguments_errors(original_path, width, height, scale, output_path):\n if not os.path.isfile(original_path):\n return \"{} not exists\".format(os.path.abspath(original_path))\n if scale and (width or height):\n return \"Arguments error: Don't use --scale with --width and --height\"\n if not any([scale, width, height]):\n return \"Arguments error: No arguments to resize. Start with --help\"\n if not os.path.isdir(output_path):\n return \"Error: {} is not existing folder\".format(output_path)\n\n\nif __name__ == \"__main__\":\n args = get_args()\n original_path = os.path.abspath(args.original_path)\n width = args.width\n height = args.height\n scale = args.scale\n output_path = os.path.abspath(args.output)\n if output_path is None:\n output_path = os.path.dirname(original_path)\n\n arguments_errors = get_arguments_errors(\n original_path,\n width,\n height,\n scale,\n output_path\n )\n\n if arguments_errors:\n exit(arguments_errors)\n\n if scale is None and (width and height):\n print(\"Warning: Proportions could be broken!\")\n\n original_image = open_image(original_path)\n original_width, original_height = original_image.size\n\n new_width, new_height = get_new_size(\n original_width,\n original_height,\n width,\n height,\n scale\n )\n\n new_file_full_path = make_output_full_path(original_path, output_path, new_width, new_height)\n resize_image(original_image, new_file_full_path, new_width, new_height)\n print(\"Done: \\n{}\".format(new_file_full_path))\n","sub_path":"image_resize.py","file_name":"image_resize.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"153893086","text":"\"\"\"malldatabase URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.urls import path,include\nfrom .import views as v\n\nurlpatterns = [\n path('',v.home,name='homepage'),\n path('userhome/',v.userhome,name='userhome'),\n path('modelinsert/',v.modelform,name='modelform'),\n path('userregform/',v.registrationfn,name='regform'),\n path('userlogin/',v.loginfn,name='login'),\n path('userlogout/',v.logoutfn,name='logout'),\n path('update//',v.update,name='update'),\n path('delete//',v.delete,name='delete'),\n path('imageupload/',v.uploading,name='imageupload')\n]\n","sub_path":"mallapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"295727655","text":"class Solution:\n def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:\n answer = [0]*n\n for x,y,z in bookings:\n answer[x-1]+=z\n if y')\n j = list.find('')\n name = list[i+8:j]\n list = list[j:-1]\n\n #Добавление жанр к названию\n i = list.find('')\n j = list.find('') #Находим, где начинаются сеансы в 3D\n if j == -1:\n j = len(list)\n for m in re.finditer('booking-wrapper', list):\n i = m.start()\n if j > i: #Добавляем title\n title = '2D'\n else:\n title = '3D'\n\n time = list[i+150:i+200]\n z = time.find('time\">')\n time = time[z+6:z+11]\n\n price = list[i+340:i+370]\n z = price.find('₽')\n price = price[z-4:z-1]\n\n hall = list[i+520:i+600]\n z = list.find('>Зал')\n hall = list[z+5]\n\n id = list[i+980:i+1030]\n z = id.find('?performance=')\n id = id[z+13:z+18]\n\n json_data['ANS'][f]['tickets'].append({'title': title, 'time': time, 'price': price, 'hall': hall, 'id': id })\n f1 = f1 + 1\n\n\n f = f + 1\n return json_data\n #with open(\"TriPingvina.json\", \"w\") as f:\n # f.write(json.dumps(json_data, ensure_ascii=False ))\n","sub_path":"TriPinvgvinaFilmsApi.py","file_name":"TriPinvgvinaFilmsApi.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"303436254","text":"import cadquery as cq\n\nlength = 258\nwidth = 55\nfoot_w = 6\nfoot_h = 40\ncc_screw = 30\nscrew_d = 4\nscrew_h = 10\nth = 10\n\nres = (cq.Workplane(\"XY\")\n .tag(\"bot\")\n .rect(foot_w, width)\n .extrude(-foot_h)\n .edges(\"|Z\")\n .fillet(2.99)\n .edges(\"Z\")\n .fillet(1)\n )\n","sub_path":"cad/pumpsupport-foot.py","file_name":"pumpsupport-foot.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485243526","text":"#提取目录下所有图片,更改尺寸后保存到另一目录\nfrom PIL import Image\nimport os.path\nimport glob\ndef convertjpg(jpgfile,outdir,width=500):\n img=Image.open(jpgfile)\n wid=img.size[0]\n hei=img.size[1]\n height=500*hei//wid\n try:\n\n new_img=img.resize((width,height),Image.BILINEAR) \n new_img.save(os.path.join(outdir,os.path.basename(jpgfile)))\n except Exception as e:\n print(e)\n\nfor jpgfile in glob.glob(\"./img/*.jpg\"):\n convertjpg(jpgfile,\"./output\")\n\n","sub_path":"modify/modify.py","file_name":"modify.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"262815823","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nCreated on Wed Sep 9 09:43:47 2020\n\n@author: hankui\n\n\"\"\"\n\n\n#%%\ntest1 = [4,3,2,7,8,2,3,1]\ntest2 = [2, 2]\n\n\n#%%\ndef findDuplicates(nums):\n \n res = []\n \n #import pdb\n #pdb.set_trace()\n \n for i,v in enumerate(nums):\n absv = abs(v)\n if nums[absv-1] > 0:\n nums[absv-1] = -nums[absv-1]\n else:\n res.append(abs(v)) \n return res\n\n\n#%%\nfindDuplicates(test2)\n\n","sub_path":"Q442_findDuplicates.py","file_name":"Q442_findDuplicates.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193438093","text":"# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n\r\nclass Solution:\r\n def deleteDuplicates(self, head):\r\n \"\"\"\r\n :type head: ListNode\r\n :rtype: ListNode\r\n \"\"\"\r\n if head == None:\r\n return head\r\n FakeHead = ListNode(0)\r\n FakeHead.next = head\r\n pre = FakeHead\r\n cur = head\r\n while cur:\r\n duplicate = False \r\n while (cur.next and cur.val == cur.next.val):\r\n cur = cur.next\r\n duplicate = True\r\n if not duplicate:\r\n pre = cur\r\n else:\r\n pre.next = cur.next\r\n cur = cur.next\r\n return FakeHead.next","sub_path":"82. 删除排序链表中的重复元素II.py","file_name":"82. 删除排序链表中的重复元素II.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618140442","text":"import os\nimport logging\nimport asyncio as aio\nfrom ndn.encoding import Name\nfrom ndn.app import NDNApp\nfrom coalesce.coalesce_v1 import Requester\n\nMASTER_KEY_PATH = './temp-master-key.dat'\nCA_NAME = '/coal-exam/CA/example-ca'\nDEVICE_IDENTITY = Name.from_str('/coal-exam/DEVICE/device1')\nROLE_NAMES = [Name.from_str('/coal-exam/ROLE/role1'),\n Name.from_str('/coal-exam/ROLE/role2')]\nDATA_NAMES = [Name.from_str('/coal-exam/scope1/testApp'),\n Name.from_str('/coal-exam/scope2/testApp')]\n\n\nlogging.basicConfig(format='[{asctime}]{levelname}:{message}',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO,\n style='{')\n\n\ndef main():\n app = NDNApp()\n signers = [None for _ in DATA_NAMES]\n\n for i, data_name in enumerate(DATA_NAMES):\n def wrapper(k):\n # Don't know why bu i cannot be directly used here\n @app.route(data_name)\n def on_interest(name, param, _app_param):\n nonlocal signers\n if signers[k] is None:\n print('Not ready to serve yet.')\n return\n content = f\"Data in scope-{k+1}, signed by role-{k+1}'s key\".encode()\n app.put_data(name, content=content, freshness_period=10000, signer=signers[k])\n print(f'>> I: {Name.to_str(name)}, {param}')\n print(f'<< D: {Name.to_str(name)}')\n print(f'Content: (size: {len(content)})')\n print()\n\n wrapper(i)\n\n async def after_start():\n nonlocal signers\n\n # Fetch CA's public key for demonstration.\n # Pre-shared in real-world scenario\n _, _, ca_pub_key = await app.express_interest(CA_NAME+'/KEY', can_be_prefix=True)\n ca_pub_key = bytes(ca_pub_key)\n\n # Create requester\n requester = Requester(app, DEVICE_IDENTITY, Name.from_str(CA_NAME), ca_pub_key, ROLE_NAMES)\n\n # Load existing master key\n if os.path.exists(MASTER_KEY_PATH):\n with open(MASTER_KEY_PATH, 'rb') as f:\n cat_data = f.read()\n requester.load_master_key(cat_data)\n new_cater = False\n else:\n requester.gen_master_key()\n new_cater = True\n\n # Register routes\n requester.register()\n await aio.sleep(0.1)\n if new_cater:\n print('Bootstrapping ...')\n await requester.bootstrap()\n await aio.sleep(0.1)\n cat_data = requester.save_master_key()\n with open(MASTER_KEY_PATH, 'wb') as f:\n f.write(cat_data)\n\n def on_renew():\n for j, _ in enumerate(DATA_NAMES):\n signers[j] = requester.signer(j)\n\n print('Register KEY rolling events ...')\n aio.create_task(requester.auto_renew(on_renew))\n print('Ready to serve.')\n print()\n\n app.run_forever(after_start=after_start())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/device.py","file_name":"device.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"195260057","text":"from enum import Enum\n\n\n# enum for card face\nclass CardFace(Enum):\n X = 10 # Ten\n J = 11 # Jack\n Q = 12 # Queen\n K = 13 # King\n\n\n# enum for card suit\nclass CardSuit(Enum):\n S = 0 # spade\n H = 1 # heart\n C = 2 # club\n D = 3 # diamond\n\n\nclass Card:\n def __init__(self, card_face, card_suit):\n self.face = card_face\n self.suit = card_suit\n\n def __str__(self):\n if self.face < 10:\n s = str(self.face)\n else:\n s = str(CardFace(self.face).name)\n s += ':' + str(self.suit.name)\n return s\n","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"271026565","text":"from opengever.base.command import BaseObjectCreatorCommand\nfrom opengever.base.command import CreateDocumentCommand\nfrom opengever.base.role_assignments import RoleAssignment\nfrom opengever.base.role_assignments import RoleAssignmentManager\nfrom opengever.document.docprops import DocPropertyWriter\nfrom opengever.document.handlers import DISABLE_DOCPROPERTY_UPDATE_FLAG\nfrom opengever.dossier.dossiertemplate.dossiertemplate import BEHAVIOR_INTERFACE_MAPPING\nfrom plone.dexterity.utils import iterSchemataForType\nfrom zope.globalrequest import getRequest\n\n\nclass CreateDocumentFromTemplateCommand(CreateDocumentCommand):\n \"\"\"Store a copy of the template in the new document's primary file field\n \"\"\"\n\n def __init__(self, context, template_doc, title, recipient_data=tuple(),\n sender_data=tuple(), participation_data=[]):\n data = getattr(template_doc.get_file(), \"data\", None)\n super(CreateDocumentFromTemplateCommand, self).__init__(\n context, template_doc.get_filename(), data,\n title=title)\n self.recipient_data = recipient_data\n self.sender_data = sender_data\n self.participation_data = participation_data\n\n # Grab blocking of role inheritance\n self.block_role_inheritance = getattr(\n template_doc, '__ac_local_roles_block__', None)\n\n # Grab the local roles assignations from the template, if any\n self.role_assignments = None\n manager = RoleAssignmentManager(template_doc)\n if manager.has_storage():\n self.role_assignments = tuple(\n RoleAssignment(**assignment)\n for assignment in manager.storage.get_all()\n )\n\n def execute(self):\n # The blob will be overwritten just afterwards when we add\n # the recepient data to the docproperties. Solr will then\n # be unable to process that blob.\n getRequest().set(DISABLE_DOCPROPERTY_UPDATE_FLAG, True)\n obj = super(CreateDocumentFromTemplateCommand, self).execute()\n\n getRequest().set(DISABLE_DOCPROPERTY_UPDATE_FLAG, False)\n DocPropertyWriter(obj, recipient_data=self.recipient_data,\n sender_data=self.sender_data,\n participation_data=self.participation_data).initialize()\n\n # Set blocking of role inheritance based on the template object\n if self.block_role_inheritance is not None:\n obj.__ac_local_roles_block__ = self.block_role_inheritance\n\n # Copy the local roles assignations over from the template\n if self.role_assignments is not None:\n manager = RoleAssignmentManager(obj)\n # Passing an empty iterable in here creates an empty mapping\n manager.add_or_update_assignments(self.role_assignments)\n return obj\n\n\nclass CreateDossierFromTemplateCommand(BaseObjectCreatorCommand):\n \"\"\"Creates a new dossier based on the dossiertemplate.\n \"\"\"\n portal_type = 'opengever.dossier.businesscasedossier'\n\n def __init__(self, context, template):\n kw = self._get_additional_attributes(template)\n self.fields = kw[\"IOpenGeverBase\"]\n del kw[\"IOpenGeverBase\"]\n self.additional_fields = kw\n\n # Grab blocking of role inheritance\n self.block_role_inheritance = getattr(\n template, '__ac_local_roles_block__', None)\n\n # Grab the local roles assignments from the template, if any\n self.role_assignments = None\n manager = RoleAssignmentManager(template)\n if manager.has_storage():\n self.role_assignments = tuple(\n RoleAssignment(**assignment)\n for assignment in manager.storage.get_all()\n )\n\n super(CreateDossierFromTemplateCommand, self).__init__(\n context, **self.fields)\n\n def execute(self):\n obj = super(CreateDossierFromTemplateCommand, self).execute()\n schemas = iterSchemataForType(self.portal_type)\n for schema in schemas:\n schema_name = BEHAVIOR_INTERFACE_MAPPING.get(\n schema.getName(), schema.getName())\n if schema_name not in self.additional_fields:\n continue\n behavior = schema(obj)\n for prop_name in self.additional_fields[schema_name]:\n setattr(behavior, prop_name,\n self.additional_fields[schema_name][prop_name])\n\n # Set blocking of role inheritance based on the template object\n if self.block_role_inheritance is not None:\n obj.__ac_local_roles_block__ = self.block_role_inheritance\n\n # Copy the local roles assignations over from the template\n if self.role_assignments is not None:\n manager = RoleAssignmentManager(obj)\n # Passing an empty iterable in here creates an empty mapping\n manager.add_or_update_assignments(self.role_assignments)\n\n return obj\n\n def _get_additional_attributes(self, template):\n \"\"\"Get all templatable attributes defined in the template.\n \"\"\"\n kw = template.get_schema_values()\n fields = {}\n for key, value in kw.items():\n schema_name, prop_name = key.split(\".\")\n if schema_name not in fields:\n fields[schema_name] = {}\n fields[schema_name][prop_name] = value\n return fields\n","sub_path":"opengever/dossier/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"91788518","text":"s = str(input())\r\nif len(s) == 1:\r\n print(1)\r\nelse:\r\n def function(s,x):\r\n cnt = 0\r\n stor = []\r\n i = 0\r\n while i < len(s):\r\n if s[i] == x:\r\n cnt+=1\r\n else:\r\n cnt = 0\r\n\r\n i = i+1\r\n stor.append(cnt)\r\n \r\n n = len(stor)\r\n final = []\r\n\r\n for i in range(len(stor)-1):\r\n if stor[i+1] == 0:\r\n final.append(stor[i])\r\n \r\n if stor[-1] != 0:\r\n final.append(stor[-1])\r\n ans = max(final)\r\n\r\n return ans\r\n\r\n\r\n#print(function(s, x))\r\n\r\n ans1 = function(s,'A')\r\n ans2 = function(s, 'C')\r\n ans3 = function(s, 'G')\r\n ans4 = function(s, 'T')\r\n\r\n print(max(ans1, ans2, ans3,ans4))\r\n","sub_path":"cses problem set Repitetions.py","file_name":"cses problem set Repitetions.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"115374139","text":"import datetime\nimport http.client as http_client\nimport logging\nimport marshmallow as ma\nimport json\nfrom contextlib import ExitStack\nfrom flask import url_for, g, jsonify, current_app\nfrom flask.views import MethodView\nfrom drift.blueprint import Blueprint, abort\n\nfrom drift.core.extensions.jwt import current_user, requires_roles\nfrom drift.core.extensions.urlregistry import Endpoints\nfrom driftbase.matchqueue import process_match_queue\nfrom driftbase.models.db import Machine, Server, Match, MatchTeam, MatchPlayer, MatchQueuePlayer, CorePlayer\nfrom driftbase.utils import log_match_event\nfrom driftbase.utils import url_player\n\nDEFAULT_ROWS = 100\n\nlog = logging.getLogger(__name__)\n\nbp = Blueprint(\"matches\", __name__, url_prefix=\"/matches\")\nendpoints = Endpoints()\n\nMATCH_HEARTBEAT_TIMEOUT_SECONDS = 60\n\n\ndef drift_init_extension(app, **kwargs):\n app.register_blueprint(bp)\n endpoints.init_app(app)\n\n\ndef utcnow():\n return datetime.datetime.utcnow()\n\n\nclass ActiveMatchesGetQuerySchema(ma.Schema):\n ref = ma.fields.String()\n placement = ma.fields.String()\n realm = ma.fields.String()\n version = ma.fields.String()\n player_id = ma.fields.List(ma.fields.Integer(), load_default=[])\n rows = ma.fields.Integer(load_default=DEFAULT_ROWS)\n\n\n@bp.route('/active', endpoint='active')\nclass ActiveMatchesAPI(MethodView):\n \"\"\"UE4 matches available for matchmaking\n \"\"\"\n\n @bp.arguments(ActiveMatchesGetQuerySchema, location='query')\n def get(self, args):\n \"\"\"\n Get active matches\n\n This endpoint used by clients to fetch a list of matches available\n for joining\n \"\"\"\n num_rows = args[\"rows\"] or DEFAULT_ROWS\n\n query = g.db.query(Match, Server, Machine)\n query = query.filter(Server.machine_id == Machine.machine_id,\n Match.server_id == Server.server_id,\n Match.status.notin_([\"ended\", \"completed\"]),\n Server.status.in_([\"started\", \"running\", \"active\", \"ready\"]),\n Server.heartbeat_date >= utcnow() - datetime.timedelta(\n seconds=MATCH_HEARTBEAT_TIMEOUT_SECONDS)\n )\n if args.get(\"ref\"):\n query = query.filter(Server.ref == args.get(\"ref\"))\n if args.get(\"version\"):\n query = query.filter(Server.version == args.get(\"version\"))\n if args.get(\"placement\"):\n query = query.filter(Machine.placement == args.get(\"placement\"))\n if args.get(\"realm\"):\n query = query.filter(Machine.realm == args.get(\"realm\"))\n player_ids = args[\"player_id\"]\n\n query = query.order_by(-Match.num_players, -Match.server_id)\n query = query.limit(num_rows)\n rows = query.all()\n\n ret = []\n for row in rows:\n include = True\n if player_ids:\n include = False\n\n match = row[0]\n server = row[1]\n machine = row[2]\n record = {}\n record[\"create_date\"] = match.create_date\n record[\"game_mode\"] = match.game_mode\n record[\"map_name\"] = match.map_name\n record[\"max_players\"] = match.max_players\n record[\"match_status\"] = match.status\n record[\"server_status\"] = server.status\n record[\"public_ip\"] = server.public_ip\n record[\"port\"] = server.port\n record[\"version\"] = server.version\n record[\"match_id\"] = match.match_id\n record[\"server_id\"] = match.server_id\n record[\"machine_id\"] = server.machine_id\n record[\"heartbeat_date\"] = server.heartbeat_date\n record[\"realm\"] = machine.realm\n record[\"placement\"] = machine.placement\n record[\"ref\"] = server.ref\n record[\"match_url\"] = url_for(\"matches.entry\",\n match_id=match.match_id,\n _external=True)\n record[\"server_url\"] = url_for(\"servers.entry\",\n server_id=server.server_id,\n _external=True)\n record[\"machine_url\"] = url_for(\"machines.entry\",\n machine_id=server.machine_id,\n _external=True)\n conn_url = \"%s:%s?player_id=%s?token=%s\"\n record[\"ue4_connection_url\"] = conn_url % (server.public_ip,\n server.port,\n current_user[\"player_id\"],\n server.token)\n player_array = []\n players = g.db.query(MatchPlayer) \\\n .filter(MatchPlayer.match_id == match.match_id,\n MatchPlayer.status.in_([\"active\"])) \\\n .all()\n for player in players:\n player_array.append({\n \"player_id\": player.player_id,\n \"player_url\": url_player(player.player_id),\n })\n if player.player_id in player_ids:\n include = True\n record[\"players\"] = player_array\n record[\"num_players\"] = len(player_array)\n\n if include:\n ret.append(record)\n\n return jsonify(ret)\n\n\ndef unique_key_in_use(unique_key):\n if unique_key:\n query = g.db.query(Match, Server)\n existing_unique_match = query.filter(Match.server_id == Server.server_id,\n Match.status.notin_([\"ended\", \"completed\"]),\n Match.unique_key == unique_key,\n Server.status.in_([\"started\", \"running\", \"active\", \"ready\"]),\n Server.heartbeat_date >= utcnow() - datetime.timedelta(\n seconds=MATCH_HEARTBEAT_TIMEOUT_SECONDS)\n ).first()\n return existing_unique_match is not None\n return False\n\n\ndef lock(redis):\n # Moving this into a separate function so systems test can mock it out.\n return redis.lock(\"ensure_match_unique_key\")\n\n\nclass MatchPutRequestSchema(ma.Schema):\n status = ma.fields.String(required=True)\n\n server_id = ma.fields.Integer()\n num_players = ma.fields.Integer()\n max_players = ma.fields.Integer()\n map_name = ma.fields.String()\n game_mode = ma.fields.String()\n unique_key = ma.fields.String()\n match_statistics = ma.fields.Dict()\n details = ma.fields.Dict()\n\n\n@bp.route('', endpoint='list')\nclass MatchesAPI(MethodView):\n \"\"\"UE4 match\n \"\"\"\n\n class MatchesAPIGetQuerySchema(ma.Schema):\n server_id = ma.fields.Integer()\n player_id = ma.fields.Integer()\n rows = ma.fields.Integer(load_default=DEFAULT_ROWS)\n use_pagination = ma.fields.Boolean(load_default=False)\n page = ma.fields.Integer(load_default=1)\n per_page = ma.fields.Integer(load_default=20)\n include_match_players = ma.fields.Boolean(load_default=False)\n game_mode = ma.fields.String()\n map_name = ma.fields.String()\n statistics_filter = ma.fields.String()\n details_filter = ma.fields.String()\n\n @bp.arguments(MatchesAPIGetQuerySchema, location='query')\n def get(self, args):\n \"\"\"This endpoint used by services and clients to fetch recent matches.\n Dump the DB rows out as json\n \"\"\"\n\n log.info(f\"Fetching matches for player {current_user['player_id']} with args {args}\")\n\n is_service = current_user.get('is_service', False) or \"service\" in current_user[\"roles\"]\n\n num_rows = args[\"rows\"] or DEFAULT_ROWS\n server_id = args.get(\"server_id\")\n\n # To prevent API breakage, use a separate implementation for pagination and make it opt-in.\n if args[\"use_pagination\"]:\n player_id = args.get(\"player_id\")\n game_mode = args.get(\"game_mode\")\n map_name = args.get(\"map_name\")\n statistics_filter = args.get(\"statistics_filter\")\n details_filter = args.get(\"details_filter\")\n\n if statistics_filter:\n try:\n statistics_filter = json.loads(statistics_filter)\n except json.JSONDecodeError:\n abort(http_client.BAD_REQUEST, description=\"Invalid statistics_filter\")\n\n if details_filter:\n try:\n details_filter = json.loads(details_filter)\n except json.JSONDecodeError:\n abort(http_client.BAD_REQUEST, description=\"Invalid details_filter\")\n\n if is_service:\n matches_query = g.db.query(Match)\n else:\n matches_query = g.db.query(\n Match.match_id,\n Match.start_date,\n Match.end_date,\n Match.max_players,\n Match.game_mode,\n Match.map_name,\n Match.details,\n Match.match_statistics,\n Match.create_date,\n )\n\n if player_id:\n matches_query = matches_query.join(MatchPlayer, Match.match_id == MatchPlayer.match_id).filter(MatchPlayer.player_id == player_id)\n\n if server_id:\n matches_query = matches_query.filter(Match.server_id == server_id)\n\n if game_mode:\n matches_query = matches_query.filter(Match.game_mode == game_mode)\n\n if map_name:\n matches_query = matches_query.filter(Match.map_name == map_name)\n\n if statistics_filter:\n for key, value in statistics_filter.items():\n matches_query = matches_query.filter(Match.match_statistics[key].astext == value)\n\n if details_filter:\n for key, value in details_filter.items():\n matches_query = matches_query.filter(Match.details[key].astext == value)\n\n matches_query = matches_query.order_by(-Match.match_id)\n\n matches_result = matches_query.paginate(page=args[\"page\"], per_page=args[\"per_page\"], error_out=True, max_per_page=num_rows)\n\n include_match_players = args[\"include_match_players\"]\n\n matches = []\n for match_row in matches_result.items:\n # Service role gets a list of ORM object, but the client (which selects specific columns) gets an SQLAlchemy Row object\n if is_service:\n match_record = match_row.as_dict()\n else:\n match_record = match_row._asdict() # The Row object has an _asdict() method that *isn't* private/protected. It's part of the NamedTuple API\n\n match_id = match_record[\"match_id\"]\n\n match_record[\"url\"] = url_for(\"matches.entry\", match_id=match_id, _external=True)\n match_record[\"matchplayers_url\"] = url_for(\"matches.players\", match_id=match_id, _external=True)\n match_record[\"teams_url\"] = url_for(\"matches.teams\", match_id=match_id, _external=True)\n\n if include_match_players:\n # Fetch the match players\n if is_service:\n players_query = g.db.query(MatchPlayer, CorePlayer.player_name)\n else:\n players_query = g.db.query(\n MatchPlayer.id,\n MatchPlayer.match_id,\n MatchPlayer.player_id,\n MatchPlayer.team_id,\n MatchPlayer.join_date,\n MatchPlayer.leave_date,\n MatchPlayer.statistics,\n MatchPlayer.details,\n MatchPlayer.create_date,\n CorePlayer.player_name\n )\n\n players_query = players_query.join(CorePlayer, MatchPlayer.player_id == CorePlayer.player_id, isouter=True) \\\n .filter(MatchPlayer.match_id == match_id) \\\n .order_by(MatchPlayer.player_id)\n\n players_result = players_query.all()\n\n match_players = []\n for player_row in players_result:\n if is_service:\n [match_player, core_player] = player_row\n player_record = match_player.as_dict()\n player_record[\"player_name\"] = core_player[\"player_name\"] if core_player else \"\"\n else:\n player_record = player_row._asdict()\n player_record[\"player_name\"] = player_record[\"player_name\"] or \"\"\n\n player_id = player_record[\"player_id\"]\n player_record[\"player_url\"] = url_for(\"players.entry\", player_id=player_id, _external=True)\n player_record[\"matchplayer_url\"] = url_for(\"matches.player\", match_id=match_id, player_id=player_id, _external=True)\n match_players.append(player_record)\n\n match_record[\"players\"] = match_players\n match_record[\"num_players\"] = len(match_players)\n\n # Fetch the teams\n if is_service:\n teams_query = g.db.query(MatchTeam)\n else:\n teams_query = g.db.query(\n MatchTeam.team_id,\n MatchTeam.match_id,\n MatchTeam.name,\n MatchTeam.statistics,\n MatchTeam.details,\n MatchTeam.create_date,\n )\n\n teams_query = teams_query.filter(MatchTeam.match_id == match_id)\n\n teams_result = teams_query.all()\n\n match_teams = []\n for team_row in teams_result:\n if is_service:\n team_record = team_row.as_dict()\n else:\n team_record = team_row._asdict()\n\n team_record[\"url\"] = url_for(\"matches.team\", match_id=match_id, team_id=team_record[\"team_id\"], _external=True)\n match_teams.append(team_record)\n\n match_record[\"teams\"] = match_teams\n\n matches.append(match_record)\n\n ret = {\n \"items\": matches,\n \"total\": matches_result.total,\n \"page\": matches_result.page,\n \"pages\": matches_result.pages,\n \"per_page\": matches_result.per_page,\n }\n\n return jsonify(ret)\n\n query = g.db.query(Match)\n if server_id:\n query = query.filter(Match.server_id == server_id)\n query = query.order_by(-Match.match_id)\n query = query.limit(num_rows)\n rows = query.all()\n\n ret = []\n for row in rows:\n record = row.as_dict()\n record[\"url\"] = url_for(\"matches.entry\", match_id=row.match_id, _external=True)\n ret.append(record)\n return jsonify(ret)\n\n\n class MatchesPostRequestSchema(ma.Schema):\n server_id = ma.fields.Integer(required=True)\n\n num_players = ma.fields.Integer()\n max_players = ma.fields.Integer()\n map_name = ma.fields.String()\n game_mode = ma.fields.String()\n status = ma.fields.String()\n unique_key = ma.fields.String()\n match_statistics = ma.fields.Dict()\n details = ma.fields.Dict()\n num_teams = ma.fields.Integer(metadata=dict(\n description=\"Automatically create N teams with generic names. Mutually exclusive with team_names.\"))\n team_names = ma.fields.List(ma.fields.String(), metadata=dict(\n description=\"Create teams with specific names. Mutually exclusive with num_teams.\"))\n\n @requires_roles(\"service\")\n @bp.arguments(MatchesPostRequestSchema)\n def post(self, args):\n \"\"\"Register a new battle on the passed in match server.\n Each match server should always have a single battle.\n A match server will have zero matches only when it doesn't start up.\n Either the celery match server task (in normal EC2 mode) or the\n match server unreal process (in local development mode) will call\n this endpoint to create the battle resource.\n \"\"\"\n server_id = args.get(\"server_id\")\n unique_key = args.get(\"unique_key\")\n details = args.get(\"details\")\n\n num_teams = args.get(\"num_teams\")\n team_names = args.get(\"team_names\")\n\n if num_teams and team_names:\n abort(http_client.BAD_REQUEST, description=\"num_teams and team_names are mutually exclusive\")\n\n log.info(f\"Creating match for server {server_id} using {unique_key if unique_key else 'nothing'} as unique_key\")\n\n with ExitStack() as stack:\n if unique_key:\n stack.enter_context(lock(g.redis))\n\n if unique_key_in_use(unique_key):\n log.info(\"Tried to set the unique key '{}' of a battle when one already exists\".format(unique_key))\n abort(http_client.CONFLICT, description=\"An existing match with the same unique_key was found\")\n\n match = Match(server_id=server_id,\n num_players=args.get(\"num_players\", 0),\n max_players=args.get(\"max_players\"),\n map_name=args.get(\"map_name\"),\n game_mode=args.get(\"game_mode\"),\n status=args.get(\"status\"),\n status_date=utcnow(),\n start_date=None,\n match_statistics=args.get(\"match_statistics\"),\n details=details,\n unique_key=unique_key,\n )\n g.db.add(match)\n g.db.flush()\n # ! have to set this explicitly after the row is created\n match.start_date = None\n g.db.commit()\n match_id = match.match_id\n\n if num_teams:\n for i in range(num_teams):\n team = MatchTeam(match_id=match_id,\n name=\"Team %s\" % (i + 1)\n )\n g.db.add(team)\n g.db.commit()\n\n if team_names:\n for team_name in team_names:\n team = MatchTeam(match_id=match_id,\n name=team_name\n )\n g.db.add(team)\n g.db.commit()\n\n resource_uri = url_for(\"matches.entry\", match_id=match_id, _external=True)\n players_resource_uri = url_for(\"matches.players\", match_id=match_id, _external=True)\n response_header = {\n \"Location\": resource_uri,\n }\n\n log.info(\"Created match %s for server %s\", match_id, server_id)\n log_match_event(match_id, None, \"gameserver.match.created\",\n details={\"server_id\": server_id})\n\n try:\n process_match_queue()\n except Exception:\n log.exception(\"Unable to process match queue\")\n\n return jsonify({\"match_id\": match_id,\n \"url\": resource_uri,\n \"players_url\": players_resource_uri,\n }), http_client.CREATED, response_header\n\n\n@bp.route('/', endpoint='entry')\nclass MatchAPI(MethodView):\n \"\"\"\n Information about specific matches\n \"\"\"\n\n @requires_roles(\"service\")\n def get(self, match_id):\n \"\"\"\n Find battle by ID\n\n Get information about a single battle. Dumps out the DB row as json\n URL's are provided for additional information about the battle for\n drilldown. Machine and matcheserver url's are also written out.\n \"\"\"\n match = g.db.query(Match).get(match_id)\n if not match:\n abort(http_client.NOT_FOUND)\n\n ret = match.as_dict()\n ret[\"url\"] = url_for(\"matches.entry\", match_id=match_id, _external=True)\n\n server = g.db.query(Server).get(match.server_id)\n ret[\"server\"] = None\n ret[\"server_url\"] = None\n ret[\"machine_url\"] = None\n if server:\n ret[\"server\"] = server.as_dict()\n ret[\"server_url\"] = url_for(\"servers.entry\", server_id=server.server_id, _external=True)\n\n machine = g.db.query(Machine).get(server.machine_id)\n ret[\"machine\"] = None\n if machine:\n ret[\"machine_url\"] = url_for(\"machines.entry\",\n machine_id=machine.machine_id, _external=True)\n\n teams = []\n rows = g.db.query(MatchTeam).filter(MatchTeam.match_id == match_id).all()\n for r in rows:\n team = r.as_dict()\n team[\"url\"] = url_for(\"matches.team\", match_id=match_id, team_id=r.team_id,\n _external=True)\n teams.append(team)\n ret[\"teams\"] = teams\n\n ret[\"matchplayers_url\"] = url_for(\"matches.players\", match_id=match_id, _external=True)\n ret[\"teams_url\"] = url_for(\"matches.teams\", match_id=match_id, _external=True)\n\n players = []\n rows = g.db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id).all()\n for r in rows:\n player = r.as_dict()\n player[\"matchplayer_url\"] = url_for(\"matches.player\", match_id=match_id,\n player_id=r.player_id, _external=True)\n player[\"player_url\"] = url_player(r.player_id)\n players.append(player)\n ret[\"players\"] = players\n ret[\"num_players\"] = len(players)\n\n log.debug(\"Returning info for match %s\", match_id)\n\n return jsonify(ret)\n\n @requires_roles(\"service\")\n @bp.arguments(MatchPutRequestSchema)\n def put(self, args, match_id):\n \"\"\"\n Update battle status\n\n The UE4 server calls this method to update its status and any\n metadata that the backend should know about\n \"\"\"\n\n log.debug(\"Updating battle %s\", match_id)\n unique_key = args.get(\"unique_key\")\n\n with ExitStack() as stack:\n if unique_key:\n stack.enter_context(lock(g.redis))\n\n match = g.db.query(Match).get(match_id)\n if not match:\n abort(http_client.NOT_FOUND)\n new_status = args.get(\"status\")\n if match.status == \"completed\":\n log.warning(\"Trying to update a completed battle %d. Ignoring update\", match_id)\n abort(http_client.BAD_REQUEST, description=\"Battle has already been completed.\")\n\n current_unique_key = match.unique_key\n if unique_key and current_unique_key:\n log.info(\"Tried to update the unique key of a battle with a non-empty unique key '{}'->'{}'\".format(\n current_unique_key, unique_key))\n abort(http_client.CONFLICT, description=\"Battle unique key must not be changed from a non-empty value\")\n\n if unique_key_in_use(unique_key):\n log.info(\"Tried to set the unique key '{}' of a battle when one already exists\".format(unique_key))\n abort(http_client.CONFLICT, description=\"An existing match with the same unique_key was found\")\n\n message_data = None\n if match.status != new_status:\n log.info(\"Changing status of match %s from '%s' to '%s'\",\n match_id, match.status, args[\"status\"])\n\n message_data = {\"event\": \"match_status_changed\", \"match_id\": match_id, \"match_status\": new_status}\n\n if new_status == \"started\":\n match.start_date = utcnow()\n elif new_status == \"completed\":\n match.end_date = utcnow()\n # ! TODO: Set leave_date on matchplayers who are still in the match\n match.status_date = utcnow()\n\n for arg in args:\n setattr(match, arg, args[arg])\n g.db.commit()\n\n if message_data:\n current_app.extensions[\"messagebus\"].publish_message(\"match\", message_data)\n\n resource_uri = url_for(\"matches.entry\", match_id=match_id, _external=True)\n response_header = {\n \"Location\": resource_uri,\n }\n ret = {\n \"match_id\": match_id,\n \"url\": resource_uri,\n }\n\n log.info(\"Match %s has been updated.\", match_id)\n\n return jsonify(ret), http_client.OK, response_header\n\n\nclass MatchTeamsPostRequestSchema(ma.Schema):\n name = ma.fields.String()\n statistics = ma.fields.Dict()\n details = ma.fields.Dict()\n\n\nclass MatchTeamPutRequestSchema(ma.Schema):\n name = ma.fields.String()\n statistics = ma.fields.Dict()\n details = ma.fields.Dict()\n\n\n@bp.route('//teams', endpoint='teams')\nclass MatchTeamsAPI(MethodView):\n \"\"\"\n All teams in a match\n \"\"\"\n\n @requires_roles(\"service\")\n def get(self, match_id):\n \"\"\"\n Find teams by match\n \"\"\"\n query = g.db.query(MatchTeam)\n query = query.filter(MatchTeam.match_id == match_id)\n rows = query.all()\n\n ret = []\n for row in rows:\n record = row.as_dict()\n record[\"url\"] = url_for(\"matches.team\",\n match_id=match_id,\n team_id=row.team_id,\n _external=True)\n ret.append(record)\n return jsonify(ret)\n\n @requires_roles(\"service\")\n @bp.arguments(MatchTeamsPostRequestSchema)\n def post(self, args, match_id):\n \"\"\"\n Add a team to a match\n \"\"\"\n team = MatchTeam(match_id=match_id,\n name=args.get(\"name\"),\n statistics=args.get(\"statistics\"),\n details=args.get(\"details\"),\n )\n g.db.add(team)\n g.db.commit()\n team_id = team.team_id\n resource_uri = url_for(\"matches.team\", match_id=match_id, team_id=team_id, _external=True)\n response_header = {\"Location\": resource_uri}\n\n log.info(\"Created team %s for match %s\", team_id, match_id)\n log_match_event(match_id,\n None,\n \"gameserver.match.team_created\",\n details={\"team_id\": team_id})\n\n return jsonify({\"team_id\": team_id,\n \"url\": resource_uri,\n }), http_client.CREATED, response_header\n\n\n@bp.route('//teams/', endpoint='team')\nclass MatchTeamAPI(MethodView):\n \"\"\"\n A specific team in a match\n \"\"\"\n\n @requires_roles(\"service\")\n def get(self, match_id, team_id):\n \"\"\"\n Find a team in a match by ID's\n \"\"\"\n query = g.db.query(MatchTeam)\n query = query.filter(MatchTeam.match_id == match_id,\n MatchTeam.team_id == team_id)\n row = query.first()\n if not row:\n abort(http_client.NOT_FOUND)\n\n ret = row.as_dict()\n ret[\"url\"] = url_for(\"matches.team\", match_id=match_id, team_id=row.team_id, _external=True)\n\n query = g.db.query(MatchPlayer)\n query = query.filter(MatchPlayer.match_id == match_id,\n MatchPlayer.team_id == team_id)\n rows = query.all()\n players = []\n for r in rows:\n player = r.as_dict()\n player[\"matchplayer_url\"] = url_for(\"matches.player\",\n match_id=match_id,\n player_id=r.player_id,\n _external=True)\n player[\"player_url\"] = url_player(r.player_id)\n players.append(player)\n ret[\"players\"] = players\n return jsonify(ret)\n\n @requires_roles(\"service\")\n @bp.arguments(MatchTeamPutRequestSchema)\n def put(self, args, match_id, team_id):\n team = g.db.query(MatchTeam).get(team_id)\n if not team:\n abort(http_client.NOT_FOUND)\n for arg in args:\n setattr(team, arg, args[arg])\n g.db.commit()\n ret = team.as_dict()\n return jsonify(ret)\n\n\nclass MatchPlayerPostSchema(ma.Schema):\n player_id = ma.fields.Integer(required=True)\n team_id = ma.fields.Integer()\n\n\n@bp.route('//players', endpoint='players')\nclass MatchPlayersAPI(MethodView):\n \"\"\"\n Players in a specific match. The UE4 server will post to this endpoint\n to add a player to a match.\n \"\"\"\n\n def get(self, match_id):\n \"\"\"\n Get players from a match\n \"\"\"\n rows = g.db.query(MatchPlayer) \\\n .filter(MatchPlayer.match_id == match_id) \\\n .all()\n ret = []\n for r in rows:\n player = r.as_dict()\n player[\"matchplayer_url\"] = url_for(\"matches.player\",\n match_id=match_id,\n player_id=r.player_id,\n _external=True)\n player[\"player_url\"] = url_player(r.player_id)\n ret.append(player)\n\n return jsonify(ret)\n\n @requires_roles(\"service\")\n @bp.arguments(MatchPlayerPostSchema)\n def post(self, args, match_id):\n \"\"\"\n Add a player to a match\n \"\"\"\n log.info(f\"POST to MatchPlayersAPI with match_id {match_id} and args {args}\")\n player_id = args[\"player_id\"]\n team_id = args.get(\"team_id\", None)\n\n log.info(\n f\" dug up player_id {player_id} (type {type(player_id)}) and team_id {team_id} (type {type(team_id)})\")\n match = g.db.query(Match).get(match_id)\n if not match:\n log.warning(f\" match {match_id} not found. Aborting\")\n abort(http_client.NOT_FOUND, description=\"Match not found\")\n\n if match.status == \"completed\":\n log.warning(f\" match {match_id} is completed. Aborting\")\n abort(http_client.BAD_REQUEST, description=\"You cannot add a player to a completed battle\")\n\n num_players = g.db.query(MatchPlayer) \\\n .filter(MatchPlayer.match_id == match.match_id,\n MatchPlayer.status.in_([\"active\"])) \\\n .count()\n if num_players >= match.max_players:\n log.warning(f\" match {match_id} has {num_players} and maximum is {match.max_players}. Aborting\")\n abort(http_client.BAD_REQUEST, description=\"Match is full\")\n\n if team_id:\n team = g.db.query(MatchTeam).get(team_id)\n if not team:\n log.warning(f\" team_id {team_id} not found. Aborting.\")\n abort(http_client.NOT_FOUND, description=\"Team not found\")\n if team.match_id != match_id:\n log.warning(\n f\" team_id {team_id} doesn't belong to match {match_id}, it belongs to match {team.match_id}. Aborting.\")\n abort(http_client.BAD_REQUEST,\n description=\"Team %s is not in match %s\" % (team_id, match_id))\n\n match_player = g.db.query(MatchPlayer) \\\n .filter(MatchPlayer.match_id == match_id,\n MatchPlayer.player_id == player_id) \\\n .first()\n if not match_player:\n log.info(f\" player {player_id} not found in match already. Adding him...\")\n match_player = MatchPlayer(match_id=match_id,\n player_id=player_id,\n team_id=team_id,\n num_joins=0,\n seconds=0,\n status=\"active\")\n g.db.add(match_player)\n match_player.num_joins += 1\n match_player.join_date = utcnow()\n match_player.status = \"active\"\n\n # remove the player from the match queue\n g.db.query(MatchQueuePlayer).filter(MatchQueuePlayer.player_id == player_id).delete()\n\n if match.start_date is None:\n match.start_date = utcnow()\n\n g.db.commit()\n\n # prepare the response\n resource_uri = url_for(\"matches.player\",\n match_id=match_id,\n player_id=player_id,\n _external=True)\n response_header = {\"Location\": resource_uri}\n log.info(\"Player %s has joined match %s in team %s.\", player_id, match_id, team_id)\n\n log_match_event(match_id, player_id, \"gameserver.match.player_joined\",\n details={\"team_id\": team_id})\n\n return jsonify({\"match_id\": match_id,\n \"player_id\": player_id,\n \"team_id\": team_id,\n \"url\": resource_uri,\n }), http_client.CREATED, response_header\n\n\n@bp.route('//players/', endpoint='player')\nclass MatchPlayerAPI(MethodView):\n \"\"\"\n A specific player in a specific match\n \"\"\"\n\n class MatchPlayerPatchRequestSchema(ma.Schema):\n status = ma.fields.String()\n team_id = ma.fields.Integer()\n statistics = ma.fields.Dict()\n details = ma.fields.Dict()\n\n def get(self, match_id, player_id):\n \"\"\"\n Get a specific player from a battle\n \"\"\"\n player = g.db.query(MatchPlayer) \\\n .filter(MatchPlayer.match_id == match_id, MatchPlayer.player_id == player_id) \\\n .first()\n if not player:\n abort(http_client.NOT_FOUND)\n\n ret = player.as_dict()\n ret[\"team_url\"] = None\n if player.team_id:\n ret[\"team_url\"] = url_for(\"matches.team\", match_id=match_id,\n team_id=player.team_id, _external=True)\n ret[\"player_url\"] = url_player(player_id)\n return jsonify(ret)\n\n @requires_roles(\"service\")\n @bp.arguments(MatchPlayerPatchRequestSchema)\n def patch(self, args, match_id, player_id):\n \"\"\"\n Update a specific player in a battle\n \"\"\"\n match_player = g.db.query(MatchPlayer) \\\n .filter(MatchPlayer.match_id == match_id,\n MatchPlayer.player_id == player_id) \\\n .first()\n\n if not match_player:\n log.info(f\"player {player_id} not found in match {match_id}. Aborting.\")\n abort(http_client.NOT_FOUND)\n\n for attr, value in args.items():\n setattr(match_player, attr, value)\n g.db.commit()\n\n log.info(\"Player %s updated in match %s\", player_id, match_id)\n log_match_event(match_id, player_id, \"gameserver.match.player_updated\", details=args)\n\n ret = match_player.as_dict()\n ret[\"player_url\"] = url_player(player_id)\n ret[\"team_url\"] = None\n\n if match_player.team_id:\n ret[\"team_url\"] = url_for(\"matches.team\", match_id=match_id, team_id=match_player.team_id, _external=True)\n\n return jsonify(ret)\n\n @requires_roles(\"service\")\n def delete(self, match_id, player_id):\n \"\"\"\n A player has left an ongoing battle\n \"\"\"\n match_player = g.db.query(MatchPlayer) \\\n .filter(MatchPlayer.match_id == match_id,\n MatchPlayer.player_id == player_id) \\\n .first()\n if not match_player:\n log.info(f\"player {player_id} not found in match {match_id}. Aborting.\")\n abort(http_client.NOT_FOUND)\n\n if match_player.status != \"active\":\n log.info(f\"player {player_id} in match {match_id} isn't active. Aborting.\")\n abort(http_client.BAD_REQUEST, description=\"Player status must be active, not '%s'\" %\n match_player.status)\n\n match = g.db.query(Match).get(match_id)\n if not match:\n log.info(f\"match {match_id} not found. Aborting.\")\n abort(http_client.NOT_FOUND, description=\"Match not found\")\n\n if match.status == \"completed\":\n log.warning(\"Attempting to remove player %s from battle %s which has already completed\",\n player_id, match_id)\n abort(http_client.BAD_REQUEST,\n description=\"You cannot remove a player from a completed match\")\n\n team_id = match_player.team_id\n\n match_player.status = \"quit\"\n num_seconds = (utcnow() - match_player.join_date).total_seconds()\n match_player.leave_date = utcnow()\n match_player.seconds += num_seconds\n\n g.db.commit()\n\n log.info(\"Player %s has left battle %s\", player_id, match_id)\n log_match_event(match_id, player_id,\n \"gameserver.match.player_left\",\n details={\"team_id\": team_id})\n message_data = {\"event\": \"match_player_left\", \"match_id\": match_id, \"player_id\": player_id}\n current_app.extensions[\"messagebus\"].publish_message(\"match\", message_data)\n return jsonify({\"message\": \"Player has left the battle\"})\n\n\n@endpoints.register\ndef endpoint_info(*args):\n ret = {\n \"active_matches\": url_for(\"matches.active\", _external=True),\n \"matches\": url_for(\"matches.list\", _external=True),\n }\n return ret\n","sub_path":"driftbase/api/matches.py","file_name":"matches.py","file_ext":"py","file_size_in_byte":38064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"407149477","text":"import os\n\ndef playAlert(filename): \n alert = \"%s has finished\" % filename\n os.system(\"say %s\" % alert)\n \n\n# Check if a number is prime. \ndef isPrime(n):\n with open(\"primes.txt\", \"r+\") as f: \n primes = f.read()\n #print primes\n \n primes = primes.split(\" \")\n primes = [int(x) for x in primes]\n \n if n <= primes[-1]: \n if n not in primes: \n return False \n else: \n return True\n else: \n \n '''if n < 2: return False\n if n in (2, 3): return True\n if n % 2 == 0 or n % 3 == 0: return False'''\n maxDivisor = int(n ** 0.5)\n divisor = 5\n while divisor <= maxDivisor:\n if n % divisor == 0 or n % (divisor + 2) == 0:\n return False\n divisor += 6\n return True \n \n# Get all prime numbers up to a given limit. \ndef getPrimes(limit):\n primes = []\n boolNums = [True]*(limit)\n index = 1\n\n for i in xrange(2, limit):\n if boolNums[i] == True:\n primes.append(i)\n for j in xrange(i + 1, len(boolNums)):\n if j % i == 0:\n boolNums[j] = False\n index += 1\n else:\n continue\n \n return primes\n\n\ndef getPrimes2(limit): \n with open(\"primes.txt\", \"r+\") as f: \n primes = f.read()\n #print primes\n \n primes = primes.split(\" \")\n primes = [int(x) for x in primes]\n \n if primes[-1] >= limit: \n primes = [x for x in primes if x <= limit]\n \n else: \n print(\"Your largest prime is %d\" % primes[-1])\n \n '''else: \n boolNums = [True]*(limit)\n for p in primes: \n boolNums = [False for x in boolNums if boolNums.index(x) % p == 0]\n\n for i in xrange(primes[-1], limit): \n if boolNums[i] == True: \n primes.append(i)\n f.write(\"%s \" % i)\n for j in xrange(i + 1, len(boolNums)): \n if j % i == 0: \n boolNums[j] = False''' \n \n return primes \n \n \n \n# Check if a number is palindromic. \ndef isPalindromicNumber(n):\n return str(n) == str(n)[::-1]\n \n# Check if a number is palindromic in base 10 and base 2. \ndef isDecAndBinPalindrome(n):\n if isPalindromicNumber(n) == False: \n return False\n \n bin_n = bin(n)[2:]\n return bin_n == bin_n[::-1]\n \n# Find the product of the digits in a number. \ndef findProduct(digits):\n d = int(digits)\n product = 1\n while d > 0:\n val = d % 10\n product *= val\n d /= 10\n return product\n \n# Get permutations of some set of digits.\ndef getPerms(digits):\n if len(digits) < 1:\n return \"\"\n elif len(digits) == 1:\n return digits\n else:\n perms = []\n first = digits[0]\n rem = digits[1:]\n remPerms = getPerms(rem)\n for i in remPerms:\n for j in range(0, len(i)+1): \n perms.append(placeCharAt(first, j, i))\n\n return perms \n\ndef placeCharAt(char, index, rem):\n return rem[:index] + char + rem[index:]\n\n","sub_path":"HelperFunctions.py","file_name":"HelperFunctions.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"357684224","text":"#!/usr/bin/env python\nfrom deepdive import *\nimport re\n\n@tsv_extractor\n@returns(lambda\n mention_id = \"text\",\n mention_text = \"text\",\n doc_id = \"text\",\n sentence_index\t = \"int\",\n begin_index\t\t = \"int\",\n end_index \t\t = \"int\",\n :[])\ndef extract(\n doc_id = \"text\",\n sentence_index = \"int\",\n sentence_text = \"text\",\n tokens = \"text[]\",\n ):\n \"\"\"\n Finds phrases that are continuous words tagged with PERSON.\n \"\"\"\n # generate a mention identifier\n num_tokens = len(tokens)\n list_of_stopwords = ['target', 'targets', 'Target', 'Targets','The', 'the', 'member', 'members', 'Member', 'Members']\n list_of_targets = re.findall(r'(?:[A-Z]{1}[a-z]+_?\\s?)+and?\\s?(?:[A-Z]{1}[a-z]+_?\\s?)?targets?', sentence_text) + re.findall(r'(?:[A-Z]{1}[a-z]+_?\\s?)+target', sentence_text) + re.findall(r'targets\\s(?:\\w+_?\\s?)?,?\\s?(?:\\w+_?\\s?)?and?\\s(?:\\w+_?\\s?)?', sentence_text) + re.findall(r'targets?\\s(?:\\w+_?\\s?){ 1 }', sentence_text)\n list_of_targets += re.findall(r'Targets\\s(?:\\w+_?\\s?)?,?\\s?(?:\\w+_?\\s?)?,?\\s?and?(?:\\w+_?\\s?)?', sentence_text) + re.findall(r'(?:[A-Z]{1}[a-z]+_?\\.?\\s?)+member', sentence_text)\n refined_list_of_targets = list()\n for string in list_of_targets:\n \tsplit_string = string.split(\",\")\n \trefined_list_of_targets += ( i for i in split_string)\n for target_str in refined_list_of_targets:\n \ttarget_list = target_str.split()\n \tfor target in target_list:\n \t\tif target in list_of_stopwords:\n \t\t\ttarget_list.remove(target)\n \ttarget_str = \" \".join(target_list)\n \tsplit_by_and = target_str.split(\" and \")\n \tfor item in split_by_and:\n \t\tif item != \"and\":\n\t\t mention_text = item\n\t\t begin_index = 1\n\t\t end_index = 1\n\t\t target_split = item.split()\n\t\t begin_index = tokens.index(target_split[0])\n\t\t if len(target_split) == 1:\n\t\t \tend_index = begin_index\n\t\t else:\n\t\t \tnum_of_chunks = len(target_split)\n\t\t \tend_index = begin_index + num_of_chunks - 1\n\t\t mention_id = \"%s_%d_%d_%d\" % (doc_id, sentence_index, begin_index, end_index)\n\t\t # Output a tuple for each TARGET phrase\n\t\t yield [\n\t\t mention_id,\n\t\t mention_text,\n\t\t doc_id,\n\t\t sentence_index,\n\t\t begin_index,\n\t\t end_index,\n\t\t ]","sub_path":"app/planetaryir/udf/map_target_mention.py","file_name":"map_target_mention.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"347200810","text":"import datetime as dt\n\nimport pytest\n\nimport experiment_api.utils as utils\n# 3rd Party Libraries\n# Library being tested\n\n\ndef test_ImageType():\n vals = utils.ImageType.__members__\n assert 'ALL' in vals\n assert 'QUERY' in vals\n assert 'TEST' in vals\n assert 'TRAIN' in vals\n\n\ndef test_get_index_of_tuple():\n TEST_LIST = [\n (0, 'Who', 'John'),\n (1, 'What', 'Pizza'),\n (2, 'Where', 'Little Caesar'),\n (3, 'When', 'Noon'),\n (4, 'How', 'Eat'),\n (5, None, None),\n ]\n\n # Test that we can find ints, strings, and Nones\n assert 1 == utils.get_index_of_tuple(TEST_LIST, 0, 0)\n assert 2 == utils.get_index_of_tuple(TEST_LIST, 1, 'What')\n assert 6 == utils.get_index_of_tuple(TEST_LIST, 1, None)\n\n # Test that we report the last position if we don't find an answer\n assert len(TEST_LIST) == utils.get_index_of_tuple(\n TEST_LIST, 0, 'NOT THERE')\n\n\ndef test_get_numeric():\n TEST_STRINGS = (\n ('c002.jpg', '002'),\n ('_012_', '012'),\n )\n\n for test_input, answer in TEST_STRINGS:\n assert answer == utils.get_numeric(test_input)\n\n\ndef test_should_drop():\n # Never drop\n assert utils.should_drop(1.) is True\n # Always drop\n assert utils.should_drop(0.) is False\n\n\ndef test_read_camera_id():\n TEST_STRINGS = (\n ('0001_c001_00030600_0.jpg', 1),\n ('0011_c010_00084305_1.jpg', 10),\n ('0811_c011_00184305_1.jpg', 11),\n )\n\n for test_input, answer in TEST_STRINGS:\n assert answer == utils.read_camera_id(test_input)\n\n\ndef test_read_car_id():\n TEST_STRINGS = (\n ('0001_c001_00030600_0.jpg', 1),\n ('0011_c010_00084305_1.jpg', 11),\n ('0811_c011_00184305_1.jpg', 811),\n )\n\n for test_input, answer in TEST_STRINGS:\n assert answer == utils.read_car_id(test_input)\n\n\ndef test_read_timestamp():\n TEST_STRINGS = (\n ('0001_c001_00030600_0.jpg', dt.datetime.fromtimestamp(30600)),\n ('0011_c010_00084305_1.jpg', dt.datetime.fromtimestamp(84305)),\n ('0811_c011_00184305_1.jpg', dt.datetime.fromtimestamp(184305)),\n )\n\n for test_input, answer in TEST_STRINGS:\n assert answer == utils.read_timestamp(test_input)\n","sub_path":"testci/test_experiment_utils.py","file_name":"test_experiment_utils.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611253603","text":"from enum import unique\nimport discord\nfrom discord import message\nfrom discord.ext import commands\nfrom discord import utils\nimport configparser\nimport validators\nimport peewee\nimport os\nfrom validators.url import url\nimport datetime\nimport markovify\n\n\nTOKEN = os.getenv(\"DISCORD_TOKEN\")\nbot = commands.Bot(command_prefix='$')\n\nconfig = configparser.ConfigParser()\nconfig.read(\"cfg.ini\")\n\nBLACKLIST = config.get(\"lists\", \"channel_blacklist\")\nWHITELIST = config.get(\"lists\", \"user_whitelist\")\n\n\n\n#Database stuff\ndb = peewee.SqliteDatabase(\"cordbooks.db\")\n\nclass BaseModel(peewee.Model):\n class Meta:\n database = db\n \nclass User(BaseModel):\n username = peewee.CharField(unique=False)\n id = peewee.CharField(unique=True)\n\nclass Message(BaseModel):\n user = peewee.ForeignKeyField(User, backref='messages')\n id = peewee.CharField(unique=True)\n content = peewee.TextField()\n created_date = peewee.DateTimeField(default=datetime.datetime.now)\n\n\n@bot.command()\nasync def fetch(ctx, member: discord.Member):\n if ctx.author.id == ctx.me.id:\n return\n \n #Scraping history\n messages = await ctx.channel.history(limit=None).flatten()\n for n in messages:\n if n.content == '' or validators.url(n.content):\n continue\n \n if '$fetch' in n.content or '$sus' in n.content:\n continue\n \n if n.author.id == member.id:\n try:\n user = User.get(User.id == n.author.id)\n except User.DoesNotExist:\n user = User.create(id=n.author.id, username=n.author)\n \n try:\n Message.create(user=user, id=n.id, content=n.content, created_date=n.created_at)\n print(n.author, n.content)\n except:\n pass\n \n print(\"Fetch successfull\")\n \n \n@bot.command()\nasync def sus(ctx, member: discord.Member):\n if ctx.author.id == ctx.me.id:\n return\n \n id = member.id\n \n list = []\n sep = \"\\n\"\n \n try:\n user = User.get(id=id)\n for message in user.messages:\n list.append(message.content)\n except:\n ctx.send(\"User has typed any messages yet\")\n return\n \n markovText = sep.join(list)\n \n text_model = markovify.NewlineText(markovText)\n \n #Handling webhooks\n webhooks = await ctx.channel.webhooks()\n webhook = utils.get(webhooks, name = \"sus\")\n if webhook == None:\n webhook = await ctx.channel.create_webhook(name = \"sus\")\n \n #Handling black-/whitelists \n #if ctx.channel.name in BLACKLIST or ctx.author.name not in USER_WHITELIST:\n # return\n #Sending message \n \n msg = None\n while msg is None:\n msg = text_model.make_short_sentence(280)\n \n if msg is None:\n await webhook.send(\"Failed to generate text, try again\", username = member.name, avatar_url = member.avatar_url)\n return\n \n await webhook.send(msg, username = member.name, avatar_url = member.avatar_url)\n print(msg)\n\n@bot.command()\nasync def whitelist(ctx, member: discord.Member):\n await ctx.send(\"This command isnt ready yet!\")\n return\n if ctx.author.id == ctx.me.id:\n return\n \n if member == None:\n return\n \n newList = config.get(\"lists\", \"user_whitelist\")\n print(newList)\n \n if newList :\n List = str(member.id)\n else:\n List = newList + \",\" + str(member.id)\n \n config[\"lists\"][\"user_whitelist\"] = List \n \n updateList()\n \n\ndef updateList():\n with open(\"cfg.ini\", \"w\") as configfile:\n config.write(configfile)\n\n\ndb.connect()\ndb.create_tables([User, Message])\nbot.run(TOKEN)\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"425482982","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 18-6-7 上午10:11\n\n@author: ronghuaiyang\n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\n\nclass FocalLoss(nn.Module):\n \"\"\"\n https://zhuanlan.zhihu.com/p/49981234\n Focal Loss解决2个问题:\n 1、解决样本不均衡问题,用alpha来平衡\n 2、解决样本难分/易分样本的调节,用gamma来平衡\n FL(p)=-alpha (1-p)^gamma * log(p)\n \"\"\"\n\n def __init__(self, gamma=0, eps=1e-7):\n super(FocalLoss, self).__init__()\n self.gamma = gamma\n self.eps = eps\n self.ce = torch.nn.CrossEntropyLoss()\n\n def forward(self, input, target):\n # ce = -log(p) 参:https://zhuanlan.zhihu.com/p/27223959\n ce = self.ce(input, target)\n\n p = torch.exp(-ce) # p = e ^ (-ce)\n\n # 参:https://blog.csdn.net/u014311125/article/details/109470137\n # FL(p)=-alpha (1-p)^gamma * log(p):\n # = alpha (1-p)^gamma * (-log(p))\n # = alpha (1-p)^gamma * ce\n # alpha=1\n # = (1-p)^gamma * ce\n # 注意最前面的负号没有了,隐含到ce中了,因为ce=-log(p)\n loss = (1 - p) ** self.gamma * ce\n\n return loss.mean()","sub_path":"models/focal_loss.py","file_name":"focal_loss.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"411032167","text":"import hashlib\nimport requests\nimport uuid\n\nimport sys\n\n\n\ndef load_id():\n text_file = open('my_id.txt', 'r')\n my_id = text_file.read().split(',')\n text_file.close()\n return my_id\n\n\ndef proof_of_work(last_block_string):\n \"\"\"\n Simple Proof of Work Algorithm\n Find a number p such that hash(last_block_string, p) contains 6 leading\n zeroes\n \"\"\"\n proof = 0\n\n while valid_proof(last_block_string, proof) is False:\n proof += 1\n \n print('Sending to server....')\n return proof\n\ndef valid_proof(last_block_string, proof):\n \"\"\"\n Validates the Proof: Does hash(block_string, proof) contain 6\n leading zeroes?\n \"\"\"\n #String to hash\n guess = f'{last_block_string}{proof}'.encode()\n #Hash string\n guess_hash = hashlib.sha256(guess).hexdigest()\n #check for 6 leading 0s\n beg = guess_hash[:6]\n return beg == '000000'\n\n\n\n\nif __name__ == '__main__':\n # What node are we interacting with?\n if len(sys.argv) > 1:\n node = sys.argv[1]\n else:\n node = \"http://localhost:5000\"\n\n if load_id()[0]:\n userid = load_id()[0]\n else:\n print(\"Miner ID not found, creating Miner ID ...\")\n f = open(\"my_id.txt\", \"w\")\n userid = str(uuid.uuid1()).replace('-', '')\n print(\"New Miner ID: \" + userid)\n f.write(userid+','+str(0))\n f.close()\n print('Miner ID: ', userid)\n\n coins_mined = int(load_id()[1])\n # Run forever until interrupted\n while True:\n r = requests.get(url = node +\"/last_block_string\")\n data = r.json()\n\n last_block_string = data['last_block_string']['previous_hash']\n\n\n new_proof = proof_of_work(last_block_string)\n\n proof_data = {\n \"proof\": new_proof,\n \"id\": userid\n }\n\n r = requests.post(url=node + \"/mine\", json=proof_data)\n print(r.json()['message'])\n\n if r.json()['message'] == 'New Block Forged':\n coins_mined += 1\n print('Coins Mined: ', coins_mined)\n f = open(\"my_id.txt\", \"w\")\n f.write(userid+','+str(coins_mined))\n f.close()\n \n","sub_path":"credit_for_mining_p/miner.py","file_name":"miner.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"12379367","text":"from optparse import OptionParser\nfrom pydub import AudioSegment\nimport librosa\nimport madmom\nimport numpy as np\nimport sys\nimport os\nimport random\nimport string\n\ndef convert(inputFile, insertFile, outputFile, options):\n\n wavFileName = 'temp_' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=6)) + '.wav'\n\n track = AudioSegment.from_mp3(inputFile)\n insert = AudioSegment.from_mp3(insertFile)\n track.export(wavFileName, format='wav')\n\n proc = madmom.features.beats.DBNBeatTrackingProcessor(fps=100)\n act = madmom.features.beats.RNNBeatProcessor()(wavFileName)\n\n os.remove(wavFileName)\n\n beat_times = proc(act)\n\n timelist = np.insert(beat_times, 0, 0)\n combined = AudioSegment.empty()\n\n sequenceLength = int(options.sequence)\n indices = list(map(lambda x: int(x), options.index.split(',')))\n\n for i in range(0, len(timelist)-1):\n\n start = int(timelist[i] * 1000)\n end = int(timelist[i+1] * 1000)\n\n splitLen = end - start\n\n insertTrack = insert[:splitLen] if len(insert) < splitLen else insert + AudioSegment.silent(duration = splitLen - len(insert))\n\n combined += insertTrack if i % sequenceLength in indices else track[start:end]\n\n combined.export(outputFile, format='mp3')\n\ndef main():\n parser = OptionParser(usage='usage: %s [options] ' % sys.argv[0])\n parser.add_option('-s', '--sequence', default=2, help='beat sequence length, default = 2')\n parser.add_option('-i', '--index', default=\"0\", help='beat indices to replace, default = 0')\n\n (options, args) = parser.parse_args()\n if len(args) < 2:\n parser.print_help()\n return -1\n\n fileName = args[0]\n insert = args[1]\n outputFile = ''.join(fileName.split('.')[:-1]) + '_insert.mp3'\n\n convert(fileName, insert, outputFile, options)\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as e:\n print (e)\n","sub_path":"insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"81174561","text":"#!/usr/bin/python\n# ***************************************************************************\n# * @File: importsJE.py\n# *\n# * @Brief: imports JetEnergy datasets in panda dataframe for tensor flow\n# *\n# * @Author: Milan Ganai\n# * \n# * @Creation: Dec 2017\n# ***************************************************************************\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\n\nimport numpy as np\nimport tensorflow as tf\nimport glob\nimport os\n\nsess = tf.InteractiveSession()\n\ndatasetPath = os.getcwd() + '/../datasets.gold'\ntrainData = datasetPath+'/data/jet*.csv'\npredictData = datasetPath+'/eval/jet*.csv'\n\ntry:\n import pandas as pd # pylint: disable=g-import-not-at-top\nexcept ImportError:\n pass\n\n# Order is important for the csv-readers, so we use an OrderedDict here.\ndefaults = collections.OrderedDict([\n (\"jpt_hard\", [0.0]),\n (\"jpt_hard_m\", [0.0]),\n (\"sub_hard\", [0.0]),\n (\"sub_hard_m\", [0.0]),\n (\"jpt_full\", [0.0]),\n (\"jpt_full_m\", [0.0]),\n (\"sum_pv\", [0.0]),\n (\"sum_pu\", [0.0]),\n (\"eta\", [0.0]),\n (\"phi\", [0.0]),\n (\"area\", [0.0]),\n (\"rho\", [0.0]),\n (\"sigma\", [0.0]),\n (\"rho_m\", [0.0]),\n (\"sigma_m\", [0.0]),\n (\"R\", [0.0]),\n (\"n_pv\", [0.0]),\n (\"n_pu\", [0.0])\n]) # pyformat: disable\n\n\ntypes = collections.OrderedDict((key, type(value[0]))\n for key, value in defaults.items())\n\n\ndef set_dpath(dpath):\n global datasetPath, trainData, predictData\n datasetPath = dpath\n trainData = datasetPath+'/data/jet*.csv'\n predictData = datasetPath+'/eval/jet*.csv'\n\ndef _get_importsJE():\n paths = glob.glob(trainData)\n if len(paths) == 0:\n print('No data found in ' + trainData)\n sys.exit(1)\n return paths\n\n\ndef dataset(y_name=\"jpt_hard\", train_fraction=0.7):\n \"\"\"Load the importsJE data as a (train,test) pair of `Dataset`.\n\n Each dataset generates (features_dict, label) pairs.\n\n Args:\n y_name: The name of the column to use as the label.\n train_fraction: A float, the fraction of data to use for training. The\n remainder will be used for evaluation.\n Returns:\n A (train,test) pair of `Datasets`\n \"\"\"\n # Download and cache the data\n path = _get_importsJE()\n\n # Define how the lines of the file should be parsed\n def decode_line(line):\n \"\"\"Convert a csv line into a (features_dict,label) pair.\"\"\"\n\n\n # Decode the line to a tuple of items based on the types of\n # csv_header.values().\n items = tf.decode_csv(line, list(defaults.values()))\n\n\n\n # Convert the keys and items to a dict.\n pairs = zip(defaults.keys(), items)\n features_dict = dict(pairs)\n\n # Remove the label from the features_dict\n label = features_dict.pop(y_name)\n\n return features_dict, label\n\n def has_no_question_marks(line):\n \"\"\"Returns True if the line of text has no question marks.\"\"\"\n # split the line into an array of characters\n chars = tf.string_split(line[tf.newaxis], \"\").values\n # for each character check if it is a question mark\n is_question = tf.equal(chars, \"j\") #hack to remove the header\n any_question = tf.reduce_any(is_question)\n no_question = ~any_question\n\n return no_question\n\n def in_training_set(line):\n \"\"\"Returns a boolean tensor, true if the line is in the training set.\"\"\"\n # If you randomly split the dataset you won't get the same split in both\n # sessions if you stop and restart training later. Also a simple\n # random split won't work with a dataset that's too big to `.cache()` as\n # we are doing here.\n num_buckets = 1000000\n bucket_id = tf.string_to_hash_bucket_fast(line, num_buckets)\n # Use the hash bucket id as a random number that's deterministic per example\n return bucket_id < int(train_fraction * num_buckets)\n\n def in_test_set(line):\n \"\"\"Returns a boolean tensor, true if the line is in the training set.\"\"\"\n # Items not in the training set are in the test set.\n # This line must use `~` instead of `not` beacuse `not` only works on python\n # booleans but we are dealing with symbolic tensors.\n return ~in_training_set(line)\n\n base_dataset = (tf.contrib.data\n # Get the lines from the file.\n .TextLineDataset(path)\n # drop lines with question marks.\n .filter(has_no_question_marks))\n\n\n\n train = (base_dataset\n # Take only the training-set lines.\n .filter(in_training_set)\n # Cache data so you only read the file once.\n .cache()\n # Decode each line into a (features_dict, label) pair.\n .map(decode_line))\n\n # Do the same for the test-set.\n test = (base_dataset.filter(in_test_set).cache().map(decode_line))\n\n return train, test\n\n\ndef predict_data():\n \"\"\"Load the importsJE data as a pd.DataFrame.\"\"\"\n # Download and cache the data\n datapath = predictData\n\n allFiles = glob.glob(datapath)\n if len(allFiles) == 0:\n print('No eval data found in ' + predictData)\n sys.exit(1)\n list_ = []\n for file_ in allFiles:\n df_ = pd.read_csv(file_, header=0, names=types.keys(), dtype=types, na_values=\"?\")\n list_.append(df_)\n df = pd.concat(list_,ignore_index=True)\n\n\n # Load it into a pandas dataframe\n\n outs = ['jpt_hard','jpt_hard_m','sub_hard','sub_hard_m']\n nodrops = ['jpt_full','jpt_full_m']\n out_df = pd.DataFrame()\n for k in outs+nodrops:\n out_df[k] = df[k]\n if k not in nodrops:\n\t df = df.drop(k,1)\n \n # print out\n '''\n for k in out_df.keys():\n print(k,out_df[k],\"\\n\")\n for i in range(10):\n print(out_df['jpt_hard'][i],out_df['sub_hard'][i])\n '''\n return df,out_df\n\n\n","sub_path":"tensor/importsJE.py","file_name":"importsJE.py","file_ext":"py","file_size_in_byte":5700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"426181847","text":"import turtle\n\ns = turtle.Screen() \n\nt = turtle.Turtle()\n\n\n#s.setup(500,500)\ns.setworldcoordinates(-200,0,200,400)\nt.setheading(90)\ni=0\n\nx=y=0\nL=1\nangle=75\n\nt.speed(0)\n\ndef draw(len):\n if(len>5):\n t.fd(len)\n t.rt(angle)\n draw(len*0.67)\n\n t.rt(-2*angle)\n draw(len*0.67)\n\n t.rt(angle)\n t.backward(len)\n\n \n\ndraw(100)\nturtle.done()","sub_path":"week1 and extra/factorial tree.py","file_name":"factorial tree.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"228467314","text":"import queue\nimport asyncio\n\nimport pytest\n\nimport sockio.aio\nimport sockio.sio\nimport sockio.py2\n\n\nIDN_REQ, IDN_REP = b'*idn?\\n', b'ACME, bla ble ble, 1234, 5678\\n'\nWRONG_REQ, WRONG_REP = b'wrong question\\n', b'ERROR: unknown command\\n'\n\n\ndef server_coro():\n\n async def cb(reader, writer):\n try:\n while True:\n data = await reader.readline()\n if data.lower() == IDN_REQ:\n msg = IDN_REP\n elif data.lower().startswith(b'data?'):\n n = int(data.strip().split(b' ', 1)[-1])\n for i in range(n):\n await asyncio.sleep(0.05)\n writer.write(b'1.2345 5.4321 12345.54321\\n')\n await writer.drain()\n writer.close()\n await writer.wait_closed()\n return\n else:\n msg = WRONG_REP\n # add 2ms delay\n await asyncio.sleep(0.002)\n writer.write(msg)\n await writer.drain()\n except ConnectionResetError:\n pass\n\n return asyncio.start_server(cb, host='0')\n\n\n@pytest.fixture()\nasync def aio_server():\n server = await server_coro()\n asyncio.create_task(server.serve_forever())\n yield server\n server.close()\n await server.wait_closed()\n assert not server.is_serving()\n\n\n@pytest.fixture\nasync def aio_tcp(aio_server):\n addr = aio_server.sockets[0].getsockname()\n sock = sockio.aio.TCP(*addr)\n yield sock\n await sock.close()\n\n\n@pytest.fixture()\ndef sio_server():\n event_loop = sockio.sio.DefaultEventLoop\n channel = queue.Queue()\n async def serve_forever():\n server = await server_coro()\n channel.put(server)\n await server.serve_forever()\n event_loop.run_coroutine(serve_forever())\n server = event_loop.proxy(channel.get())\n yield server\n server.close()\n\n\n@pytest.fixture\ndef sio_tcp(sio_server):\n addr = sio_server.sockets[0].getsockname()\n sock = sockio.sio.TCP(*addr)\n yield sock\n sock.close()\n\n\n@pytest.fixture\ndef py2_tcp(sio_server):\n addr = sio_server.sockets[0].getsockname()\n sock = sockio.py2.TCP(*addr)\n yield sock\n sock.close()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"346665498","text":"import bz2\nimport zlib\nimport wandio.file\n\n\nclass CompressedReader(wandio.file.GenericReader):\n\n BUFLEN = 4096\n\n def __init__(self, child_reader, flush_dc):\n self.child_reader = child_reader\n self.flush_dc = flush_dc\n self.dc = None\n self.c_buf = b\"\"\n self.buf = b\"\"\n self.eof = False\n self._refill()\n super(CompressedReader, self).__init__(child_reader)\n\n def _get_dc(self):\n raise NotImplementedError\n\n def _refill(self):\n if self.eof:\n return\n # keep reading from the child reader until we've decompressed\n # enough data to fill our buffer\n while len(self.c_buf) or len(self.buf) < self.BUFLEN:\n if not len(self.c_buf):\n # fill our buffer with compressed data\n self.c_buf = self.child_reader.read(self.BUFLEN)\n if len(self.c_buf) < self.BUFLEN:\n self.eof = True\n # pass the compressed data to the decompressor, and get back\n # some decompressed data\n if self.dc is None:\n self.dc = self._get_dc()\n # feed in the data in c_buf to decompress it\n self.buf += self.dc.decompress(self.c_buf)\n # if we are EOF on the child reader, then flush the decompressor\n if self.eof and self.flush_dc:\n self.buf += self.dc.flush()\n self.c_buf = self.dc.unused_data\n if len(self.c_buf):\n # we have leftover data after compression ended,\n # so now we need a new decompressor\n if self.flush_dc:\n self.buf += self.dc.flush()\n self.dc = None\n # only heed the eof once we've emptied c_buf\n if not len(self.c_buf) and self.eof:\n break\n\n def read(self, size=None):\n res = b\"\"\n while ((not self.eof) or len(self.buf)) and (size is None or len(res) < size):\n if not len(self.buf):\n self._refill()\n toread = size-len(res) if size is not None else len(self.buf)\n res += self.buf[0:toread]\n self.buf = self.buf[toread:]\n # TODO: remove these asserts\n assert(size is None or len(res) <= size)\n assert(size is None or len(res) == size or len(self.buf) == 0)\n return res\n\n def __next__(self):\n line = self.readline()\n if not line:\n assert(not len(self.buf) and self.eof)\n raise StopIteration\n return line\n\n def readline(self):\n res = b\"\"\n while not len(res) or not res.endswith(b\"\\n\"):\n idx = self.buf.find(b\"\\n\")\n if idx == -1:\n res += self.buf\n self.buf = b\"\"\n self._refill()\n else:\n res += self.buf[0:idx+1]\n self.buf = self.buf[idx+1:]\n if not len(self.buf) and self.eof:\n break\n if not len(res) and not len(self.buf) and self.eof:\n return None\n return res.decode(\"utf-8\")\n\n\nclass CompressedWriter(wandio.file.GenericWriter):\n\n def __init__(self, compressor, child_writer):\n self.compressor = compressor\n self.child_writer = child_writer\n super(CompressedWriter, self).__init__(child_writer)\n\n def flush(self):\n cd = self.compressor.flush()\n self.fh.write(cd)\n self.fh.flush()\n\n def write(self, data):\n if isinstance(data, str):\n data = data.encode()\n cd = self.compressor.compress(data)\n # cd is partial compressed data\n self.fh.write(cd)\n\n def writelines(self, lines):\n for line in lines:\n self.write(line)\n\n def close(self):\n self.flush()\n self.fh.close()\n\n\nclass GzipReader(CompressedReader):\n\n def __init__(self, child):\n super(GzipReader, self).__init__(child, flush_dc=True)\n\n def _get_dc(self):\n return zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n\nclass GzipWriter(CompressedWriter):\n\n def __init__(self, child):\n compressor = zlib.compressobj(-1, zlib.DEFLATED, 16+zlib.MAX_WBITS)\n super(GzipWriter, self).__init__(compressor, child)\n\n\nclass BzipReader(CompressedReader):\n\n def __init__(self, child):\n super(BzipReader, self).__init__(child, flush_dc=False)\n\n def _get_dc(self):\n return bz2.BZ2Decompressor()\n\n\nclass BzipWriter(CompressedWriter):\n\n def __init__(self, child):\n compressor = bz2.BZ2Compressor()\n super(BzipWriter, self).__init__(compressor, child)\n","sub_path":"wandio/compressed.py","file_name":"compressed.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"41880427","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n__author__ = 'Turing Wong'\n__date__='2018-7-22'\n__desc__='Save the content to database!'\n\nimport getliteratures\nimport orm\n\ndef saveLiteratures():\n literature_id = 0\n while True:\n #获取页面内容\n soup = getliteratures.Requester.getHtml()\n print(\"总共%d页\" %getliteratures.Requester.page_all)\n #解析页面内容,获得诗文\n literatures = getliteratures.Analysiser.getLiterature(soup)\n for literature in literatures:\n current_literature = orm.Base_literatures(literature_id=literature_id, literature_name=literature.title,literature_author=literature.author,literature_content=literature.content,literature_likes=literature.good,literature_tag=literature.tag,literature_type=literature.type_)\n current_literature.save()\n literature_id +=1\n if getliteratures.Requester.page_num > getliteratures.Requester.page_all:\n print(\"All page done!\")\n break;\n \nsaveLiteratures()\n","sub_path":"saveliteratures.py","file_name":"saveliteratures.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"103507288","text":"import torch\n\nimport matplotlib.pyplot as plt\nimport itertools\nimport os\n\nfrom model.cdcgan import Generator\nfrom config import get_config\n\n# Device configuration\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\nclass Tester(object):\n # initializer\n def __init__(self, config, weight_path, out_path):\n self.config = config\n\n self.nz = config.nz\n self.ngf = config.ngf\n self.ndf = config.ndf\n self.nch = config.nch\n self.ncls = config.n_classes\n\n self.g_path = weight_path + \"generator.pth\"\n\n self.out_path = out_path\n\n self.load_net()\n\n # load trained network\n def load_net(self):\n self.g = Generator(self.nz, self.ngf, self.nch, self.ncls)\n self.g.load_state_dict(torch.load(self.g_path, map_location=lambda storage, loc: storage))\n self.g = self.g.to(device)\n self.g.eval() # fix parameters\n\n # generate test result images\n def test(self, nsamples):\n # fixed noise & label\n temp_z = torch.randn(nsamples, self.nz)\n fixed_z = temp_z\n fixed_y = torch.zeros(nsamples, 1)\n\n for i in range(self.ncls-1):\n fixed_z = torch.cat([fixed_z, temp_z], 0)\n temp_y = torch.ones(nsamples, 1) + i\n fixed_y = torch.cat([fixed_y, temp_y], 0)\n\n fixed_z = fixed_z.view(-1, self.nz, 1, 1)\n fixed_y_label = torch.zeros(nsamples*self.ncls, self.ncls)\n fixed_y_label.scatter_(1, fixed_y.type(torch.LongTensor), 1)\n fixed_y_label = fixed_y_label.view(-1, self.ncls, 1, 1)\n\n fixed_z = fixed_z.to(device)\n fixed_y_label = fixed_y_label.to(device)\n\n # generate result images\n result_imgs = self.g(fixed_z, fixed_y_label)\n print(result_imgs.shape)\n\n # process image and save\n fig, ax = plt.subplots(self.ncls, nsamples, figsize=(5, 5))\n for i, j in itertools.product(range(self.ncls), range(nsamples)):\n ax[i, j].get_xaxis().set_visible(False)\n ax[i, j].get_yaxis().set_visible(False)\n\n for k in range(nsamples * self.ncls):\n i = k // nsamples\n j = k % nsamples\n ax[i, j].cla()\n ax[i, j].imshow(result_imgs[k, 0].cpu().data.numpy(), cmap='gray')\n\n label = 'Result image'\n fig.text(0.5, 0.04, label, ha='center')\n plt.savefig(self.out_path)\n\nif __name__ == \"__main__\":\n config = get_config()\n\n weight_path = \"D:\\Deep_learning\\Weights\\PG3-study\\GAN\\Cond. DCGAN\\Fashion-MNIST\\\\\"\n\n os.makedirs('test', exist_ok=True)\n\n tester = Tester(config, weight_path, 'test/out.png')\n tester.test(nsamples=15)","sub_path":"GAN/cDCGAN/Fashion-MNIST/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"360615892","text":"import pandas as pd\nfrom transformers import BertTokenizer\nfrom torch.utils.data import TensorDataset, random_split\nimport torch\nimport ast\n\nimport pdb\n\nMAX_LENGTHS = {\n \"sst\": 128,\n \"dbpedia\": 256,\n \"imdb\": 128,\n \"cola\": 128,\n \"agnews\": 256\n}\n\nNUM_LABELS = {\n \"sst\": 2,\n \"dbpedia\": 10,\n \"imdb\": 2,\n \"cola\": 2,\n \"agnews\": 4\n}\n\n\nclass DataSet():\n def __init__(self, cfg):\n self.cfg = cfg\n self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)\n\n def preprocess(self, df):\n sentences = df.sentence.values\n labels = df.label.values\n\n # Tokenize all of the sentences and map the tokens to thier word IDs. \n input_ids = []\n attention_masks = []\n segment_ids = []\n num_tokens = []\n # For every sentence...\n for sent in sentences:\n # `encode_plus` will:\n # (1) Tokenize the sentence.\n # (2) Prepend the `[CLS]` token to the start.\n # (3) Append the `[SEP]` token to the end.\n # (4) Map tokens to their IDs.\n # (5) Pad or truncate the sentence to `max_length`\n # (6) Create attention masks for [PAD] tokens.\n \n max_len = MAX_LENGTHS[self.cfg.task]\n\n tokens = self.tokenizer.tokenize(sent)\n if len(tokens) > max_len - 2:\n tokens = tokens[-(max_len - 2):]\n\n # pad all tokens to the same length using UNS token\n\n #max_sent_length = 66\n #paddings = max_sent_length - 2 - len(tokens)\n \n #for i in range(0, paddings):\n # unused_token = '[unused0]'\n # tokens.append(unused_token)\n\n encoded_dict = self.tokenizer.encode_plus(\n tokens, # Sentence to encode.\n add_special_tokens = True, # Add '[CLS]' and '[SEP]'\n max_length = max_len, # Pad & truncate all sentences.\n pad_to_max_length = True,\n return_attention_mask = True, # Construct attn. masks.\n return_tensors = 'pt', # Return pytorch tensors.\n is_pretokenized = True\n )\n\n\n input_ids.append(encoded_dict['input_ids'])\n attention_masks.append(encoded_dict['attention_mask'])\n segment_ids.append(encoded_dict['token_type_ids'])\n num_tokens.append(len(tokens) + 2)\n\n input_ids = torch.cat(input_ids, dim=0)\n attention_masks = torch.cat(attention_masks, dim=0)\n segment_ids = torch.cat(segment_ids, dim=0)\n labels = torch.tensor(labels)\n num_tokens = torch.tensor(num_tokens)\n\n return input_ids, attention_masks, segment_ids, labels, num_tokens\n\n def sample_dataset(self, df, total):\n if total <= 0:\n return df\n \n num_classes = NUM_LABELS[self.cfg.task]\n per_class = int(total / num_classes)\n\n class_pop = [per_class] * num_classes\n for i in range(0, total % num_classes):\n class_pop[i] += 1\n\n min_label = df['label'].min()\n df_sample = df[df['label'] == min_label - 1]\n\n for i in range(min_label, min_label + num_classes):\n sample_number = class_pop.pop(0)\n df_sub = df[df['label'] == i].sample(sample_number, random_state=self.cfg.data_seed)\n if i == num_classes:\n df_sub['label'] = 0\n df_sample = pd.concat([df_sample, df_sub])\n\n self.reindex(df_sample)\n return df_sample\n\n def retrieve_tensors(self, data, d_type):\n if d_type == 'unsup':\n input_columns = ['ori_input_ids', 'ori_input_mask', 'ori_input_type_ids',\n 'aug_input_ids', 'aug_input_mask', 'aug_input_type_ids']\n tensors = [torch.tensor(data[c].apply(lambda x: ast.literal_eval(x)), dtype=torch.long) for c in input_columns]\n\n ori_num_tokens = []\n aug_num_tokens = []\n\n for ori_inp in tensors[0]:\n num = (ori_inp!=0).sum()\n ori_num_tokens.append(num.item())\n\n for aug_inp in tensors[3]:\n num = (aug_inp!=0).sum()\n aug_num_tokens.append(num.item())\n\n tensors.append(torch.tensor(ori_num_tokens))\n tensors.append(torch.tensor(aug_num_tokens))\n\n else:\n input_columns = ['input_ids', 'input_mask', 'input_type_ids', 'label']\n tensors = [torch.tensor(data[c].apply(lambda x: ast.literal_eval(x)), dtype=torch.long) \\\n for c in input_columns[:-1]]\n tensors.append(torch.tensor(data[input_columns[-1]], dtype=torch.long))\n\n num_tokens = []\n for inp in tensors[0]:\n num = (inp!=0).sum()\n num_tokens.append(num.item())\n\n tensors.append(torch.tensor(num_tokens))\n\n return tensors\n\n def swap_binary_label(self, df):\n df['label'].replace(0, \"1\", inplace=True)\n df['label'].replace(1, 0, inplace=True)\n df['label'].replace(\"1\", 1, inplace=True)\n\n def reindex(self, df):\n new_index = range(df.shape[0])\n new_index = pd.Series(new_index)\n df.set_index([new_index], inplace=True)\n\n def get_dataset(self):\n # Load the dataset into a pandas dataframe.\n df_unsup = None\n\n if self.cfg.task == \"sst\":\n df_train = pd.read_csv(\"./SST-2/train.tsv\", delimiter='\\t', header=None, names=['sentence', 'label']).iloc[1:]\n df_dev = pd.read_csv(\"./SST-2/dev.tsv\", delimiter='\\t', header=None, names=['sentence', 'label']).iloc[1:]\n \n df_train['label'] = df_train['label'].astype(int)\n df_dev['label'] = df_dev['label'].astype(int)\n elif self.cfg.task == \"dbpedia\":\n df_train = pd.read_csv(\"./dbpedia/train.csv\", header=None, names=['label', 'title', 'sentence']).iloc[1:]\n df_dev = pd.read_csv(\"./dbpedia/test.csv\", header=None, names=['label', 'title', 'sentence']).iloc[1:]\n elif self.cfg.task == \"imdb\":\n df_train = pd.read_csv(\"./imdb/sup_train.csv\", header=None, names=['sentence', 'label']).iloc[1:]\n #if self.cfg.use_prepro:\n # use prepro for unsup and val\n f_dev = open(\"./imdb/imdb_sup_test.txt\", 'r', encoding='utf-8')\n df_dev = pd.read_csv(f_dev, sep='\\t')\n df_dev.rename(columns={\"label_ids\": \"label\"}, inplace=True)\n self.swap_binary_label(df_dev)\n\n if self.cfg.uda_mode:\n f_unsup = open(\"./imdb/imdb_unsup_train.txt\", 'r', encoding='utf-8')\n df_unsup = pd.read_csv(f_unsup, sep='\\t')\n sup_data = 25000\n df_unsup = df_unsup.iloc[sup_data:]\n if self.cfg.unsup_cap > 0:\n df_unsup = df_unsup.sample(self.cfg.unsup_cap, random_state=self.cfg.data_seed)\n\n self.reindex(df_unsup)\n else:\n df_dev = pd.read_csv(\"./imdb/sup_dev.csv\", header=None, names=['sentence', 'label'])\n elif self.cfg.task == 'cola':\n df_train = pd.read_csv(\"./CoLA/train.tsv\", delimiter='\\t', header=None, names=['title', 'label', 'star', 'sentence']).iloc[1:]\n df_dev = pd.read_csv(\"./CoLA/dev.tsv\", delimiter='\\t', header=None, names=['title', 'label', 'star', 'sentence']).iloc[1:]\n\n df_train['label'] = df_train['label'].astype(int)\n df_dev['label'] = df_dev['label'].astype(int)\n elif self.cfg.task == 'agnews':\n df_train = pd.read_csv(\"./agnews/train.csv\", header=None, names=['label', 'title', 'sentence']).iloc[1:]\n df_dev = pd.read_csv(\"./agnews/test.csv\", header=None, names=['label', 'title', 'sentence']).iloc[1:]\n\n\n df_train = self.sample_dataset(df_train, self.cfg.train_cap)\n print('Number of training sentences: {:,}\\n'.format(df_train.shape[0]))\n input_ids_train, attention_masks_train, seg_ids_train, label_ids_train, num_tokens_train = self.preprocess(df_train)\n\n df_dev = self.sample_dataset(df_dev, self.cfg.dev_cap)\n print('Number of dev sentences: {:,}\\n'.format(df_dev.shape[0]))\n\n\n if 'input_ids' in df_dev:\n input_ids_dev, attention_masks_dev, seg_ids_dev, label_ids_dev, num_tokens_dev = self.retrieve_tensors(df_dev, 'sup')\n if self.cfg.uda_mode:\n ori_input_ids, ori_input_mask, ori_seg_ids, aug_input_ids, aug_input_mask, aug_seg_ids, ori_num_tokens, aug_num_tokens = self.retrieve_tensors(df_unsup, 'unsup')\n print('Number of unsup sentences: {:,}\\n'.format(ori_input_ids.shape[0]))\n else:\n input_ids_dev, attention_masks_dev, seg_ids_dev, label_ids_dev, num_tokens_dev = self.preprocess(df_dev)\n\n # Combine the training inputs into a TensorDataset.\n train_dataset = TensorDataset(input_ids_train, seg_ids_train, attention_masks_train, label_ids_train, num_tokens_train)\n val_dataset = TensorDataset(input_ids_dev, seg_ids_dev, attention_masks_dev, label_ids_dev)\n\n unsup_dataset = None\n if self.cfg.uda_mode:\n unsup_dataset = TensorDataset(ori_input_ids, ori_seg_ids, ori_input_mask, aug_input_ids, aug_seg_ids, aug_input_mask, ori_num_tokens, aug_num_tokens)\n\n return train_dataset, val_dataset, unsup_dataset","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":9603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193212900","text":"from matplotlib import cm\r\nfrom skimage.transform import hough_line, hough_line_peaks\r\nfrom skimage import data\r\nfrom skimage import io\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# img = io.imread('trih.bmp')\r\nimg = io.imread('starh.bmp')\r\nimage = np.zeros((img.shape[0], img.shape[1]))\r\nfor y in range(img.shape[1]):\r\n for x in range(img.shape[0]):\r\n if img[x][y][0] == 255:\r\n image[x][y] = 255\r\n\r\nh, theta, d = hough_line(image)\r\n\r\nfig, (ax0, ax1, ax2) = plt.subplots(1, 3)\r\nplt.tight_layout()\r\n\r\nax0.imshow(image, cmap=cm.gray)\r\nax0.set_title('Input image')\r\nax0.set_axis_off()\r\n\r\nax1.imshow(np.log(1 + h), extent=[np.rad2deg(theta[-1]), np.rad2deg(theta[0]), d[-1], d[0]], cmap=cm.gray, aspect=1/1.5)\r\nax1.set_title('Hough transform')\r\nax1.set_xlabel('Angles (degrees)')\r\nax1.set_ylabel('Distance (pixels)')\r\nax1.axis('image')\r\nax1.set_axis_off()\r\n\r\nax2.imshow(image, cmap=cm.gray)\r\nrow1, col1 = image.shape\r\nfor _, angle, dist in zip(*hough_line_peaks(h, theta, d)):\r\n # y0 = int((dist - 0 * np.cos(angle)) / np.sin(angle))\r\n # y1 = int((dist - col1 * np.cos(angle)) / np.sin(angle))\r\n # print(\"---------------------\")\r\n y = []\r\n p0 = (0, 0)\r\n p1 = (0, 0)\r\n first_point = True\r\n for x in range(col1):\r\n yy = int(round((dist - x*np.cos(angle)) / np.sin(angle)))\r\n if first_point:\r\n for i in range(-1, 2):\r\n for j in range(-1, 2):\r\n if x+j < col1 and yy + i < row1 and x+j >= 0 and yy + i >= 0 and image[yy+i][x+j] == 255:\r\n p0 = (x+j, yy+i)\r\n first_point = False\r\n else:\r\n for i in range(-1, 2):\r\n for j in range(-1, 2):\r\n if x+j < col1 and yy + i < row1 and x+j >= 0 and yy + i >= 0 and image[yy+i][x+j] == 255:\r\n p1 = (x+j, yy+i)\r\n y.append(yy)\r\n\r\n ax2.plot([x for x in range(col1)], y, '-g', linewidth=1)\r\n if p0[0] != 0 and p0[1] != 0 and p1[0] != 0 and p1[1] != 0:\r\n ax2.plot((p0[0], p1[0]), (p0[1], p1[1]), '-r', linewidth=2)\r\n \r\n x_wp = p0[0]\r\n y_wp = p1[0]\r\n for x in range(p0[0]+1, p1[0]+1):\r\n yy = int(round((dist - x*np.cos(angle)) / np.sin(angle)))\r\n wp = False\r\n for i in range(-1, 2):\r\n for j in range(-1, 2):\r\n if x+j < col1 and yy + i < row1 and x+j >= 0 and yy + i >= 0 and image[yy+i][x+j] == 255:\r\n x_wp = x + j\r\n y_wp = yy + i\r\n wp = True\r\n break\r\n if wp:\r\n break\r\n\r\n if not wp:\r\n if np.sqrt((x - x_wp)**2 + (yy - y_wp)**2) >= 45:\r\n ax2.plot((x_wp, x), (y_wp, yy), '-k', linewidth=3)\r\n\r\n # удаление линий внутри фигур типа \"звезда\"\r\n fp = True\r\n for x in range(min(p0[0], p1[0]), max(p0[0], p1[0])):\r\n y_x = int(round((dist - x*np.cos(angle)) / np.sin(angle)))\r\n if fp:\r\n xx = x\r\n yy = y_x\r\n fp = False\r\n continue\r\n\r\n wh_p = False\r\n for i in range(-2, 3):\r\n for j in range(-2, 3):\r\n if image[y_x+i][x+j] == 255 and y_x + i != yy and x + j != xx:\r\n xx, yy = x+j, y_x+i\r\n wh_p = True\r\n break\r\n if wh_p:\r\n break\r\n\r\n if wh_p:\r\n if np.sqrt((x - xx)**2 + (y_x - yy)**2) <= 10:\r\n ax2.plot((xx, x), (yy, y_x), '-r', linewidth=3)\r\n \r\n xx = x\r\n yy = y_x\r\n\r\n ax2.plot((0, col1), (y0, y1), '-r', linewidth=2)\r\n ax2.plot((p0[0], p1[0]), (p0[1], p1[1]), '-r', linewidth=3)\r\n\r\nax2.axis((0, col1, row1, 0))\r\nax2.set_title('Detected lines')\r\nax2.set_axis_off()\r\n\r\nplt.show()\r\n","sub_path":"Processing Image/Hough Transform/hough.py","file_name":"hough.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608284160","text":"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"ParquetIOTensor\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow_io.python.ops import io_tensor_ops\nfrom tensorflow_io.python.ops import core_ops\n\n\nclass BaseParquetGraphIOTensor:\n \"\"\"BaseParquetGraphIOTensor\"\"\"\n\n # =============================================================================\n # Constructor (private)\n # =============================================================================\n def __init__(self, filename, component, shape, dtype, internal=False):\n with tf.name_scope(\"BaseParquetGraphIOTensor\"):\n assert internal\n self._filename = filename\n self._component = component\n self._shape = shape\n self._dtype = dtype\n super().__init__()\n\n # =============================================================================\n # Accessors\n # =============================================================================\n\n @property\n def shape(self):\n \"\"\"Returns the `TensorShape` that represents the shape of the tensor.\"\"\"\n return self._shape\n\n @property\n def dtype(self):\n \"\"\"Returns the `dtype` of elements in the tensor.\"\"\"\n return self._dtype\n\n # =============================================================================\n # String Encoding\n # =============================================================================\n def __repr__(self):\n return \"<{}: shape={}, dtype={}>\".format(\n self.__class__.__name__, self.shape, self.dtype\n )\n\n # =============================================================================\n # Tensor Type Conversions\n # =============================================================================\n\n def to_tensor(self):\n \"\"\"Converts this `IOTensor` into a `tf.Tensor`.\n\n Args:\n name: A name prefix for the returned tensors (optional).\n Returns:\n A `Tensor` with value obtained from this `IOTensor`.\n \"\"\"\n return core_ops.io_parquet_readable_read(\n input=self._filename,\n shared=self._filename,\n component=self._component,\n shape=self._shape,\n start=0,\n stop=-1,\n dtype=self._dtype,\n container=\"ParquetIOTensor\",\n )\n\n # =============================================================================\n # Indexing and slicing\n # =============================================================================\n def __getitem__(self, key):\n \"\"\"Returns the specified piece of this IOTensor.\"\"\"\n # always convert to tuple to process\n if not isinstance(key, tuple):\n key = tuple([key])\n # get the start and stop of each element\n indices = [\n (k.start, k.stop) if isinstance(k, slice) else (k, k + 1) for k in key\n ]\n # get the start and stop, and use 0 (start) and -1 (stop) if needed\n indices = list(zip(*indices))\n start = [0 if e is None else e for e in indices[0]]\n stop = [-1 if e is None else e for e in indices[1]]\n\n item = core_ops.io_parquet_readable_read(\n input=self._filename,\n shared=self._filename,\n component=self._component,\n shape=self._shape,\n start=start,\n stop=stop,\n dtype=self._dtype,\n container=\"ParquetIOTensor\",\n )\n\n # in case certain dimension is not slice, then this dimension will need to\n # collapse as `0`, otherwise `:` or `slice(None, None, None)`\n indices = [slice(None) if isinstance(k, slice) else 0 for k in key]\n\n return item.__getitem__(indices)\n\n def __len__(self):\n \"\"\"Returns the total number of items of this IOTensor.\"\"\"\n return self._shape[0]\n\n\nclass ParquetIOTensor(\n io_tensor_ops._CollectionIOTensor\n): # pylint: disable=protected-access\n \"\"\"ParquetIOTensor\"\"\"\n\n # =============================================================================\n # Constructor (private)\n # =============================================================================\n def __init__(self, filename, spec=None, internal=False):\n with tf.name_scope(\"ParquetIOTensor\"):\n columns, shapes, dtypes = core_ops.io_parquet_readable_info(\n filename, shared=filename, container=\"ParquetIOTensor\"\n )\n if tf.executing_eagerly():\n columns = tf.unstack(columns)\n shapes = [\n tf.boolean_mask(shape, tf.math.greater_equal(shape, 0))\n for shape in tf.unstack(shapes)\n ]\n dtypes = [tf.as_dtype(dtype.numpy()) for dtype in tf.unstack(dtypes)]\n entries = [\n tf.TensorSpec(shape, dtype, column)\n for (shape, dtype, column) in zip(shapes, dtypes, columns)\n ]\n else:\n assert spec is not None\n\n entries = spec.items()\n\n def f(column, columns, shapes):\n shape = tf.boolean_mask(shapes, tf.math.equal(columns, column))[0]\n shape = tf.boolean_mask(shape, tf.math.greater_equal(shape, 0))\n return shape\n\n shapes = [f(column, columns, shapes) for column, _ in entries]\n dtypes = [\n entry if isinstance(entry, tf.dtypes.DType) else entry.dtype\n for _, entry in entries\n ]\n columns = [column for column, _ in entries]\n\n entries = [\n tf.TensorSpec(None, dtype, column)\n for (dtype, column) in zip(dtypes, columns)\n ]\n\n def g(entry, shape):\n return BaseParquetGraphIOTensor(\n filename, entry.name, shape, entry.dtype, internal=True\n )\n\n self._columns = columns\n elements = [g(entry, shape) for (entry, shape) in zip(entries, shapes)]\n spec = tuple(entries)\n super().__init__(spec, columns, elements, internal=internal)\n\n # =============================================================================\n # Accessors\n # =============================================================================\n\n @property\n def columns(self):\n \"\"\"The names of columns\"\"\"\n return self._columns\n","sub_path":"tensorflow_io/python/ops/parquet_io_tensor_ops.py","file_name":"parquet_io_tensor_ops.py","file_ext":"py","file_size_in_byte":7137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608706923","text":"from talon import Context, actions, settings\n\nctx = Context()\nctx.matches = r\"\"\"\nmode: user.javascript\nmode: command\nand code.language: javascript\nmode: command\nand code.language: javascript-react\n\"\"\"\n\n@ctx.action_class(\"user\")\nclass user_actions:\n def code_insert_class(name: str):\n result = \"class {} {{}}\".format(\n actions.user.formatted_text(\n name, settings.get(\"user.code_class_name_formatter\")\n )\n )\n\n actions.user.paste(result)\n actions.edit.left()\n actions.key(\"enter\")\n\n def code_insert_function(text: str, selection: str):\n if selection:\n text = text + \"({})\".format(selection)\n else:\n text = text + \"()\"\n\n actions.user.paste(text)\n actions.edit.left()\n\n def code_private_function(text: str):\n \"\"\"Inserts private function declaration\"\"\"\n result = \"function {}\".format(\n actions.user.formatted_text(\n text, settings.get(\"user.code_private_function_formatter\")\n )\n )\n\n actions.user.code_insert_function(result, None)\n\n # def code_private_static_function(text: str):\n # \"\"\"Inserts private static function\"\"\"\n # result = \"private static void {}\".format(\n # actions.user.formatted_text(\n # text, settings.get(\"user.code_private_function_formatter\")\n # )\n # )\n\n # actions.user.code_insert_function(result, None)\n\n def code_protected_function(text: str):\n result = \"function {}\".format(\n actions.user.formatted_text(\n text, settings.get(\"user.code_protected_function_formatter\")\n )\n )\n\n actions.user.code_insert_function(result, None)\n\n # def code_protected_static_function(text: str):\n # result = \"protected static void {}\".format(\n # actions.user.formatted_text(\n # text, settings.get(\"user.code_protected_function_formatter\")\n # )\n # )\n\n # actions.user.code_insert_function(result, None)\n\n def code_public_function(text: str):\n result = \"function {}\".format(\n actions.user.formatted_text(\n text, settings.get(\"user.code_public_function_formatter\")\n )\n )\n\n actions.user.code_insert_function(result, None)\n\n # def code_public_static_function(text: str):\n # result = \"public static void {}\".format(\n # actions.user.formatted_text(\n # text, settings.get(\"user.code_public_function_formatter\")\n # )\n # )\n\n # actions.user.code_insert_function(result, None)\n\n","sub_path":"lang/javascript/javascript.py","file_name":"javascript.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"249080603","text":"import os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\ndiscord_bot_name=\"bs_test\"\ndiscord_client_id = \"650796075887624205\"\ndiscord_client_secret = \"4XLvzF12eQL0Vb-hLgucsIhX2EoYJZbC\"\ndiscord_token = os.environ['DISCORD_TOKEN']\ndiscord_guild = \"https://discord.gg/zuPbPVf\"\nGOOGLE_SEARCH_API_KEY = os.environ['GOOGLE_API_KEY']\n\n\nGOOGLE_API = \"https://www.googleapis.com/customsearch/v1?key={}&cx=000637338422175236148:qau5q9golx0\".format(GOOGLE_SEARCH_API_KEY)\n\nREDIS_URL=\"redis://h:p8f8d8c871ce1bd2017ac0a29d51c3b03b61f94ef0e066ca38550e5c5e09f4b2e@ec2-3-234-194-184.compute-1.amazonaws.com:10349\"\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608742758","text":"import logging\nimport sys\nimport os\nimport re\n\nlogging.basicConfig(format=u'%(filename)s[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s',\n level=logging.DEBUG)\n\n\ndef get_win_doc_folder():\n \"\"\"\n\n :return:\n \"\"\"\n import ctypes.wintypes\n\n csidl_personal = 5\n shgfp_type_current = 0\n buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH)\n ctypes.windll.shell32.SHGetFolderPathW(0, csidl_personal, 0, shgfp_type_current, buf)\n return buf.value\n\n\ndef game_util_folder():\n \"\"\"\n\n :return:\n \"\"\"\n platform = sys.platform\n logging.debug(platform)\n\n if platform == \"win32\":\n\n get_windows_version = sys.getwindowsversion()\n logging.debug(get_windows_version)\n\n my_documents = get_win_doc_folder()\n logging.debug(my_documents)\n\n if get_windows_version.major >= 6:\n return os.path.join(my_documents, \"My Games\", \"StarConflict\")\n else:\n return os.path.join(my_documents, \"My Games\", \"StarConflict\")\n\n elif platform == \"linux\":\n return os.path.join(os.path.expanduser(\"~\"), \".local\", \"share\", \"starconflict\")\n\n elif platform == \"darwin\":\n return os.path.join(os.path.expanduser(\"~\"), \"Library\", \"Application Support\", \"Star Conflict\")\n\n\ndef get_logs_directories():\n \"\"\"\n\n :return:\n \"\"\"\n return [f for f in os.listdir(os.path.join(game_util_folder(), \"logs\")) if\n re.match('\\d{4}\\.\\d{2}\\.\\d{2} \\d{2}\\.\\d{2}\\.\\d{2}', f)]\n\n\ndef get_last_directory():\n \"\"\"\n\n :return:\n \"\"\"\n return os.path.join(game_util_folder(), \"logs\", sorted(get_logs_directories())[-1])\n\n\nif __name__ == \"__main__\":\n logging.info(game_util_folder())\n logging.info(get_last_directory())\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430684105","text":"import SpotfireReport as sf\n\nwith open('ReportLink.txt') as links:\n for url in links:\n with open('TestCases.txt', 'a') as tc:\n rep = sf.Report()\n rep.run(url)\n\n if rep.waiting_time != None:\n if rep.get_active_tab() == 'Cover Page':\n result = 'Pass'\n elif rep.get_active_tab() != 'Cover Page':\n result = 'Fail\\tThe report is opened on the ' + rep.get_active_tab() + ' page'\n else:\n result = 'Fail\\tThe report is not opened.'\n\n tc.write(rep.report_title + '\\t')\n tc.write('Library' + '\\t')\n tc.write('Link' + '\\t')\n tc.write(url.strip() + '\\t')\n tc.write('Click' + '\\t')\n tc.write('The report is opened on the Cover Page' + '\\t')\n tc.write(str(rep.waiting_time) + '\\t')\n tc.write(result + '\\n')\n\n rep.quit()\n","sub_path":"1_open_report.py","file_name":"1_open_report.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615960028","text":"def get_jaccard_sim(str1, str2):\n a = set(str1.split())\n print(a)\n b = set(str2.split())\n print(b)\n c = a.intersection(b)\n return float(len(c)) / (len(a) + len(b) - len(c))\n\n\nsentence1 = 'Hello, how are you ?'\nsentence2 = 'Hey, how are you ?'\nprint(\"jacob sentence similarity\", get_jaccard_sim(sentence1, sentence2))\n","sub_path":"exercises/nlp/jacobsentencesimilarity.py","file_name":"jacobsentencesimilarity.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"576576218","text":"\"\"\"2Sum\"\"\"\n\ndef two_sum(lists,index_map,n):\n for v in lists:\n if -v in lists and n != index_map[-v]:\n return (index_map[v], index_map[-v])\n return (-1,)\n\nk,n = [int(x) for x in input().split()]\nlists = []\nfor _ in range(k):\n lists.append([int(x) for x in input().split()])\n\nindex_maps = []\nfor l in lists:\n m = dict()\n for i,v in enumerate(l):\n m[v] = i+1\n index_maps.append(m)\n\nfor i,l in enumerate(lists):\n print(*two_sum(l,index_maps[i],n))\n","sub_path":"rosalind/algorithmic_heights/problem_8.py","file_name":"problem_8.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"522531140","text":"from typing import Any\nfrom typing import Dict\nfrom typing import FrozenSet\nfrom typing import Set\nfrom typing import TYPE_CHECKING\nfrom typing import Tuple\n\nfrom ddtrace.contrib.trace_utils import set_flattened_tags\n\n\nif TYPE_CHECKING: # pragma: no cover\n from ddtrace.span import Span\n\n\nEXCLUDED_ENDPOINT = frozenset({\"kms\", \"sts\", \"sns\", \"kinesis\", \"events\"})\nEXCLUDED_ENDPOINT_TAGS = {\n \"firehose\": frozenset({\"params.Records\"}),\n \"secretsmanager\": frozenset({\"params.SecretString\", \"params.SecretBinary\"}),\n}\n\n\ndef truncate_arg_value(value, max_len=1024):\n # type: (Any, int) -> Any\n \"\"\"Truncate values which are bytes and greater than `max_len`.\n Useful for parameters like 'Body' in `put_object` operations.\n \"\"\"\n if isinstance(value, bytes) and len(value) > max_len:\n return b\"...\"\n\n return value\n\n\ndef add_span_arg_tags(\n span, # type: Span\n endpoint_name, # type: str\n args, # type: Tuple[Any]\n args_names, # type: Tuple[str]\n args_traced, # type: Set[str]\n):\n # type: (...) -> None\n if endpoint_name not in EXCLUDED_ENDPOINT:\n exclude_set = EXCLUDED_ENDPOINT_TAGS.get(endpoint_name, frozenset()) # type: FrozenSet[str]\n set_flattened_tags(\n span,\n items=((name, value) for (name, value) in zip(args_names, args) if name in args_traced),\n exclude_policy=lambda tag: tag in exclude_set or tag.endswith(\"Body\"),\n processor=truncate_arg_value,\n )\n\n\ndef _add_api_param_span_tags(span, endpoint_name, params):\n # type: (Span, str, Dict[str, Any]) -> None\n # Note: Only some boto3 requests will supply these params\n # i.e. that might explain why you see these tags being set to empty strings\n if endpoint_name == \"cloudwatch\":\n log_group_name = params.get(\"logGroupName\")\n if log_group_name:\n span.set_tag_str(\"aws.cloudwatch.logs.log_group_name\", log_group_name)\n span.set_tag_str(\"loggroupname\", log_group_name)\n elif endpoint_name == \"dynamodb\":\n table_name = params.get(\"TableName\")\n if table_name:\n span.set_tag_str(\"aws.dynamodb.table_name\", table_name)\n span.set_tag_str(\"tablename\", table_name)\n elif endpoint_name == \"kinesis\":\n stream_name = params.get(\"StreamName\")\n if stream_name:\n span.set_tag_str(\"aws.kinesis.stream_name\", stream_name)\n span.set_tag_str(\"streamname\", stream_name)\n elif endpoint_name == \"redshift\":\n cluster_identifier = params.get(\"ClusterIdentifier\")\n if cluster_identifier:\n span.set_tag_str(\"aws.redshift.cluster_identifier\", cluster_identifier)\n span.set_tag_str(\"clusteridentifier\", cluster_identifier)\n elif endpoint_name == \"s3\":\n bucket_name = params.get(\"Bucket\")\n if bucket_name:\n span.set_tag_str(\"aws.s3.bucket_name\", bucket_name)\n span.set_tag_str(\"bucketname\", bucket_name)\n\n elif endpoint_name == \"sns\":\n topic_arn = params.get(\"TopicArn\")\n if topic_arn:\n # example topicArn: arn:aws:sns:sa-east-1:1234:topicname\n span.set_tag_str(\"aws.sns.topic_arn\", topic_arn)\n topicname = topic_arn.split(\":\")[-1]\n aws_account = topic_arn.split(\":\")[-2]\n span.set_tag_str(\"aws_account\", aws_account)\n span.set_tag_str(\"topicname\", topicname)\n\n elif endpoint_name == \"sqs\":\n queue_name = params.get(\"QueueName\", \"\")\n queue_url = params.get(\"QueueUrl\")\n if queue_url and (queue_url.startswith(\"sqs:\") or queue_url.startswith(\"http\")):\n # example queue_url: https://sqs.sa-east-1.amazonaws.com/12345678/queuename\n queue_name = queue_url.split(\"/\")[-1]\n aws_account = queue_url.split(\"/\")[-2]\n span.set_tag_str(\"aws_account\", aws_account)\n span.set_tag_str(\"aws.sqs.queue_name\", queue_name)\n span.set_tag_str(\"queuename\", queue_name)\n\n elif endpoint_name == \"lambda\":\n function_name = params.get(\"FunctionName\", \"\")\n span.set_tag_str(\"functionname\", function_name)\n\n elif endpoint_name == \"events\":\n rule_name = params.get(\"Name\", \"\")\n span.set_tag_str(\"rulename\", rule_name)\n\n elif endpoint_name == \"states\":\n state_machine_arn = params.get(\"stateMachineArn\", \"\")\n span.set_tag_str(\"statemachinearn\", state_machine_arn)\n\n\nAWSREGION = \"aws.region\"\nREGION = \"region\"\nAGENT = \"aws.agent\"\nOPERATION = \"aws.operation\"\n","sub_path":"ddtrace/ext/aws.py","file_name":"aws.py","file_ext":"py","file_size_in_byte":4497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"480856037","text":"# -*- coding: utf-8 -*-\n# Author:leali\n# Description: yield The lowest level of the implementation of Coroutine\n# Version:v1.0\n# Date:2018-06-24-03:15 PM\n\n\ndef customer(name):\n \"\"\"\n Generator by yield\n yield 能保持上下文\n :return:\n \"\"\"\n print(\"Customer Start:\")\n while True:\n result = yield\n print(\"%s Eating %s \" % (name, result))\n\n\ndef producer(conn):\n \"\"\"\n next get generator\n :return:\n \"\"\"\n next(conn)\n i = 0\n print(\"Producer Start:\")\n while i < 5:\n print(\"Making \", i)\n conn.send(i)\n i += 1\n\n\nif __name__ == \"__main__\":\n c1 = customer(\"Leal\")\n # c2 = customer(\"Jane\")\n producer(c1)\n # producer(c2)\n","sub_path":"Study/oldboy/tthreading/coroutine_yield.py","file_name":"coroutine_yield.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"217800482","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# Copyright 2011-2015, Yu-chen Kao (cybeliak)\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\"\"\"\nThe basic definition of a job.\n\"\"\"\n__author__ = \"Yu-chen Kao (cybeliak)\"\n\nfrom enum import IntEnum\nfrom ..utils import log\nfrom ..utils.log import logger\nfrom .class_panel import PanelLink, PanelRes\nfrom .class_hook import Hookable\n\nclass Job(Hookable):\n \"\"\" This class defines a task.\n\n Note that this is just a very minimal skeleton of a job, thus most of the\n details are not defined.\n\n :param kwargs: You can also specify some values to input resources via kwargs.\n that is, write something like Job(res1='value', res2='value')\n\n \"\"\"\n\n class JobState(IntEnum):\n \"\"\" Define the current state of a job. Each job can only be executed once. \"\"\"\n Unknown = 0\n Ready = 1\n Running = 2\n Cached = 98\n Done = 99\n Failed = 100\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._state = self.JobState.Unknown\n \"\"\" State of current task. \"\"\"\n self.i = PanelLink(parent_object=self)\n \"\"\" Input panel for linkers. \"\"\"\n self.o = PanelRes(parent_object=self)\n \"\"\" Input panel for resources. \"\"\"\n\n self.logger = log.get_empty_logger(\"Tiphereth.%s\" % (self.puid))\n \"\"\" Logger object specifically for run contents. \"\"\"\n self.logfile = None\n \"\"\" Log file, will only log when this attribute is set before run. \"\"\"\n\n # ==================== Properties ====================\n\n @property\n def is_unknown(self):\n \"\"\" Whether this job is in unknown stats. \"\"\"\n return self._state == self.JobState.Unknown\n\n @property\n def is_ready(self):\n \"\"\" Whether this job is in ready stats. \"\"\"\n return self._state == self.JobState.Ready\n\n @property\n def is_running(self):\n \"\"\" Whether this job is running. \"\"\"\n return self._state == self.JobState.Running\n\n @property\n def is_cached(self):\n \"\"\" Whether this job is over and the results are being cached. \"\"\"\n return self._state == self.JobState.Cached\n\n @property\n def is_done(self):\n \"\"\" Whether this job is over and successful. \"\"\"\n return self._state == self.JobState.Done\n\n @property\n def is_failed(self):\n \"\"\" Whether this job is over and failed. \"\"\"\n return self._state == self.JobState.Failed\n\n # ==================== Setters ====================\n\n def update_state(self):\n \"\"\" Update the job's state. If all input resources are ready,\n then mark this job as ready (runnable). \"\"\"\n if self.is_unknown and self.i.is_ready:\n self._state = self.JobState.Ready\n\n def set_running(self):\n \"\"\" Update the job's state to be running. \"\"\"\n if self.is_ready:\n self._state = self.JobState.Running\n elif not self.is_running:\n raise RuntimeError(\"%s need to be ready to start run.\" % (self))\n\n def set_done(self):\n \"\"\" Update the job's state to be done. \"\"\"\n if self.is_running:\n self._state = self.JobState.Done\n elif not self.is_done:\n raise RuntimeError(\"%s need to be running to be done.\" % (self))\n\n def set_failed(self):\n \"\"\" Update the job's state to be failed. \"\"\"\n if self.is_running:\n self._state = self.JobState.Failed\n elif not self.is_failed:\n raise RuntimeError(\"%s need to be running to be fail.\" % (self))\n\n def set_cached(self):\n \"\"\" Update the job's state to be cached. \"\"\"\n if self.is_running:\n self._state = self.JobState.Cached\n elif not self.is_cached:\n raise RuntimeError(\"%s need to be running to be cached.\" % (self))\n\n def uptodate(self):\n \"\"\" Checking that if this job is up-to-date. There's no definition\n in this base class. You'll have to inherit this class and override\n this function.\n\n :returns: If up-to-date, the return value should be **True**. Any\n other return values are considered not up-to-date.\n \"\"\"\n return False\n\n def run(self):\n \"\"\" Run the job. Check for mandatory resources, run the work, and then\n pass output resources to things depends on this job.\n\n :returns: If it succeed, the return value should be **True**. Any\n other return values are considered failure.\n \"\"\"\n logger.debug(\" ========== start %s ==========\", self.puid)\n\n self.run_hook('run_pre')\n\n self.update_state()\n self.set_running() # Input resources will be checked here\n\n try:\n if not self.uptodate():\n with log.with_log_file(self.logger, self.logfile):\n self.run_hook('run_setup')\n self.run_hook('run')\n self.run_hook('run_check')\n is_cached = False\n else:\n is_cached = True\n\n self.run_hook('run_post')\n self.o.complete() # Output resources will be checked here\n\n if is_cached == True:\n self.set_cached()\n else:\n self.set_done()\n except Exception as exc:\n self.set_failed()\n raise exc\n\n return True\n","sub_path":"Tiphereth/core/class_job.py","file_name":"class_job.py","file_ext":"py","file_size_in_byte":5850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"155222230","text":"from app.main import main\nfrom app.main.forms import CookiesForm\nfrom flask import (\n current_app,\n flash,\n json,\n make_response,\n redirect,\n render_template,\n request,\n)\nfrom flask_wtf.csrf import CSRFError\nfrom werkzeug.exceptions import HTTPException\n\n\n@main.route(\"\", methods=[\"GET\"])\ndef index():\n return render_template(\"main/index.html\")\n\n\n@main.route(\"/cookies\", methods=[\"GET\", \"POST\"])\ndef cookies():\n form = CookiesForm()\n # Default cookies policy to reject all categories of cookie\n cookies_policy = {\"functional\": \"no\"}\n\n if form.validate_on_submit():\n # Update cookies policy consent from form data\n cookies_policy[\"functional\"] = form.functional.data\n\n # Create flash message confirmation before rendering template\n flash(\"You’ve set your cookie preferences.\", \"success\")\n\n # Create the response so we can set the cookie before returning\n response = make_response(render_template(\"cookies.html\", form=form))\n\n # Set cookies policy for one year\n response.set_cookie(\"cookies_policy\", json.dumps(cookies_policy), max_age=31557600)\n return response\n elif request.method == \"GET\":\n if request.cookies.get(\"cookies_policy\"):\n # Set cookie consent radios to current consent\n cookies_policy = json.loads(request.cookies.get(\"cookies_policy\"))\n form.functional.data = cookies_policy[\"functional\"]\n else:\n # If conset not previously set, use default \"no\" policy\n form.functional.data = cookies_policy[\"functional\"]\n return render_template(\"cookies.html\", form=form)\n\n\n@main.app_errorhandler(HTTPException)\ndef http_exception(error):\n current_app.logger.error(f\"{error.code}: {error.name} - {request.url}\")\n return render_template(\"error.html\", title=error.name, error=error), error.code\n\n\n@main.app_errorhandler(CSRFError)\ndef csrf_error(error):\n current_app.logger.error(f\"{error.code}: {error.description} - {request.url}\")\n flash(\"The form you were submitting has expired. Please try again.\", \"info\")\n return redirect(request.full_path)\n","sub_path":"app/main/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"24693897","text":"##########################AGENTE##############################\n#calculator\nimport os\nimport importlib.util\nimport math\nspec = importlib.util.spec_from_file_location(\"Brick\", os.path.abspath(os.path.join(os.getcwd(), os.pardir)) + \"/agent.py\")\nfoo = importlib.util.module_from_spec(spec)\nspec.loader.exec_module(foo)\nBrick = foo.Brick\n\ndef builder():\n\n def new_perception(self, entry):\n if entry == \"info_edge\":\n return \"Invalid perception\"\n else:\n return True\n\n def new_action(self, entry):\n if entry == \"info_edge\":\n return \"Invalid reaction\"\n else:\n print (\"Invalid entry: \", entry)\n\n state_interactions = [0]\n output_interactions = [0]\n waiting_number = Brick(\"Waiting Number\", \"Entry any real number\", 0, state_interactions,output_interactions, new_perception, new_action)\n bricks_calculator = []\n bricks_calculator.append(waiting_number)\n ##brick created##\n\n def new_action1(self, entry):\n if entry == \"info_edge\":\n return \"Store first number\"\n else:\n self.memory.append(entry)\n print (\"Stored: \", entry)\n\n def new_perception1(self, entry):\n if entry == \"info_edge\":\n return \"Recieve real number\"\n if entry == \"info_edge_from_0\":\n return \"First Real number\"\n if entry == \"info_edge_from_2\":\n return \"Second Real number\"\n try:\n check = float(entry)\n return True\n except ValueError:\n return False\n\n state_interactions = [1, 1, 1]\n output_interactions = [1, 0, 0]\n waiting_operator = Brick(\"Waiting Operator\", \"Entry +, -, *, /\", 1, state_interactions, output_interactions, new_perception1, new_action1)\n bricks_calculator.append(waiting_operator)\n ##brick created##\n\n def new_perception2(self, entry):\n if entry == \"info_edge\":\n return \"Recieve operator\"\n if entry == \"info_edge_from_1\":\n return \"Operators (+, -, *, /)\"\n operators = [\"+\", \"-\", \"*\", \"/\"]\n if entry in operators:\n return True\n else:\n return False\n\n def new_action2(self, entry):\n if entry == \"info_edge\":\n return \"Return the result\"\n if self.memory[1] == \"+\":\n print (\"solution: \", float(self.memory[0]) + float(entry))\n self.memory.clear()\n else:\n if self.memory[1] == \"-\":\n print (\"solution: \", float(self.memory[0]) - float(entry))\n self.memory.clear()\n else:\n if self.memory[1] == \"*\":\n print (\"solution: \", float(self.memory[0]) * float(entry))\n self.memory.clear()\n else:\n print (\"solution: \", float(self.memory[0]) / float(entry))\n self.memory.clear()\n\n state_interactions = [0, 2, 2, 0, 2]\n output_interactions = [0, 1, 0, 2, 0]\n waiting_final_number = Brick(\"Waiting Final number\", \"Entry second number\", 2, state_interactions, output_interactions, new_perception2, new_action2)\n bricks_calculator.append(waiting_final_number)\n ##brick created##\n\n def new_perception3(self, entry):\n if entry == \"info_edge\":\n return \"Recieve trigonometric function\"\n if entry == \"info_edge_from_3\":\n return \"Recieve trigonometric function\"\n if entry == \"info_edge_from_1\":\n return \"Jump to trigonometric calculator\"\n operators = [\"sen()\", \"cos()\", \"tan()\"]\n if self.current_state == 1:\n if entry == \"trigo\":\n return True\n else:\n if entry in operators:\n return True\n else:\n return False\n\n def new_action3(self, entry):\n if entry == \"info_edge\":\n return \"Return trigonometric result\"\n if entry == \"sen()\":\n print (\"solution: sen(\", float(self.memory[0]), \")= \", float(math.sin(float(self.memory[0]))))\n self.memory.clear()\n else:\n if entry == \"cos()\":\n print (\"solution: cos(\", float(self.memory[0]), \")= \", float(math.cos(float(self.memory[0]))))\n self.memory.clear()\n else:\n print (\"solution: tan(\", float(self.memory[0]), \")= \", float(math.tan(float(self.memory[0]))))\n self.memory.clear()\n\n state_interactions = [0, 3, 2, 0, 3, 3, 3]\n output_interactions = [0, 1, 0, 3, 0, 0, 0]\n waiting_trigo_operator = Brick(\"Waiting trigonometric operator\", \"Entry trigonometric operator\", 3, state_interactions, output_interactions, new_perception3, new_action3)\n bricks_calculator.append(waiting_trigo_operator)\n\n\n return foo.AbstractAgent(bricks_calculator, \"calculator2\")\n\n##########################AGENTE##############################","sub_path":"diegoVersion/nodo3/calculator2.py","file_name":"calculator2.py","file_ext":"py","file_size_in_byte":4876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"492737586","text":"class Garden():\n def __init__(self, initState: str, rules: {}):\n self.state = initState\n self.rules = rules\n self.startIdx = 0\n \n # adds padding to left & right\n def addPadding(self, amnt: int):\n self.state = '.' * amnt + self.state + '.' * amnt\n self.startIdx += amnt\n\n def simGen(self) -> None:\n temp = ''\n for i in range(0, len(self.state)):\n start = max(0, i - 2)\n section = self.state[start : i + 3]\n if section in self.rules:\n temp += self.rules[section]\n else:\n temp += '.'\n self.state = temp\n \n def sumGen(self) -> int:\n tot = 0\n for i in range(0, len(self.state)):\n worth = i - self.startIdx\n tot += 0 if self.state[i] == '.' else worth\n return tot\n \n def __repr__(self) -> str:\n s = ''\n for i in range(0, len(self.state)):\n x = self.state[i]\n s += x\n return s\n\n\"\"\"\n INPUT\n\"\"\"\ndef parseInputInit(line: str) -> str:\n return line[line.find(':') + 2:].strip()\n\ndef parseInputRules(lines: [str]) -> {}:\n psd = {}\n for l in lines:\n ls = l.strip().split(' ')\n psd[ls[0]] = ls[2]\n return psd\n\ndef parseInput(file_loc: str) -> (str, str):\n init = None\n rules = None\n with open(file_loc, 'r') as f:\n lines = f.readlines()\n init = parseInputInit(lines[0])\n rules = parseInputRules(lines[2:])\n f.close()\n return (init, rules)\n\n\"\"\"\n EXEC\n\"\"\"\ndef tests():\n psd = parseInput('input_tests.txt')\n\n g = Garden(psd[0], psd[1])\n g.addPadding(20)\n for i in range(0, 20):\n print('{}:\\n{}'.format(i, g))\n g.simGen()\n print(g.sumGen())\n\ndef incDictVal(key, diff, dct: {}):\n if key in dct:\n dct[key] += diff\n else:\n dct[key] = diff\n\ndef task():\n psd = parseInput('input.txt')\n \n g = Garden(psd[0], psd[1])\n g.addPadding(100000)\n\n sums = {}\n sumPrev = g.sumGen()\n for i in range(0, 5000):\n diff = g.sumGen() - sumPrev\n sumPrev = g.sumGen()\n incDictVal(sumPrev, 1, sums)\n print('{}:{}\\tDIFF:{}\\tSUMS:{}'.format(i, g.sumGen(), diff, len(sums)))\n g.simGen()\n print(g.sumGen())\n\ntask()","sub_path":"12/task_2.py","file_name":"task_2.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"211496835","text":"\nimport os\nfrom typing import List\nimport config as cfg\nimport pandas as pd\n\n\nclass AnnotationTheme:\n \"\"\"\n テーマ別の進捗\n \"\"\"\n def __init__(self,\n annot_id: str,\n theme_id: str,\n done: str,\n ):\n # アノテータID\n self.annot_id = annot_id\n # 議論テーマ\n self.theme_id = theme_id\n # アノテーションが完了したか(自己申告)\n self.done = done\n\n\nclass Annotator:\n \"\"\"\n アノテータクラス\n \"\"\"\n def __init__(self,\n id: str,\n name: str,\n phase1_progresses: List[AnnotationTheme],\n phase2_progresses: List[AnnotationTheme],\n ):\n # ID\n self.id = id\n # アノテータ名\n self.name = name\n # 第1フェーズの進捗\n self.phase1_progresses = phase1_progresses\n # 第2フェーズの進捗\n self.phase2_progresses = phase2_progresses\n\n\ndef load_annotators():\n \"\"\"\n アノテータのCSVデータを読み込んで,\n どのアノテータが\n どのフェーズの\n どの議論テーマを\n アノテーションしたかを読み込む\n :return:\n \"\"\"\n # アノテーション進捗を読み込む\n pp = pd.read_csv(cfg.COLLAGREE_ANNOT_RESULT_PROGRESS, error_bad_lines=False, dtype=str)\n annotation_progs = []\n for idx in range(len(pp)):\n row = pp.ix[idx, :]\n annotation_progs.append(\n AnnotationTheme(\n annot_id=str(row[0]),\n theme_id=str(row[1]),\n done=str(row[2])\n )\n )\n\n # アノテータ一覧を読み込む\n pp = pd.read_csv(cfg.COLLAGREE_ANNOT_RESULT_ANNOTATORS, error_bad_lines=False, dtype=str)\n annotators = []\n for idx in range(len(pp)):\n row = pp.ix[idx, :]\n phase1_annot_id = str(row[1])\n phase2_annot_id = str(row[2])\n annotators.append(\n Annotator(\n id=str(row[0]),\n name=str(row[3]),\n phase1_progresses=[prog for prog in annotation_progs if prog.annot_id == phase1_annot_id],\n phase2_progresses=[prog for prog in annotation_progs if prog.annot_id == phase2_annot_id],\n )\n )\n\n return annotators\n\n\nif __name__ == '__main__':\n load_annotators()\n\n","sub_path":"src/annotation/annotator_loader.py","file_name":"annotator_loader.py","file_ext":"py","file_size_in_byte":2419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"44592903","text":"#!/usr/bin/python\n# tweetweather.py\n# Tweet weather data\n\nimport os\nimport logging\nimport argparse\nfrom ConfigParser import SafeConfigParser\nimport tweepy\nfrom getweather import download_data, create_weather\n\n\nABS_FILE_PATH = os.path.dirname(os.path.abspath(__file__))\n\n\ndef parse_args():\n '''Returns the command-line arguments'''\n parser = argparse.ArgumentParser(description='Tweet weather for a WOEID',\n usage='python tweetweather.py [options]')\n parser.add_argument('-i', '--woeid', default='17656',\n help='A WOEID (Where on Earth IDentifier) is a \\\n unique 32 bit reference identifier assigned by \\\n Yahoo! to identify any feature on Earth.')\n parser.add_argument('-u', '--unit', choices=['c', 'f'], default='c',\n help=\"'c' for Celsius and 'f' for Fahreheit\")\n parser.add_argument('-g', '--geo', help='Add location to your tweets. \\\n This must be switched on in the settings of your \\\n Twitter account',\n action=\"store_true\")\n return parser.parse_args()\n\n\ndef get_weather(woeid, unitcode):\n '''Returns a Weather object'''\n datafile = \"%s%s.xml\" % (woeid, unitcode)\n download_data(woeid, unitcode, datafile)\n return create_weather(datafile)\n\n\ndef tweet_weather(weatherobject, geo):\n '''Tweet a weather object'''\n\n # Create a ConfigParser object and read the cfg file\n cfg = SafeConfigParser()\n cfg.read(os.path.join(ABS_FILE_PATH, 'oauthtokens.cfg'))\n\n # assign the tokens to variables\n consumer_key = cfg.get('oauth', 'consumer_key')\n consumer_secret = cfg.get('oauth', 'consumer_secret')\n access_token = cfg.get('oauth', 'access_token')\n access_token_secret = cfg.get('oauth', 'access_token_secret')\n\n # Authenticate\n try:\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n api = tweepy.API(auth)\n except tweepy.TweepError as ex:\n logging.error(\"problem authenticating: %s\", ex)\n\n # Send tweet\n try:\n if geo:\n api.update_status(status=weatherobject.to_tweet(),\n lat=weatherobject.get_geography()['lat'],\n long=weatherobject.get_geography()['long'])\n else:\n api.update_status(weatherobject.to_tweet())\n except tweepy.TweepError as ex:\n logging.error(\"problem updating status: %s\", ex)\n\n\ndef main():\n '''Main entry method to program'''\n # Config logging\n logging.basicConfig(filename=(os.path.join(ABS_FILE_PATH,\n 'getweather.log')),\n format='%(asctime)s: %(message)s',\n level=logging.DEBUG)\n\n # Grab the arguments from the command-line\n woeid = parse_args().woeid\n unit = parse_args().unit\n geo = parse_args().geo\n\n # Make a weather object and tweet it\n weather = get_weather(woeid, unit)\n tweet_weather(weather, geo)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tweetweather/tweetweather.py","file_name":"tweetweather.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"96963979","text":"import discord\nfrom discord.ext import commands\nfrom discord.ext.commands import BadArgument\n\nclass Paramater(object):\n __slots__ = (\"_payload\", \"name\", \"required\")\n\n def __init__(self, payload):\n self._payload = payload\n\n self.name = payload.get(\"name\")\n self.required = payload.get(\"required\")\n \n def __str__(self):\n return self.name\n \n def __repr__(self):\n return self.name\n\nclass CommandCogConverter(commands.Converter):\n async def convert(self, ctx, argument):\n argument = f\"{argument[0].upper()}{argument[1:]}\"\n cog_or_command = ctx.bot.cogs.get(argument, None) or ctx.bot.get_command(argument)\n \n if not cog_or_command:\n raise BadArgument(f\"Extension or command **{argument}** not found\")\n \n return cog_or_command\n\nclass Misc(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self._ignored_cogs = [\"jishaku\",\"main\"]\n \n async def clean_arguments(self, params):\n paramaters = []\n for name, value in params.items():\n if str(value).lower().endswith(\"none\"):\n paramaters.append(Paramater({\n \"name\": str(name),\n \"required\": True\n }))\n\n else:\n paramaters.append(Paramater({\n \"name\": str(name),\n \"required\": False\n }))\n \n return paramaters\n\n @commands.command(name=\"help\")\n async def help_(self, ctx, command_or_cog: CommandCogConverter = None):\n \"\"\"Get help for a command or extension\n If command_or_cog is left empty, a list of extensions will be shown\"\"\"\n embed = discord.Embed(title=\"Help\", colour=discord.Colour.blue(), timestamp=ctx.message.created_at)\n if command_or_cog is not None:\n\n if isinstance(command_or_cog, commands.Command):\n if command_or_cog.hidden:\n raise CommandOrCogNotFound(f\"Command **{command_or_cog}** not found\")\n\n command_paramaters = await self.clean_arguments(command_or_cog.clean_params)\n command_paramaters_cleaned = []\n\n for paramater in command_paramaters:\n if paramater.required is False:\n command_paramaters_cleaned.append(f\"<{str(paramater)}>\")\n else:\n command_paramaters_cleaned.append(f\"[{str(paramater)}]\")\n \n embed.description = f\"`{command_or_cog} {' '.join(command_paramaters_cleaned)}`\\n\"\n embed.description += f\"**{command_or_cog.help}**\\n\"\n\n elif isinstance(command_or_cog, commands.Cog):\n if command_or_cog.__class__.__name__.lower() in self._ignored_cogs:\n raise CommandOrCogNotFound(f\"Extension **{command_or_cog.__class__.__name__}** not found\")\n\n embed.title += f\" for extension {command_or_cog.__class__.__name__}\"\n embed.description = \"**Commands**\\n\"\n\n for command in command_or_cog.walk_commands():\n command_paramaters = await self.clean_arguments(command.clean_params)\n command_paramaters_cleaned = []\n\n for paramater in command_paramaters:\n if paramater.required is False:\n command_paramaters_cleaned.append(f\"<{str(paramater)}>\")\n else:\n command_paramaters_cleaned.append(f\"[{str(paramater)}]\")\n\n embed.description += f\"\\n`{command} {' '.join(command_paramaters_cleaned)}`\\n{command.help}\"\n\n else:\n embed.description = \"**Cogs**\\n\"\n for name, value in self.bot.cogs.items():\n if name.lower() in self._ignored_cogs:\n continue\n\n embed.description += f\"\\n`{name}`\\n{value.description}\"\n\n return await ctx.send(embed=embed)\n\ndef setup(bot):\n bot.add_cog(Misc(bot))\n","sub_path":"cogs/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"5609654","text":"'''\nCreated on Feb 6, 2013\n\n@package: ally plugin\n@copyright: 2012 Sourcefabric o.p.s.\n@license: http://www.gnu.org/licenses/gpl-3.0.txt\n@author: Gabriel Nistor\n\nProvides the distribution controlled events for the plugins.\n'''\n\nimport logging\nfrom os.path import isfile\n\nfrom ally.container import ioc, app, support\nfrom ally.container.event import ITrigger\nfrom ally.container.impl.config import load, save, Config\nfrom ally.design.priority import Priority, PRIORITY_LAST\n\n\n# --------------------------------------------------------------------\nlog = logging.getLogger(__name__)\n\nPRIORITY_PERSIST_MARKERS = Priority('Persist events markers', before=PRIORITY_LAST)\n# The persist markers priority.\n\nAPP_NORMAL = 'normal'\n# Name used for normal application mode.\nAPP_DEVEL = 'devel'\n# Name used for development application mode.\n\n# --------------------------------------------------------------------\n\n@ioc.config\ndef distribution_file_path():\n ''' The name of the distribution file for the plugins deployments'''\n return 'distribution.properties'\n\n@ioc.config\ndef application_mode():\n '''\n The distribution application mode, the possible values are:\n \"normal\" - the application behaves as the normal production instance, this means:\n * the deployments are executed every time, as it should normally would\n * the populates are executed only once as it should normally would\n\n \"devel\" - the application behaves as a development instance, this means:\n * the deployments are executed every time, as it should normally would\n * the populates are executed only once as it should normally would except those that are marked for development.\n '''\n return APP_DEVEL\n\n# --------------------------------------------------------------------\n\n@ioc.entity\ndef markers():\n ''' The markers for the executed events'''\n markers = {}\n if isfile(distribution_file_path()):\n with open(distribution_file_path(), 'r') as f:\n for key, value in load(f).items(): markers['__plugin__.%s' % key] = value\n return markers\n\n@ioc.entity\ndef used():\n ''' The used markers'''\n return set()\n \n# --------------------------------------------------------------------\n\n@ioc.start(priority=PRIORITY_PERSIST_MARKERS)\ndef persistMarkers():\n ''' Persist the markers of the executed events'''\n plen = len('__plugin__.')\n configs = {}\n for name, value in markers().items():\n assert name.startswith('__plugin__.'), 'Invalid name \\'%s\\' is not from a plugin' % name\n if name in used(): group = 'current markers'\n else: group = 'unused markers'\n configs[name[plen:]] = Config(name, value, group)\n with open(distribution_file_path(), 'w') as f: save(configs, f)\n\n# --------------------------------------------------------------------\n\ndef triggerEvents(*triggers, always=(app.DEPLOY,), regardless=(app.DEVEL,), otherwise=(app.NORMAL, app.DEVEL)):\n '''\n Triggers the event for the provided triggers in accordance with the plugin distribution.\n The defaults of this function are for normal application execution.\n \n @param triggers: arguments[object]\n The triggers to perform the events for.\n @param always: tuple(ITrigger)\n The triggers that if present should always be executed.\n @param regardless: tuple(ITrigger)\n The triggers that if present with POPULATE should always be executed.\n @param otherwise: tuple(ITrigger)\n The triggers that if no POPULATE is present should otherwise be executed.\n '''\n assert triggers, 'At least one trigger is required'\n assert isinstance(always, tuple), 'Invalid always triggers %s' % always\n assert isinstance(regardless, tuple), 'Invalid regardless triggers %s' % regardless\n assert isinstance(otherwise, tuple), 'Invalid otherwise triggers %s' % otherwise\n if __debug__:\n for trigger in always: assert isinstance(trigger, ITrigger), 'Invalid always trigger %s' % trigger\n for trigger in regardless: assert isinstance(trigger, ITrigger), 'Invalid regardless trigger %s' % trigger\n for trigger in otherwise: assert isinstance(trigger, ITrigger), 'Invalid otherwise trigger %s' % trigger\n \n for call, name, ctriggers in support.eventsFor(*triggers):\n if app.DEVEL.isTriggered(ctriggers) and application_mode() != APP_DEVEL: continue\n if app.NORMAL.isTriggered(ctriggers) and application_mode() != APP_NORMAL: continue\n \n if any(trigger.isTriggered(ctriggers) for trigger in always):\n log.debug('Executing always event call \\'%s\\'', name)\n call()\n elif app.POPULATE.isTriggered(ctriggers):\n used().add(name)\n executed = markers().get(name)\n if any(trigger.isTriggered(ctriggers) for trigger in regardless): executed = None\n if executed is None:\n executed = call()\n log.debug('Executed populate event call \\'%s\\' for the first time and got %s', name, executed)\n elif not executed:\n executed = call()\n log.debug('Executed populate event call \\'%s\\' again and got %s', name, executed)\n else:\n log.debug('No need to execute populate event call \\'%s\\'', name)\n markers()[name] = executed\n\n elif any(trigger.isTriggered(ctriggers) for trigger in otherwise):\n log.debug('Executing otherwise event call \\'%s\\'', name)\n call()\n","sub_path":"components/ally-plugin/__setup__/ally_plugin/distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"287925726","text":"import numpy as np\nimport pandas as pd\nimport os\n\n\ndef mergeRegions(dir=\"mergeFiles\"):\n os.chdir(dir)\n list_files = []\n\n pwd = os.getcwd()\n for root, dirs, files in os.walk(pwd):\n for file in files:\n if \"csv\" in file:\n list_files.append(file)\n print(list_files)\n df = pd.DataFrame()\n for name in list_files:\n df = df.append(pd.read_csv(name, sep=','))\n df.to_csv(\"MergedResults.csv\", header=True, index=False)\n\n\ndef mergeCal(dir=\"mergeFiles\"):\n\n os.chdir(\"mergeFiles\")\n list_files = []\n\n pwd = os.getcwd()\n for root, dirs, files, in os.walk(pwd):\n for file in files:\n if \".csv\" in file and \"List\" not in file and \"results.csv\" not in file:\n list_files.append(file)\n f = open('ListInputs.csv', \"w\")\n print(list_files)\n df = pd.DataFrame()\n for file in list_files:\n name = file[:-4]\n f.write(name)\n df_temp = pd.read_csv(file, sep=',')\n df[\"E_\" + name] = df_temp['CalibratedE']\n df['cluster_ENG_CALIB_TOT'] = df_temp['cluster_ENG_CALIB_TOT']\n df.to_csv(\"results.csv\", header=True, index=False)\n\n\nmergeCal()\n","sub_path":"merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"166952853","text":"from unittest import TestCase\n\nfrom tests import fixtures_dir\nfrom tests.fixtures.books.fixtures import books\nfrom xsdata.formats.dataclass.serializers import XmlSerializer\nfrom xsdata.formats.dataclass.serializers.config import SerializerConfig\nfrom xsdata.formats.dataclass.serializers.writers import LxmlEventWriter\n\n\nclass LxmlEventWriterTests(TestCase):\n def setUp(self):\n config = SerializerConfig(pretty_print=True)\n self.serializer = XmlSerializer(config=config, writer=LxmlEventWriter)\n\n def test_render(self):\n actual = self.serializer.render(books)\n expected = fixtures_dir.joinpath(\"books/books_auto_ns.xml\").read_text()\n\n self.assertEqual(expected, actual)\n\n def test_render_with_provided_namespaces(self):\n actual = self.serializer.render(books, {\"brk\": \"urn:books\"})\n expected = fixtures_dir.joinpath(\"books/books.xml\").read_text()\n\n self.assertEqual(expected, actual)\n\n def test_render_with_default_namespace_prefix(self):\n actual = self.serializer.render(books, {None: \"urn:books\"})\n expected = fixtures_dir.joinpath(\"books/books_default_ns.xml\").read_text()\n\n xml_declaration, actual = actual.split(\"\\n\", 1)\n _, expected = expected.split(\"\\n\", 1)\n\n self.assertEqual(expected, actual)\n\n def test_encoding(self):\n self.serializer.config.encoding = \"US-ASCII\"\n self.serializer.config.xml_version = \"1.1\"\n actual = self.serializer.render(books)\n xml_declaration, _ = actual.split(\"\\n\", 1)\n\n self.assertEqual('', xml_declaration)\n\n def test_declaration_disabled(self):\n self.serializer.config.xml_declaration = False\n actual = self.serializer.render(books, {None: \"urn:books\"})\n expected = fixtures_dir.joinpath(\"books/books_default_ns.xml\").read_text()\n xml_declaration, expected = expected.split(\"\\n\", 1)\n\n self.assertEqual(expected, actual)\n\n def test_pretty_print_false(self):\n self.serializer.config.pretty_print = False\n actual = self.serializer.render(books)\n expected = fixtures_dir.joinpath(\"books/books_auto_ns.xml\").read_text()\n\n _, actual = actual.split(\"\\n\", 1)\n _, expected = expected.split(\"\\n\", 1)\n self.assertEqual(expected.replace(\" \", \"\").replace(\"\\n\", \"\"), actual)\n\n def test_pretty_print_indent(self):\n self.serializer.config.pretty_print_indent = \" \"\n actual = self.serializer.render(books)\n expected = fixtures_dir.joinpath(\"books/books_auto_ns.xml\").read_text()\n\n _, actual = actual.split(\"\\n\", 1)\n _, expected = expected.split(\"\\n\", 1)\n self.assertEqual(expected.replace(\" \", \" \"), actual)\n","sub_path":"tests/formats/dataclass/serializers/writers/test_lxml.py","file_name":"test_lxml.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"392234487","text":"\"\"\"\nRuntime: 56 ms, faster than 77.34% of Python3 online submissions for How Many Numbers Are Smaller Than the Current Number.\nMemory Usage: 14.4 MB, less than 13.73% of Python3 online submissions for How Many Numbers Are Smaller Than the Current Number.\n\"\"\"\n\n\n# Took about ~29 min to find more optimal solution at O(n log n)\n# Brute force would have been O(n^2). I skipped brute force entirely\n# Utilizes dictionary to store the indices for each unique number\n# Heapsorts the list achieve a sorted list\n# There were even better solutions. One coder achieved linear time!\n\ndef smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:\n index = {}\n res = []\n for ii in range(len(nums)):\n nums[ii] *= -1\n res.append(0)\n \n for ii in range(len(nums)):\n if nums[ii] in index:\n lst = index[nums[ii]]\n lst.append(ii)\n index[nums[ii]] = lst\n else:\n index.update({nums[ii]:[ii]}) \n print(index)\n heapq.heapify(nums)\n prior = heapq.heappop(nums)\n while len(nums) > 0:\n if nums[0]==prior:\n prior = heapq.heappop(nums)\n else:\n lst = index[prior]\n for loc in lst:\n res[loc] = len(nums)\n prior = heapq.heappop(nums)\n return res","sub_path":"Arrays/smallerNumbersThanCurrent.py","file_name":"smallerNumbersThanCurrent.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"279111029","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\n\nimport sys\n\nimport pickle\n\nfrom pitched_recommend import Recommender\n\n\ndef rertain_model():\n rec_config = {\n 'pct_test': 0.1,\n 'alpha': 100,\n 'factors': 200,\n 'regularization': 0.1,\n 'iterations': 1000,\n 'rseed': 4393971,\n 'save_basedir': '../saved_models/iter1000_alpha100_factors200_reg01_rseed0_pctTest01',\n }\n\n\n rec = Recommender(rec_config)\n rec.build_recommender(sys.argv[1])\n with open(sys.argv[2], 'wb') as file:\n \tpickle.dump(rec, file)\n\nif __name__ == '__main__':\n rertain_model()","sub_path":"recommender/playlist_recommend/airflow/retrain_model.py","file_name":"retrain_model.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607346290","text":"import numpy as np\n\nfrom object_storage import ObjectStore\nfrom openpathsampling.trajectory import Trajectory\n\n# This adds delayed snapshot loading support to Trajectory\n\ndef load_missing_snapshot(func):\n def getter(self, *args, **kwargs):\n item = func(self, *args, **kwargs)\n\n if type(item) is tuple:\n item = item[0][item[1]]\n\n return item\n\n return getter\n\nTrajectory.__getitem__ = load_missing_snapshot(Trajectory.__getitem__)\nTrajectory.__getslice__ = load_missing_snapshot(Trajectory.__getslice__)\n\nclass TrajectoryStore(ObjectStore):\n def __init__(self, storage, lazy=True, use_snapshot_cache=True):\n super(TrajectoryStore, self).__init__(storage, Trajectory)\n self.lazy = lazy\n self.use_snapshot_cache = use_snapshot_cache\n\n def save(self, trajectory, idx=None):\n \"\"\"\n Add the current state of the trajectory to the storage. Saving also\n all referenced snapshots in it\n\n Parameters\n ----------\n trajectory : Trajectory()\n the trajectory to be saved\n idx : int or None\n if idx is not None the index will be used for saving in the storage.\n This might overwrite already existing trajectories!\n\n Notes\n -----\n This also saves all contained frames in the trajectory if not done yet.\n A single Trajectory object can only be saved once!\n \"\"\"\n\n # Check if all snapshots are saved\n values = []\n for snap in list.__iter__(trajectory):\n if type(snap) is not tuple:\n self.storage.snapshots.save(snap)\n values.append(snap.idx[self.storage])\n elif snap[0].storage is not self.storage:\n new_snap = snap[0][snap[1]]\n self.storage.snapshots.save(new_snap)\n values.append(new_snap.idx[self.storage])\n else:\n values.append(snap[1])\n\n# map(self.storage.snapshots.save, trajectory)\n# values = self.list_to_numpy(trajectory, 'snapshot')\n\n values = self.list_to_numpy(values, 'index')\n self.storage.variables['trajectory_snapshot_idx'][idx] = values\n\n # self.storage.sync()\n\n def snapshot_indices(self, idx):\n '''\n Load snapshot indices for trajectory with ID 'idx' from the storage\n\n Parameters\n ----------\n idx : int\n ID of the trajectory\n\n Returns\n -------\n list of int\n trajectory indices\n\n '''\n\n # get the values\n values = self.storage.variables['trajectory_snapshot_idx'][idx]\n\n # typecast to integer\n return self.list_from_numpy(values, 'index')\n\n def load(self, idx):\n '''\n Return a trajectory from the storage\n\n Parameters\n ----------\n idx : int\n index of the trajectory\n\n Returns\n -------\n Trajectory\n the trajectory\n\n '''\n\n values = self.storage.variables['trajectory_snapshot_idx'][idx]\n\n # typecast to snapshot\n if self.lazy:\n if self.use_snapshot_cache:\n snapshots = [ self.storage.snapshots.cache[idx] if idx in self.storage.snapshots.cache else tuple([self.storage.snapshots, idx]) for idx in self.list_from_numpy(values, 'int') ]\n else:\n snapshots = [ tuple([self.storage.snapshots, idx]) for idx in self.list_from_numpy(values, 'int') ]\n else:\n snapshots = self.list_from_numpy(values, 'snapshots')\n\n trajectory = Trajectory(snapshots)\n # save the used storage to load snapshots if required\n\n trajectory.storage = self.storage\n\n return trajectory\n\n def iter_snapshot_indices(this, iter_range=None):\n '''\n Return an iterator over the lists of snapshot indices for all\n trajectories in the storage\n\n Parameters\n ----------\n iter_range : slice or None\n if this is not `None` it confines the iterator to objects specified\n in the slice\n\n Returns\n -------\n Iterator\n the iterator\n '''\n\n class ObjectIterator:\n def __init__(self):\n self.storage = this\n self.iter_range = iter_range\n if iter_range is None:\n self.idx = 0\n self.end = self.storage.count()\n else:\n self.idx = iter_range.start\n self.end = iter_range.stop\n\n def __iter__(self):\n return self\n\n def next(self):\n if self.idx < self.storage.count():\n obj = self.snapshot_indices(self.idx)\n if self.iter_range is not None and self.iter_range.step is not None:\n self.idx += self.iter_range.step\n else:\n self.idx += 1\n return obj\n else:\n raise StopIteration()\n\n return ObjectIterator()\n\n def _init(self, units=None):\n super(TrajectoryStore, self)._init()\n\n # index associated storage in class variable for all Trajectory instances to access\n\n self.init_variable('trajectory_snapshot_idx', 'index', 'trajectory',\n description=\"trajectory[trajectory][frame] is the snapshot index (0..nspanshots-1) of frame 'frame' of trajectory 'trajectory'.\",\n variable_length = True,\n chunksizes=(10240, )\n )","sub_path":"openpathsampling/storage/trajectory_store.py","file_name":"trajectory_store.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"344340347","text":"from p1_support import load_level, show_level, save_level_costs\nfrom math import inf, sqrt\nfrom heapq import heappop, heappush\nDEBUG = False;\n\ndef dijkstras_shortest_path(initial_position, destination, graph, adj):\n \"\"\" Searches for a minimal cost path through a graph using Dijkstra's algorithm.\n Args:\n initial_position: The initial cell from which the path extends.\n destination: The end location for the path.\n graph: A loaded level, containing walls, spaces, and waypoints.\n adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.\n\n Returns:\n If a path exits, return a list containing all cells from initial_position to destination.\n Otherwise, return None.\n\n \"\"\"\n # Initilize the heap, dist and prev\n heap = []\n dist = {}\n prev = {}\n\n # Put the initial position, with weight 0 into\n dist[initial_position] = 0\n prev[initial_position] = None\n active = tuple([0,initial_position]);\n heappush(heap, active)\n #(weight, (x,y))\n found = False\n while heap:\n active = heappop(heap)\n if active[1] == destination:\n found = True\n break\n neighbours = adj(graph, active[1])\n for considered in neighbours:\n alt_val = active[0] + considered[0]\n if active[0] == inf: continue\n if considered[1] not in dist or alt_val < dist[considered[1]]:\n considered = tuple([alt_val,considered[1]])\n dist[considered[1]] = alt_val\n prev[considered[1]] = active[1]\n if considered in heap: heap.remove(considered)\n heappush(heap, considered)\n\n #Get the path\n path = []\n head = destination\n\n if not found:\n return path;\n\n while prev[head]:\n path.append(prev[head])\n head = prev[head]\n\n return path\n\n\n\ndef dijkstras_shortest_path_to_all(initial_position, graph, adj):\n \"\"\" Calculates the minimum cost to every reachable cell in a graph from the initial_position.\n\n Args:\n initial_position: The initial cell from which the path extends.\n graph: A loaded level, containing walls, spaces, and waypoints.\n adj: An adjacency function returning cells adjacent to a given cell as well as their respective edge costs.\n\n Returns:\n A dictionary, mapping destination cells to the cost of a path from the initial_position.\n \"\"\"\n\n heap = []\n dist = {}\n prev = {}\n\n # Put the initial position, with weight 0 into\n dist[initial_position] = 0\n prev[initial_position] = None\n active = tuple([0,initial_position]);\n heappush(heap, active)\n\n #While the heap has something in it, it means there is unexplored nodes.\n while heap:\n # set the active node and get its neighbors\n active = heappop(heap)\n neighbours = adj(graph, active[1])\n #forevery neighbor compare its current value to the alternate path\n # that can be reached through the active node.\n # Also, make sure to check whether the cell is in our dictionary.\n # Keep track of the parent of each node\n for considered in neighbours:\n alt_val = active[0] + considered[0]\n if considered[1] not in dist or alt_val < dist[considered[1]]:\n considered = tuple([alt_val,considered[1]])\n dist[considered[1]] = alt_val\n prev[considered[1]] = active[1]\n if considered in heap: heap.remove(considered)\n heappush(heap, considered)\n return dist\n\n\ndef navigation_edges(level, cell):\n \"\"\" Provides a list of adjacent cells and their respective costs from the given cell.\n Args:\n level: A loaded level, containing walls, spaces, and waypoints.\n cell: A target location.\n Returns:\n A list of tuples containing an adjacent cell's coordinates and the cost of the edge joining it and the\n originating cell.\n\n E.g. from (0,0):\n [((0,1), 1),\n ((1,0), 1),\n ((1,1), 1.4142135623730951),\n ... ]\n \"\"\"\n return_list = [];\n spaces = level[\"spaces\"]\n walls = level[\"walls\"]\n waypoints = level[\"waypoints\"]\n sqrt2 = sqrt(2);\n\n\n for i in range(-1,2):\n for j in range(-1, 2):\n try:\n if i == 0 and j == 0: continue\n neighbor_cell = list();\n neighbor_cell.append(cell[0] + i);\n neighbor_cell.append(cell[1] + j);\n if (tuple(neighbor_cell)) in spaces.keys():\n neighbor_weight = spaces[tuple(neighbor_cell)]\n elif tuple(neighbor_cell) in walls:\n neighbor_weight = inf;\n elif tuple(neighbor_cell) in waypoints.keys():\n neighbor_weight = 1;\n else:\n continue\n if abs(i+j)% 2 == 1:\n neighbor_weight *= sqrt2;\n tple = (neighbor_weight, tuple(neighbor_cell))\n return_list.append( tple)\n except IndexError:\n print(\"whoops out of bounds!\")\n\n return return_list\n\n #print(list(level[\"walls\"])[0:5]); # (x,y) [(11, 11), (14, 4)]\n #print(list(level[\"spaces\"].items())[0:5]); # ((x,y), weight) [((1, 1), 3.0), ((2, 1), 2.0)]\n #print(list(level[\"waypoints\"].items())[0:5]); # (waypoint, (x,y)) [('b', (18, 2)), ('e', (8, 6))]\n\n\ndef unit_test_route(filename, src_waypoint, dst_waypoint):\n \"\"\" Loads a level, searches for a path between the given waypoints, and displays the result.\n\n Args:\n filename: The name of the text file containing the level.\n src_waypoint: The character associated with the initial waypoint.\n dst_waypoint: The character associated with the destination waypoint.\n\n \"\"\"\n\n # Load and display the level.\n level = load_level(filename)\n\n # Retrieve the source and destination coordinates from the level.\n src = level['waypoints'][src_waypoint]\n dst = level['waypoints'][dst_waypoint]\n\n # Search for and display the path from src to dst.\n path = dijkstras_shortest_path(src, dst, level, navigation_edges)\n\n return path\n\n\ndef test_route(filename, src_waypoint, dst_waypoint):\n \"\"\" Loads a level, searches for a path between the given waypoints, and displays the result.\n\n Args:\n filename: The name of the text file containing the level.\n src_waypoint: The character associated with the initial waypoint.\n dst_waypoint: The character associated with the destination waypoint.\n\n \"\"\"\n\n # Load and display the level.\n level = load_level(filename)\n show_level(level)\n\n # Retrieve the source and destination coordinates from the level.\n src = level['waypoints'][src_waypoint]\n dst = level['waypoints'][dst_waypoint]\n\n # Search for and display the path from src to dst.\n path = dijkstras_shortest_path(src, dst, level, navigation_edges)\n if path:\n show_level(level, path)\n else:\n print(\"No path possible!\")\n\n\ndef cost_to_all_cells(filename, src_waypoint, output_filename):\n \"\"\" Loads a level, calculates the cost to all reachable cells from \n src_waypoint, then saves the result in a csv file with name output_filename.\n\n Args:\n filename: The name of the text file containing the level.\n src_waypoint: The character associated with the initial waypoint.\n output_filename: The filename for the output csv file.\n\n \"\"\"\n \n # Load and display the level.\n level = load_level(filename)\n show_level(level)\n\n # Retrieve the source coordinates from the level.\n src = level['waypoints'][src_waypoint]\n \n # Calculate the cost to all reachable cells from src and save to a csv file.\n costs_to_all_cells = dijkstras_shortest_path_to_all(src, level, navigation_edges)\n save_level_costs(level, costs_to_all_cells, output_filename)\n\n\nif __name__ == '__main__':\n filename, src_waypoint, dst_waypoint = '../input/my_maze.txt', 'a','d'\n\n # Use this function call to find the route between two waypoints.\n test_route(filename, src_waypoint, dst_waypoint)\n\n # Use this function to calculate the cost to all reachable cells from an origin point.\n cost_to_all_cells(filename, src_waypoint, 'my_costs.csv')\n","sub_path":"src/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":8367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611536395","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\nimport requests\nimport json\nimport time\n\nfrom xmind2testlink.datatype import TestCase\n\n\nclass XrayIssue:\n def __init__(self, x_acpt, jira_token, xray_client_id=None, xray_client_key=None):\n self.xray_headers = {\n 'X-acpt': x_acpt,\n 'Content-Type': 'application/json;charset=UTF-8',\n }\n self.jira_headers = {\n 'Authorization': 'Basic ' + jira_token,\n 'Content-Type': 'application/json',\n }\n self.folder_id = {}\n self.project_id = {\n 'KC': '10012',\n 'KE': '10005',\n 'KM': '10028',\n 'KI': '10024',\n 'MDX': '10023',\n }\n\n self.is_smoketest = {\n True: 'Yes',\n False: 'No',\n }\n\n self.is_need_quard = {\n True: 'Yes',\n False: 'No',\n }\n\n self.testcase_type = {\n '主流程用例': '主流程用例',\n '分支用例': '分支用例',\n 'UED用例': 'UED用例',\n '波及功能用例': '波及功能用例',\n }\n self.srcum_team_jira_type = 'customfield_10089'\n self.xray_client_id = xray_client_id\n self.xray_client_key = xray_client_key\n if self.xray_client_id is not None and self.xray_client_key is not None:\n self.xray_token = self.xray_auth()\n self.bulk_xray_headers = {\n 'Authorization': 'Bearer ' + self.xray_token,\n 'Content-Type': 'application/json;charset=UTF-8',\n }\n\n def xray_auth(self):\n auth_url = 'https://xray.cloud.xpand-it.com/api/v1/authenticate'\n auth_payload = {\n 'client_id': self.xray_client_id,\n 'client_secret': self.xray_client_key,\n }\n res = requests.post(auth_url, json=auth_payload)\n return json.loads(res.content)\n\n def generate_bulk_json(self, project_name_key, issue_name, test_case, link_issue_key,\n components, is_smoketest, is_need_quard, testcase_type, forder):\n importance_list = [0, 1, 2, 3]\n importance = 3 if int(test_case.importance) not in importance_list else int(test_case.importance)\n issue_name = str(issue_name).replace('\\r\\n', '').replace('\\r', '').replace('\\n', '')\n link_issue_scrum_team_id = self.get_issue_scrum_team_id(link_issue_key)\n steps = []\n for step in test_case.steps:\n step_json = dict()\n step_json['action'] = step.action\n step_json['data'] = ''\n step_json['result'] = step.expected\n steps.append(step_json)\n bulk_json = {\n 'testtype': 'Manual',\n 'fields': {\n 'summary': issue_name,\n 'project': {'key': project_name_key},\n 'priority': {'name': 'P' + str(importance)},\n 'description': 'example of manual test',\n 'issuetype': {'name': 'Test'},\n 'components': [],\n 'assignee': [],\n 'customfield_10137': {'value': self.is_smoketest[is_smoketest]},\n 'customfield_10139': {'value': self.testcase_type[testcase_type]},\n self.srcum_team_jira_type: {'id': link_issue_scrum_team_id},\n 'customfield_10145': {'value': self.is_need_quard[is_need_quard]},\n },\n 'update': {\n 'issuelinks': [\n {\n 'add': {\n 'type': {\n 'name': 'Test'\n },\n 'outwardIssue': {\n 'key': link_issue_key,\n }\n }\n }\n ]\n },\n 'steps': steps,\n 'xray_test_repository_folder': forder,\n }\n if project_name_key == \"KC\":\n bulk_json['fields']['components'].append({'name': components})\n bulk_json['fields']['assignee'].append({'id': '5ac2e1fc09ee392b905c0972'})\n return bulk_json\n\n def bulk_xray_issue(self, bulk_json_arr):\n bulk_url = 'https://xray.cloud.xpand-it.com/api/v1/import/test/bulk'\n\n try:\n self.xray_token = self.xray_auth()\n res = requests.post(bulk_url, json=bulk_json_arr, headers=self.bulk_xray_headers)\n return json.loads(res.content).get('jobId')\n except Exception as e:\n print('Bulk import xray issue failed {}'.format(e))\n\n def check_bulk_issue_status(self, job_id):\n \"\"\"\n\n :param job_id: bulk issue status\n :return:\n {\n \"status\": \"successful\",\n \"result\": {\n \"errors\": [],\n \"issues\": [\n {\n \"elementNumber\": 0,\n \"id\": \"62372\",\n \"key\": \"KC-6410\",\n \"self\": \"https://olapio.atlassian.net/rest/api/2/issue/62372\"\n }\n ],\n \"warnings\": []\n }\n }\n \"\"\"\n check_bulk_url = 'https://xray.cloud.xpand-it.com/api/v1/import/test/bulk/{}/status'.format(job_id)\n try:\n res = requests.get(check_bulk_url, headers=self.bulk_xray_headers)\n except Exception:\n self.xray_token = self.xray_auth()\n res = requests.get(check_bulk_url, headers=self.bulk_xray_headers)\n return json.loads(res.content)\n\n def await_import_bulk_xray_issue(self, job_id):\n finished_status = ['successful', 'failed', 'unsuccessful']\n res = self.check_bulk_issue_status(job_id)\n while res.get('status') not in finished_status:\n print('Import status is {}, not finished, wait 20 second'.format(res.get('status')))\n time.sleep(20)\n res = self.check_bulk_issue_status(job_id)\n print('Import finished, status is {}'.format(res.get('status')))\n return res\n\n def create_xray_issue(self, project_name_key, issue_name, importance, link_issue_key,\n components=None, is_smoketest=False, is_need_quard=False, testcase_type='主流程用例'):\n url = \"https://olapio.atlassian.net/rest/api/2/issue\"\n importance_list = [0, 1, 2, 3]\n if int(importance) not in importance_list:\n importance = 3\n issue_name = str(issue_name).replace('\\r\\n', '').replace('\\r', '').replace('\\n', '')\n link_issue_scrum_team_id = self.get_issue_scrum_team_id(link_issue_key)\n payload = {\n \"fields\": {\n \"project\": {\"key\": project_name_key},\n \"summary\": issue_name,\n \"priority\": {\"name\": \"P\" + str(importance)},\n \"description\": \"example of manual test\",\n \"issuetype\": {\"name\": \"Test\"},\n 'components': [],\n 'assignee': [],\n 'customfield_10137': {'value': self.is_smoketest[is_smoketest]},\n 'customfield_10139': {'value': self.testcase_type[testcase_type]},\n self.srcum_team_jira_type: {'id': link_issue_scrum_team_id},\n 'customfield_10145': {'value': self.is_need_quard[is_need_quard]},\n }\n }\n if project_name_key == \"KC\":\n payload['fields']['components'].append({'name': components})\n payload['fields']['assignee'].append({'id': '5ac2e1fc09ee392b905c0972'})\n\n response = requests.request(\"POST\", url, headers=self.jira_headers, data=json.dumps(payload))\n if response.status_code >= 400:\n print('创建issue 状态码为{}'.format(response.status_code))\n print('create jira issue failed, {}'.format(response.content.decode(encoding='utf-8')))\n print(response.json()['key'])\n print('成功创建了xray issue https://olapio.atlassian.net/browse/' + response.json()['key'])\n return response.json()['id'], response.json()['key']\n\n # 2. 给issue新增step, 替换url中的id\n\n def create_xray_issue_step(self, key, index, action, data, result):\n create_step_url = 'https://xray.cloud.xpand-it.com/api/internal/test/' + key + '/step'\n data = {\"id\": \"-1\", \"index\": index, \"customFields\": [], \"action\": action, \"data\": data, \"result\": result}\n\n response = requests.post(create_step_url, headers=self.xray_headers, data=json.dumps(data))\n if response.status_code == 500:\n print(response.json()['error'])\n exit(1)\n # else:\n # print('创建步骤成功')\n\n def create_xray_full_issue(self, project_name_key, issue_name, test_case, link_issue_key,\n components, is_smoketest, is_need_quard, testcase_type):\n # test_case = TestCase(test_case)\n (issue_id, issue_key) = self.create_xray_issue(project_name_key, issue_name, test_case.importance,\n link_issue_key, components, is_smoketest,\n is_need_quard, testcase_type)\n self.link_issue(link_issue_key, issue_key)\n # self.get_folder_id(project_name_key)\n for i in range(len(test_case.steps)):\n step = test_case.steps[i]\n self.create_xray_issue_step(issue_id, i, step.action, '', step.expected)\n # self.move_issue_to_folder(issue_id, project_name_key, components)\n return issue_id\n\n def move_issue_to_folder(self, issue_ids, project_name_key, components):\n move_url = 'https://xray.cloud.xpand-it.com/api/internal/test-repository/move-tests-to-folder'\n data = {\n 'folderId': self.folder_id[components],\n 'issueIds': issue_ids,\n 'skipTestValidation': False,\n 'projectId': self.project_id[project_name_key],\n }\n response = requests.post(move_url, headers=self.xray_headers, data=json.dumps(data))\n print(response.status_code)\n if response.status_code >= 400:\n print(response.content)\n\n def get_folder_id(self, project_name_key):\n get_folder_url = 'https://xray.cloud.xpand-it.com/api/internal/test-repository'\n data = {\n 'projectId': self.project_id[project_name_key],\n }\n response = requests.post(get_folder_url, headers=self.xray_headers, data=json.dumps(data))\n print(response.status_code)\n if response.status_code >= 400:\n print(response.content)\n for folder in json.loads(response.content).get('folders'):\n self.folder_id[folder.get('name')] = folder.get('folderId')\n\n def link_issue(self, origin_key, xray_key):\n url = 'https://olapio.atlassian.net/rest/api/2/issueLink'\n\n # payload = {\"type\": {\"id\": \"10006\"}, \"inwardIssue\": {\"key\": \"KE-12706\"}, \"outwardIssue\": {\"key\": \"QUARD-263\"}}\n payload = {\"type\": {\"id\": \"10006\"}, \"inwardIssue\": {\"key\": origin_key}, \"outwardIssue\": {\"key\": xray_key}}\n\n response = requests.request(\"POST\", url, headers=self.jira_headers, data=json.dumps(payload))\n # return response.json()['id']\n\n def get_issue_scrum_team_id(self, issue_key):\n res = self.get_issue_info(issue_key)\n if self.srcum_team_jira_type not in res.get('fields').keys():\n print('{} has not scrum team property, please add it')\n raise None\n return res.get('fields').get(self.srcum_team_jira_type).get('id')\n\n def get_issue_info(self, issue_key):\n url = \"https://olapio.atlassian.net/rest/api/2/issue/{}\".format(issue_key)\n\n payload = {}\n\n response = requests.request(\"GET\", url, headers=self.jira_headers, data=payload)\n\n return json.loads(response.content)\n\n\n# create_xray_full_issue()\nif __name__ == '__main__':\n X_acpt = ''\n xray_headers = {\n 'X-acpt': X_acpt,\n 'Content-Type': 'application/json;charset=UTF-8',\n }\n jira_token = ''\n xray_issue = XrayIssue(X_acpt, jira_token,\n '',\n '')\n res = xray_issue.xray_auth()\n print(res)\n # project_name_key = 'QUARD'\n # issue_name = 'test_issue'\n # test_case = ''\n # link_issue_key = ''\n # xray_issue.create_xray_full_issue(project_name_key, issue_name, test_case, link_issue_key)\n","sub_path":"xmind2testlink/xray.py","file_name":"xray.py","file_ext":"py","file_size_in_byte":12382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"48093139","text":"def calc_distance(a, b):\n return ( abs(a[0] - b[0]) + abs(a[1] - b[1]) )\n\ndef closest_thing(position, things):\n closest = 100000\n found = None\n \n for t in things:\n distance = calc_distance( position, t.position )\n\n if distance < closest:\n closest = distance\n found = t\n\n return found\n","sub_path":"wedge/wedgeutil.py","file_name":"wedgeutil.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"443116213","text":"import inference\nimport sys\nimport cv2 as cv\nimport os\nimport numpy as np\n# https://pjreddie.com/media/files/yolov2-tiny.weights\n\ndir = os.path.dirname(os.path.abspath(__file__))\n\n\ndef yolo_processor(args, frame, output):\n class_id = None\n cols = frame.shape[1]\n rows = frame.shape[0]\n\n for i in range(output.shape[0]):\n k_probability_index = 5\n probability_size = output.shape[1] - k_probability_index\n scores = output[i, k_probability_index:]\n\n class_id = np.argmax(scores)\n confidence = output[i, k_probability_index + class_id]\n if confidence < args.thr:\n continue\n cx = output[i, 0]\n cy = output[i, 1]\n width = output[i, 2]\n height = output[i, 3]\n xLeftBottom = int((cx - width / 2) * cols)\n yLeftBottom = int((cy - height / 2) * rows)\n xRightTop = int((cx + width / 2) * cols)\n yRightTop = int((cy + height / 2) * rows)\n\n print(\"Best match\", args.classes[class_id])\n cv.rectangle(frame, (xLeftBottom, yLeftBottom), (xRightTop, yRightTop),\n (0, 255, 0))\n inference.put_text(frame, \"%s: %.3f\" %\n (args.classes[class_id], confidence), (xLeftBottom, yLeftBottom), (0, 0, 255))\n\n\nif __name__ == \"__main__\":\n parser = inference.create_base_parser()\n parser.add_argument(\n '--class_names', help='Path to COCO class_names file.', required=True)\n if len(sys.argv) == 1:\n args = parser.parse_args([\"--model_config\",\n os.path.join(\n dir, \"assets/tiny-yolo-voc.cfg\"),\n \"--model_binary\",\n os.path.join(\n dir, \"assets/yolov2-tiny.weights\"),\n \"--class_names\",\n os.path.join(dir, \"assets/coco.names\"),\n \"--net_scale\",\n \"0.003921568627451\",\n \"--swap_rg\",\n \"--net_width\",\n \"416\",\n \"--net_height\",\n \"416\"\n ])\n else:\n args = parser.parse_args()\n\n args.classes = inference.get_class_list(args.class_names)\n\n inference.run(args, yolo_processor)\n","sub_path":"opencv-inference/yolo_detector.py","file_name":"yolo_detector.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"17336653","text":"import logging\nimport sys\n\ndef get_basic_logger():\n if \"basic\" in logging.Logger.manager.loggerDict.keys():\n return logging.getLogger(\"basic\")\n else:\n logger = logging.getLogger(\"basic\")\n logger.setLevel(logging.DEBUG)\n\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n return logger\n","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"297731174","text":"a,b,c=map(int,input().split())\nl=[]\nn=len(str(l))\nif(a%2==0):\n q=a//2\n for i in range(n):\n if(q%(b+c)==0):\n a.append(l)\nif(len(l)==n or a==224):\n print(\"YES\")\nelse:\n print(\"NO\")\n","sub_path":"bhar.py","file_name":"bhar.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611366799","text":"from django.contrib import admin\nfrom .models import Reviews_list\n\n# Register your models here.\n\n\nclass ReviewAdmin(admin.ModelAdmin):\n list_display = (\n 'product',\n 'review',\n 'review_rating',\n 'date',\n )\n\nadmin.site.register(Reviews_list, ReviewAdmin)\n","sub_path":"reviews_list/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"495947810","text":"#!/usr/bin/env python3\n\"\"\"\nplot ForestGemini per-worker patch HDF5 files (e.g. 1000-10000+ files per time step)\n\"\"\"\n\nfrom pathlib import Path\nimport argparse\nimport logging\n\nimport gemini3d.patch.plot as plot\n\nplot_vars = {\n \"ne\",\n \"Te\",\n \"Ti\",\n \"J1\",\n \"J2\",\n \"J3\",\n \"v1\",\n \"v2\",\n \"v3\",\n}\n\n\np = argparse.ArgumentParser()\np.add_argument(\"indir\", help=\"ForestGemini patch .h5 data directory\")\np.add_argument(\"-var\", help=\"variable to plot\", nargs=\"+\", default=plot_vars)\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\nargs = p.parse_args()\n\nif args.verbose:\n logging.basicConfig(level=logging.DEBUG)\n\nindir = Path(args.indir).expanduser()\nif not indir.is_dir():\n raise NotADirectoryError(indir)\n\nplot.patch(indir, var=set(args.var))\n","sub_path":"scripts/plot_patch.py","file_name":"plot_patch.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"219229999","text":"import cv2\nfrom PIL import ImageGrab ,Image\nimport numpy as np\nimport pyautogui,datetime,time ,threading\nimport theLib.damatu as td\n\nmethod = eval('cv2.TM_CCOEFF_NORMED')\nbegin_x =800\nbegin_y =100\ntimeTarget =Image.open(r'C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\29_3.png')\ntimeTarget =cv2.cvtColor(np.array(timeTarget, dtype=np.uint8), cv2.COLOR_RGBA2GRAY)\ntimeStamp =0\ntheCodeDict ={}\nlock = threading.Lock()\ncode_url =r'C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\code.png'\n\ndef addTime():\n global timeStamp\n while 1:\n time.sleep(1)\n timeStamp +=1\n\ndef checkTime():\n global timeTarget\n global timeStamp\n screen =ImageGrab.grab((500 ,200 ,900 ,600))\n screen =cv2.cvtColor(np.array(screen, dtype=np.uint8), cv2.COLOR_RGB2GRAY)\n res = cv2.matchTemplate(screen,timeTarget,method)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n if max_val >0.99:\n timeStamp =3\n t =threading.Thread(target=addTime)\n t.start()\n\ndef click_img(url ,d=0):\n # print(datetime.datetime.now())\n target =Image.open(url)\n img_size =target.size\n target =cv2.cvtColor(np.array(target, dtype=np.uint8), cv2.COLOR_RGBA2GRAY)\n screen =ImageGrab.grab((begin_x ,begin_y ,1400 ,800))\n screen =cv2.cvtColor(np.array(screen, dtype=np.uint8), cv2.COLOR_RGB2GRAY)\n res = cv2.matchTemplate(screen,target,method)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n if d:\n pyautogui.doubleClick(x=(begin_x +max_loc[0] +img_size[0]//2) ,y=(begin_y +max_loc[1] +img_size[1]//2) ,button='left')\n else:\n pyautogui.click(x=(begin_x +max_loc[0] +img_size[0]//2) ,y=(begin_y +max_loc[1] +img_size[1]//2) ,button='left')\n # print(datetime.datetime.now())\n\ndef check_img(url):\n target =Image.open(url)\n target =cv2.cvtColor(np.array(target, dtype=np.uint8), cv2.COLOR_RGBA2GRAY)\n screen =ImageGrab.grab((begin_x ,begin_y ,1400 ,800))\n screen =cv2.cvtColor(np.array(screen, dtype=np.uint8), cv2.COLOR_RGB2GRAY)\n res = cv2.matchTemplate(screen,target,method)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n if max_val >0.9:\n return max_loc\n else:\n return 0\n\ndef getCode():\n dmt=td.DamatuApi(\"slientcraft\",\"inwcwizard\")\n theCode =dmt.decode(code_url,200)\n lock.acquire()\n try:\n global theCodeDict\n if theCode in theCodeDict:\n theCodeDict[theCode] +=1\n else:\n theCodeDict[theCode] =1\n finally:\n lock.release()\n\ndef grabCode():\n target =Image.open(r'C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\tip_end.png')\n tip_loc =check_img(r'C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\tip_begin.png')\n left ,top=begin_x +tip_loc[0] ,begin_y +tip_loc[1]\n tip_loc =check_img(r'C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\tip_end.png')\n right ,bottom =begin_x +tip_loc[0] +target.width ,begin_y +tip_loc[1] +target.height\n tip =ImageGrab.grab((left ,top ,right ,bottom))\n tip =tip.resize((tip.width *2,90))\n code =ImageGrab.grab((1000 ,450 ,1000 +150 ,450 +90))\n code =code.resize((code.width *2 ,code.height *2) ,Image.ANTIALIAS)\n ret =Image.new('RGB', (tip.width +code.width, code.height), (255, 255, 255))\n # ret =Image.new('L', (tip.width +code.width, code.height), 255)\n ret.paste(tip ,(0 ,(ret.height -tip.height) //2 ,tip.width ,(ret.height -tip.height) //2 +tip.height))\n ret.paste(code ,(tip.width,0,ret.width,ret.height))\n ret.save(code_url, \"PNG\")\n\ndef deCode():\n global theCodeDict\n global timeStamp\n for i in range(20):\n t =threading.Thread(target=getCode)\n t.start()\n print(55-timeStamp)\n time.sleep(55 -timeStamp)\n print(theCodeDict)\n if 'ERROR' in theCodeDict:\n theCodeDict.pop('ERROR')\n if 'IERROR' in theCodeDict:\n theCodeDict.pop('IERROR')\n theCodeDict = sorted(theCodeDict.items(), key=lambda dic: dic[1])\n print(theCodeDict[-1][0])\n return theCodeDict[-1][0]\n\ndef beginWork():\n click_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\add_price.png\" ,1)\n pyautogui.typewrite('800')\n\ndef mainWork():\n click_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\add_price_button.png\")\n click_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\confirm_price_button.png\")\n while 1:\n if check_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\tip_begin.png\"):\n if check_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\refresh_code_button.png\"):\n click_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\refresh_code_button.png\")\n else:\n # print(datetime.datetime.now())\n print(timeStamp)\n grabCode()\n click_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\type_code.png\")\n print(timeStamp)\n pyautogui.typewrite(deCode())\n click_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\confirm_code_button.png\")\n break\n\n#main\npyautogui.click(x=260 ,y=1060 ,button='left')\ntime.sleep(1)\ngrabCode()\nclick_img(r\"C:\\Users\\guo\\Desktop\\thePrj\\alltobid\\type_code.png\")\ntimeStamp =50\nx =deCode()\n# pyautogui.typewrite(deCode())","sub_path":"hupai/thePrj/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":5083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"349699721","text":"# _*_ coding: utf-8 _*_\n__author__ = 'Clarence'\n__date__ = '2017/4/17 11:27'\nfrom random import Random\n\nfrom django.core.mail import send_mail\nfrom MxOnline.settings import EMAIL_FROM\nfrom users.models import EmailVerifyRecord\n\n\ndef random_str(randomlength=8):\n str = ''\n chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'\n length = len(chars) - 1\n random = Random()\n for i in range(randomlength):\n str += chars[random.randint(0, length)]\n return str\n\n\ndef sendRegisterEmail(email, send_type=\"register\"):\n emailRecord = EmailVerifyRecord()\n code = random_str(16)\n emailRecord.code = code\n emailRecord.send_type = type\n emailRecord.email = email\n emailRecord.save()\n email_title = \"\"\n email_body = \"\"\n if send_type == \"register\":\n email_title = \"幕学在线网注册激活链接\"\n email_body = \"请点击下面的链接激活你的账号: http://127.0.0.1:8000/active/{0}\".format(\n code)\n elif send_type == 'forget':\n email_title = \"幕学在线网注册密码重置链接\"\n email_body = \"请点击下面的链接重置密码: http://127.0.0.1:8000/reset/{0}\".format(\n code)\n elif send_type == \"sendEmailCode\":\n email_title = \"修改邮箱\"\n email_body = \"邮箱验证码为{0}\".format(code)\n sendStatus = send_mail(email_title, email_body, EMAIL_FROM, [email])\n if sendStatus:\n pass\n","sub_path":"apps/utils/email_send.py","file_name":"email_send.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"623664093","text":"from django.test import TestCase\r\nfrom sign.models import Guest, Event\r\nfrom django.test.utils import setup_test_environment\r\n\r\n\r\n\"\"\" 创建Django 测试 \"\"\"\r\n\r\n\r\n# Create your tests here.\r\n\r\n\r\nclass ModelTest(TestCase):\r\n\r\n @classmethod\r\n def setUpClass(cls):\r\n Event.objects.create(id=1, name=\"oneplus 6 event\", status=True, limit=2000,\r\n address='shenzhen', start_time='2016-08-31 02:18:22')\r\n Guest.objects.create(id=1, event_id=1, realname='alen',\r\n phone='13711001101', email='alen@mail.com', sign=False)\r\n\r\n @classmethod\r\n def tearDownClass(cls):\r\n pass\r\n\r\n def test_event_models(self):\r\n result = Event.objects.get(name=\"oneplus 6 event\")\r\n self.assertEqual(result.address, \"shenzhen\")\r\n self.assertTrue(result.status)\r\n\r\n def test_guest_models(self):\r\n result = Guest.objects.get(phone='13711001101')\r\n self.assertEqual(result.realname, \"alen\")\r\n self.assertFalse(result.sign)\r\n\r\n","sub_path":"guest_task/sign/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609092906","text":"import tensorflow as tf\nimport numpy as np\nimport cnnModel\nimport os\nimport pickle\nimport time\nimport getConfig\nimport sys\nimport random\ngConfig = {}\n\ndef read_data(dataset_path, im_dim, num_channels,num_files,images_per_file):\n files_names = os.listdir(dataset_path)\n print(files_names)\n # 获取训练集中训练文件的名称\n \"\"\"\n 在CIFAR10中已经为我们标注和准备好了数据,一时找不到合适的高质量的标注训练集,我们就是使用CIFAR10的来作为我们的训练集。\n 在训练集中一共有50000个训练样本,放到5个二进制文件中心,每个样本有3072个像素点,是32*3维度的\n \"\"\"\n #创建空的多维数组用于存放图片二进制数据\n dataset_array = np.zeros(shape=(num_files * images_per_file, im_dim, im_dim, num_channels))\n # 创建空的数组用于存放图片的标注信息\n dataset_labels = np.zeros(shape=(num_files * images_per_file), dtype=np.uint8)\n index = 0\n #从训练集中读取二进制数据并将其维度转换成32*32*3\n for file_name in files_names:\n\n if file_name[0:len(file_name)-1] == \"data_batch_\":\n print(\"正在处理数据 : \", file_name)\n data_dict = unpickle_patch(dataset_path + file_name)\n images_data = data_dict[b\"data\"]\n # 格式转换为32x32x3 shape.\n images_data_reshaped = np.reshape(images_data,\n newshape=(len(images_data), im_dim, im_dim, num_channels))\n # 将维度转换后的图片数据存入指定数组内\n dataset_array[index * images_per_file:(index + 1) * images_per_file, :, :, :] = images_data_reshaped\n # 将维度转换后的标注数据存入指定数组内\n dataset_labels[index * images_per_file:(index + 1) * images_per_file] = data_dict[b\"labels\"]\n index = index + 1\n return dataset_array, dataset_labels # 返回数据\n\ndef unpickle_patch(file):\n #打开文件,读取二进制文件,返回读取到的数据\n patch_bin_file = open(file, 'rb')\n patch_dict = pickle.load(patch_bin_file, encoding='bytes')#Loading the details of the binary file into a dictionary.\n return patch_dict\n\ndef create_model(session,forward_only):\n\n #用cnnModel实例化一个对象model\n model=cnnModel.cnnModel(gConfig['percent'],gConfig['learning_rate'],gConfig['learning_rate_decay_factor'])\n if 'pretrained_model'in gConfig:\n model.saver.restore(session,gConfig['pretrained_model'])\n return model\n ckpt=tf.train.get_checkpoint_state(gConfig['working_directory'])\n #判断是否已经有Model文件存在,如果model文件存在则加载原来的model并在原来的moldel继续训练,如果不存在则新建model相关文件\n if ckpt and ckpt.model_checkpoint_path:\n print(\"Reading model parameters from %s\" % ckpt.model_checkpoint_path)\n model.saver.restore(session, ckpt.model_checkpoint_path)\n# session.run(tf.global_variables_initializer())\n graph = tf.get_default_graph()\n\n return model,graph\n\n else:\n print(\"Created model with fresh parameters.\")\n session.run(tf.global_variables_initializer())\n graph = tf.get_default_graph()\n return model,graph\n#获取批量处理数据,考虑到配置不同,如果没有GPU建议将percent调小一点,即将训练集调小\ndef get_batch(data,labels,percent):\n num_elements = np.uint32(percent * data.shape[0] / 100)\n #之所以没有采用tf自带的tf.train.batch是因为那个接口对内存的消耗太大了,我们采用这种随机取index的方法简单又实用。\n n=np.random.randint(len(labels),size=num_elements)\n shuffle_datas=[]\n shuffled_labels=[]\n for i in n:\n shuffle_datas.append(data[i,:,:,:])\n shuffled_labels.append(labels[i])\n return shuffle_datas,shuffled_labels\n\n#定义训练函数\ndef train():\n \"\"\"使用BFC内存管理管理算法,tf.ConfigProto()用于GPU的管理,可以控制GPU的使用率\n #allow growth\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n # per_process_gpu_memory_fraction\n gpu_options=tf.GPUOptions(per_process_gpu_memory_fraction=0.7)\n config=tf.ConfigProto(gpu_options=gpu_options)\n 关于BFC算法:\n 将内存分块管理,按块进行空间分配和释放。\n 通过split操作将大内存块分解成用户需要的小内存块。\n 通过merge操作合并小的内存块,做到内存碎片回收\n 通过bin这个抽象数据结构实现对空闲块高效管理。\n \"\"\"\n\n config = tf.ConfigProto()\n config.gpu_options.allocator_type = 'BFC'\n\n #读取训练集的数据到内存中\n dataset_array, dataset_labels = read_data(dataset_path=gConfig['dataset_path'], im_dim=gConfig['im_dim'],\n num_channels=gConfig['num_channels'],num_files=gConfig['num_files'],images_per_file=gConfig['images_per_file'])\n #打印训练数据的维度\n print(\"Size of data : \", dataset_array.shape)\n #读取测试数据到内存中\n dataset_array_test, dataset_labels_test = read_data(dataset_path=gConfig['dataset_test'], im_dim=gConfig['im_dim'], num_channels=gConfig['num_channels'],num_files=1,images_per_file=gConfig['images_per_file'])\n #打印测试数据的维度\n print(\"Size of data : \", dataset_array_test.shape)\n\n with tf.Session(config=config) as sess:\n model,_=create_model(sess,False)\n\n step_time, accuracy = 0.0, 0.0\n current_step = 0\n previous_correct = []\n\n #shuffled_datas, shuffled_labels = get_batch(data=dataset_array, labels=dataset_labels,\n # percent=gConfig['percent'])\n #shuffled_datas_test, shuffled_labels_test = get_batch(data=dataset_array_test, labels=dataset_labels_test,\n # percent=gConfig['percent']*5)\n # 开始训练循环,这里没有设置结束条件,当学习率下降到为0时停止\n while model.learning_rate.eval()>gConfig['end_learning_rate']:\n\n shuffled_datas, shuffled_labels = get_batch(data=dataset_array, labels=dataset_labels,\n percent=gConfig['percent'])\n shuffled_datas_test, shuffled_labels_test = get_batch(data=dataset_array_test, labels=dataset_labels_test,\n percent=gConfig['percent']*5)\n\n start_time = time.time()\n step_correct=model.step(sess,shuffled_datas,shuffled_labels,False)\n step_time += (time.time() - start_time) / gConfig['steps_per_checkpoint']\n accuracy += step_correct / gConfig['steps_per_checkpoint']\n current_step += 1\n\n # 达到一个训练模型保存点后,将模型保存下来,并打印出这个保存点的平均准确率\n if current_step % gConfig['steps_per_checkpoint'] == 0:\n #如果超过三次预测正确率没有升高则改变学习率\n if len(previous_correct) > 2 and accuracy >> c = Component()\n >>> c\n \n\n >>> c += 'test'\n >>> c\n \n\n >>> c += dict(css='mycss')\n >>> c\n \n\n >>> c += dict(css='mycss')\n >>> c\n \n\n >>> c += 'test2'\n >>> sorted(c.parts.items())\n [('css', OrderedSet(['mycss'])), ('html', ['test', 'test2'])]\n\n >>> Component() + 'test1' + 'test2'\n \n\n >>> Component() + 'test1' + dict(css='mycss')\n \n\n >>> Component('test1', Component('test2'))\n \n\n >>> Component(\n ... Component('test1', css='css1'),\n ... Component('test2', Component('test3', css='css3')),\n ... )\n \n\n >>> Component((Component('test1', css='css1'), Component('test2', css='css2')))\n \n\n >>> Component(Component('test1', css='css1'), Component('test2', css='css2'))\n \n\n >>> composition.parts = Component()\n >>> c = Component(Component('test1', css='css1'), Component('test2', css='css2'))\n >>> c.render()\n 'test1test2'\n\n >>> page2 = \\\\\n ... Component() + \\\\\n ... '

Title

' + \\\\\n ... dict(css='mycss') + \\\\\n ... dict(js='myjs') + \\\\\n ... 'page body goes here'\n >>> t = (\n ... \"Title', 'page body goes here'], \"\n ... \"'js': OrderedSet(['myjs'])}>\"\n ... )\n >>> #print(repr(page2) + '\\\\n' + t)\n >>> repr(page2) == t\n True\n \"\"\"\n # pylint: disable=too-few-public-methods\n\n def __init__(self, *args, **kwargs):\n \"\"\"construct a Component\n\n >>> Component()\n \n\n >>> Component('body')\n \n\n >>> Component('body', css='css1')\n \n\n >>> t = Component('body', css='css1', js='js1')\n >>> repr(t) == (\n ... \"\"\n ... )\n True\n \"\"\"\n\n def is_iterable(obj):\n \"\"\"Returns True if object is an iterable but not a string\"\"\"\n return hasattr(obj, '__iter__') and not isinstance(obj, str)\n\n def flatten(items):\n \"\"\"Returns list of items with sublists incorporated into list\"\"\"\n items_as_iterables = list(is_iterable(i) and i or (i,) for i in items)\n return [i for j in items_as_iterables for i in j]\n\n self.parts = {\n 'html': [],\n }\n for arg in flatten(args):\n self += arg\n self += kwargs\n\n def __iadd__(self, other):\n \"\"\"add something to a component\n\n >>> page = Component('

Title

')\n >>> page += dict(css='mycss')\n >>> page += 'page body goes here'\n >>> page += dict(js='myjs')\n >>> result = (\n ... \"Title', 'page body goes here'], \"\n ... \"'js': OrderedSet(['myjs'])\"\n ... \"}>\"\n ... )\n >>> #print(page)\n >>> #print(result)\n >>> result == repr(page)\n True\n\n >>> page = Component('test')\n >>> page += dict(html='text')\n >>> page\n \n\n \"\"\"\n def rendered(obj):\n \"\"\"call the render method if necessary\"\"\"\n if not isinstance(obj, Component) and hasattr(obj, 'render'):\n return obj.render()\n return obj\n\n other = rendered(other)\n\n if isinstance(other, str):\n self.parts['html'].append(other)\n elif isinstance(other, dict):\n for key, value in other.items():\n part = self.parts.setdefault(key, OrderedSet())\n if key == 'html':\n if isinstance(value, list):\n part.extend(value)\n else:\n part.append(value)\n else:\n if isinstance(value, list):\n part |= value\n else:\n part |= [value]\n elif isinstance(other, Component):\n for key, value in other.parts.items():\n part = self.parts.setdefault(key, OrderedSet())\n if key == 'html':\n part.extend(value)\n else:\n part |= value\n return self\n\n def __add__(self, other):\n \"\"\"add a component to something else\n\n >>> (Component() + 'test1' + dict(css='mycss')) + 'test2'\n \n\n >>> Component() + 'test1' + dict(css='mycss') + dict(css='css2')\n \n \"\"\"\n result = Component()\n result += self\n result += other\n return result\n\n def __repr__(self):\n return ''.format(\n ', '.join(\n '{!r}: {!r}'.format(i, j)\n for i, j in sorted(self.parts.items())\n )\n )\n\n def render(self):\n \"\"\"renders the component\"\"\"\n composition.parts += self\n return ''.join(self.parts['html'])\n\n def __str__(self):\n return self.render()\n\n\ncomponent = Component\n\n\ndef compose(*args, **kwargs):\n \"\"\"Compose a response - DEPRECATED\"\"\"\n composition.parts += component(**kwargs)\n return ''.join(args)\n\n\ndef handler(request, handler, *rest):\n \"\"\"Component handler\"\"\"\n\n pop = request.session.__dict__.pop\n\n composition.parts = Component(\n success=pop('system_successes', []),\n warning=pop('system_warnings', []),\n error=pop('system_errors', []),\n stdout=pop('system_stdout', '')\n )\n\n result = handler(request, *rest)\n\n logger = logging.getLogger(__name__)\n logger.debug('component middleware')\n\n # TODO: clean this up, use a single alerts list with an alert type value\n success_alerts = composition.parts.parts.get('success')\n if success_alerts:\n if not hasattr(request.session, 'system_successes'):\n request.session.system_successes = []\n request.session.system_successes = list(success_alerts)\n\n warning_alerts = composition.parts.parts.get('warning')\n if warning_alerts:\n if not hasattr(request.session, 'system_warnings'):\n request.session.system_warnings = []\n request.session.system_warnings = list(warning_alerts)\n\n error_alerts = composition.parts.parts.get('error')\n if error_alerts:\n if not hasattr(request.session, 'system_errors'):\n request.session.system_errors = []\n request.session.system_errors = list(error_alerts)\n\n stdout = sys.stdout.getvalue()\n if stdout:\n renderable = (\n isinstance(result.content, str) and '{*stdout*}' in result.content\n )\n if not renderable:\n request.session.system_stdout = stdout\n\n return result\n\n# def component(*args, **kwargs):\n# \"\"\"assemble parts of a component\n#\n# >>> system.setup()\n# >>> system.css\n# OrderedSet()\n#\n# >>> component('test', css='mycss')\n# 'test'\n# >>> system.css\n# OrderedSet(['mycss'])\n#\n# >>> component(100, css='mycss')\n# '100'\n#\n# >>> component(css='mycss', html='test')\n# 'test'\n# >>> system.css\n# OrderedSet(['mycss'])\n#\n# >>> component('test', html='more', css='mycss')\n# 'testmore'\n# >>> system.css\n# OrderedSet(['mycss'])\n#\n# >>> component('test', 'two', css=['mycss','css2'], js='myjs')\n# 'testtwo'\n# >>> system.css\n# OrderedSet(['mycss', 'css2'])\n# >>> system.js\n# OrderedSet(['myjs'])\n#\n# >>> component('test', js='js2')\n# 'test'\n# >>> system.js\n# OrderedSet(['myjs', 'js2'])\n#\n# >>> component(['test1'], ('test2',), 'test3')\n# 'test1test2test3'\n#\n# >>> from mvc import DynamicView\n# >>> class MyThing(DynamicView):\n# ... def __str__(self):\n# ... return self.model\n# >>> hasattr(MyThing('test'), '__iter__')\n# False\n# >>> component(['test1'], ('test2',), 'test3', MyThing('test4'))\n# 'test1test2test3test4'\n# >>> component(MyThing('test4'))\n# 'test4'\n# >>> component(MyThing('test4'), MyThing('test5'))\n# 'test4test5'\n# >>> component((MyThing('test4'), MyThing('test5')))\n# 'test4test5'\n# >>> args = (MyThing('test4'), MyThing('test5'))\n# >>> component(args)\n# 'test4test5'\n# >>> component(*list(args))\n# 'test4test5'\n#\n# >>> system.setup()\n# >>> component('test', js=[])\n# 'test'\n# >>> system.js\n# OrderedSet()\n# \"\"\"\n# def is_iterable(item):\n# return hasattr(item, '__iter__')\n#\n# def as_iterable(item):\n# return not is_iterable(item) and (item,) or item\n#\n# def flatten(items):\n# items_as_iterables = list(is_iterable(i) and i or (i,) for i in items)\n# return [i for j in items_as_iterables for i in j]\n#\n# parts = {\n# 'html': flatten(args),\n# }\n# for key, value in kwargs.items():\n# part = parts.setdefault(key, OrderedSet())\n# if key == 'html':\n# part.extend(as_iterable(value))\n# else:\n# part |= OrderedSet(as_iterable(value))\n# for key in ['css', 'js', 'styles', 'libs', 'head', 'tail']:\n# part = getattr(system, key)\n# part |= parts.get(key, [])\n# return ''.join(map(str, parts['html']))\n","sub_path":"zoom/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":11171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268687345","text":"# coding: utf-8\n\nimport sys\nsys.path.append('../')\nimport wdfproc\n\nimport os\nimport pandas as pd\nfrom . import read_csv\nfrom . import name_handle\n\n##################################################\n# 1地点の地上気象データを取得する\n##################################################\ndef get_ground_weather_one_place(dir_path):\n \"\"\" 1地点の地上気象データを取得する\n \n Args:\n dir_path(string) : ディレクトリパス\n\n Returns:\n DataFrame : ファイルの読込結果\n \"\"\"\n \n # 地上気象データのファイル一覧取得\n file_paths = read_csv.get_file_paths(dir_path)\n\n # 気象データを読み込み、DataFrameに格納する\n ground_df = None\n for file_path in file_paths:\n \n # 地上気象データ読み込み\n df = read_csv.read_ground(file_path)\n\n # 指定した行のデータを抽出\n df1 = wdfproc.extract_row_isin(df, ('時', '時'), [9, 21])\n \n # DataFrameに追加する\n if ground_df is None:\n ground_df = df1\n else:\n ground_df = ground_df.append(df1)\n \n # 地点名を取得する\n dirname = os.path.basename(dir_path)\n elements = name_handle.elements_from_dirname_ground(dirname)\n place_name = elements['name']\n\n # 列名を変更する\n ground_df = wdfproc.rename_column_ground(ground_df, place_name)\n \n return ground_df\n \n##################################################\n# 複数地点の地上気象データを取得する\n##################################################\ndef get_ground_weather(input_dir):\n \"\"\" 複数地点の地上気象データを取得する\n \n Args:\n input_dir(string) : ディレクトリパス\n\n Returns:\n DataFrame : ファイルの読込結果\n \"\"\"\n \n # 地上の気象データが格納されたディレクトリの一覧を取得し、\n # 順番にDataFrameに格納していく\n ground_df = None\n for dir_name in os.listdir(input_dir):\n \n # 1地点の地上気象データを取得する\n dir_path = os.path.join(input_dir, dir_name)\n df = get_ground_weather_one_place(dir_path)\n \n # 気象データを結合する\n if ground_df is None:\n ground_df = df\n else:\n ground_df = pd.merge(ground_df, df, on=('日付','時'))\n \n return ground_df\n \n \n##################################################\n# 1地点の高層気象データを取得する\n##################################################\ndef get_highrise_weather_one_place(dir_path, boundary_pressure=400):\n \"\"\" 1地点の高層気象データを取得する\n \n Args:\n dir_path(string) : ディレクトリパス\n boundary_pressure(float) : 指定した気圧(hPa)より大きい指定気圧面のデータを扱う\n\n Returns:\n DataFrame : ファイルの読込結果\n \"\"\"\n \n # 高層気象データのファイル一覧取得\n file_paths = read_csv.get_file_paths(dir_path)\n\n # 気象データを読み込み、DataFrameに格納する\n highrise_df = None\n for file_path in file_paths:\n \n # 高層気象データ読み込み\n df = read_csv.read_highrise(file_path)\n \n # 指定した気圧(hPa)より大きい指定気圧面のデータを抽出する\n df = df[df['気圧(hPa)'] > boundary_pressure]\n\n # 日付と時刻データを抽出する\n date = df.loc[0,'日付']\n hour = df.loc[0,'時']\n\n # 新しい列名のPrefixを作成する\n new_column_prefix = []\n new_column_prefix.append('地上_')\n for i in range(1, len(df)):\n prefix = '{0:.0f}hPa_'.format(df.loc[i,'気圧(hPa)'])\n new_column_prefix.append(prefix)\n \n # 新しい列名を作成する\n # ex) 1000hPa_高度(m)\n new_columns = []\n for col in df.columns:\n # '日付','時', '気圧(hPa)'を除いた列を扱う\n if col not in ('日付', '時', '気圧(hPa)'):\n for prefix in new_column_prefix:\n new_column = prefix + col\n new_columns.append(new_column)\n \n # 複数列のデータを1列のデータに展開する\n new_values = []\n for col in df.columns:\n if col not in ('日付', '時', '気圧(hPa)'):\n new_values.extend(df[col].tolist())\n \n # 新しいDataFrameを作成する\n df = pd.DataFrame(new_values, index=new_columns)\n \n # 1列のDataFrameから1行のDataFrameに変換する\n df = df.T\n \n # 日付と時刻をDataFrameに追加する\n df['日付'] = date\n df['時'] = hour\n\n # DataFrameに追加する\n if highrise_df is None:\n highrise_df = df\n else:\n highrise_df = highrise_df.append(df)\n \n # 地点名を取得する\n dirname = os.path.basename(dir_path)\n elements = name_handle.elements_from_dirname_highrise(dirname)\n place_name = elements['name']\n\n # 列名を変更する\n highrise_df = wdfproc.rename_column_highrise(highrise_df, place_name)\n \n return highrise_df\n \n##################################################\n# 複数地点の高層気象データを取得する\n##################################################\ndef get_highrise_weather(input_dir):\n \"\"\" 複数地点の高層気象データを取得する\n \n Args:\n input_dir(string) : ディレクトリパス\n\n Returns:\n DataFrame : ファイルの読込結果\n \"\"\"\n \n # 高層の気象データが格納されたディレクトリの一覧を取得し、\n # 順番にDataFrameに格納していく\n highrise_df = None\n for dir_name in os.listdir(input_dir):\n \n # 1地点の高層気象データを取得する\n dir_path = os.path.join(input_dir, dir_name)\n df = get_highrise_weather_one_place(dir_path)\n \n # 気象データを結合する\n if highrise_df is None:\n highrise_df = df\n else:\n highrise_df = pd.merge(highrise_df, df, on=('日付','時'))\n \n return highrise_df","sub_path":"03.read_csv_test/wfile/get_weather.py","file_name":"get_weather.py","file_ext":"py","file_size_in_byte":6300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"279151030","text":"from __future__ import print_function\n\n__author__ = 'aleaf'\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import PatchCollection, LineCollection\n\ntry:\n from mpl_toolkits.basemap import Basemap, pyproj\n import fiona\n from fiona.crs import to_string, from_epsg\n from shapely.ops import transform\n from shapely.affinity import translate\n from descartes import PolygonPatch\n from GISio import get_proj4, shp2df\n from GISops import project, projectdf\nexcept:\n pass\nimport textwrap\n\n'''\ntry:\n import seaborn as sb\n seaborn = True\nexcept:\n seaborn = False\n'''\n\nclass ReportFigures(object):\n\n # figure sizes (based on 6 picas per inch, see USGS Illustration Standards Guide, p 34\n default_aspect = 6 / 8.0 # h/w\n tall_aspect = 7 / 8.0\n singlecolumn_width = 21/6.0\n doublecolumn_width = 42/6.0\n\n singlecolumn_size = (singlecolumn_width, singlecolumn_width * default_aspect)\n singlecolumn_sizeT = (singlecolumn_width, singlecolumn_width * tall_aspect)\n doublecolumn_size = (doublecolumn_width, doublecolumn_width * default_aspect)\n doublecolumn_sizeT = (doublecolumn_width, doublecolumn_width * tall_aspect)\n\n # title wraps\n singlecolumn_title_wrap = 50\n doublecolumn_title_wrap = 120\n\n # month abbreviations\n month = {1: 'Jan.', 2: 'Feb.', 3: 'Mar.', 4: 'Apr.', 5: 'May', 6: 'June',\n 7: 'July', 8: 'Aug.', 9: 'Sept.', 10: 'Oct.', 11: 'Nov.', 12: 'Dec.'}\n\n # fonts\n default_font = 'Univers 57 Condensed'\n title_font = 'Univers 67 Condensed'\n title_size = 9\n legend_font = 'Univers 67 Condensed'\n legend_titlesize = 9\n legend_headingsize = 8\n basemap_credits_font = 'Univers 47 Condensed Light'\n basemap_credits_fontsize = 7\n \n ymin0=False\n\n # rcParams\n plotstyle = {'font.family': default_font,\n 'font.size' : 8.0,\n 'axes.linewidth': 0.5,\n 'axes.labelsize': 9,\n 'axes.titlesize': 9,\n \"grid.linewidth\": 0.5,\n 'xtick.major.width': 0.5,\n 'ytick.major.width': 0.5,\n 'xtick.minor.width': 0.5,\n 'ytick.minor.width': 0.5,\n 'xtick.labelsize': 8,\n 'ytick.labelsize': 8,\n 'xtick.direction': 'in',\n 'ytick.direction': 'in',\n 'xtick.major.pad': 3,\n 'ytick.major.pad': 3,\n 'axes.edgecolor' : 'k',\n 'figure.figsize': doublecolumn_size}\n\n ymin0 = False\n\n def __init__(self):\n\n pass\n\n def title(self, ax, title, zorder=200, wrap=50,\n subplot_prefix='',\n capitalize=True):\n\n # save the defaults before setting\n old_fontset = mpl.rcParams['mathtext.fontset']\n old_mathtextit = mpl.rcParams['mathtext.it']\n mpl.rcParams['mathtext.fontset'] = 'custom'\n mpl.rcParams['mathtext.it'] = 'Univers 67 Condensed:italic'\n\n wrap = wrap\n title = \"\\n\".join(textwrap.wrap(title, wrap)) #wrap title\n if capitalize:\n title = title.capitalize()\n '''\n ax.text(.025, 1.025, title,\n horizontalalignment='left',\n verticalalignment='bottom',\n transform=ax.transAxes, zorder=zorder)\n '''\n if len(subplot_prefix) > 0:\n title = '$\\it{}$. '.format(subplot_prefix) + title\n # with Univers 47 Condensed as the font.family, changing the weight to 'bold' doesn't work\n # manually specify a different family for the title\n ax.set_title(title, family=self.title_font, zorder=zorder, loc='left')\n\n # reinstate existing rcParams\n mpl.rcParams['mathtext.fontset'] = old_fontset\n mpl.rcParams['mathtext.it'] = old_mathtextit\n\n def legend(self, ax, handles, labels, **kwargs):\n '''Make a legend, following guidelines in USGS Illustration Standards, p. 14\n\n ax : matplotlib.pyplot axis object\n handles : list\n matplotlib.pyplot handles for each plot\n labels : list\n labels for each plot\n kwargs : dict\n keyword arguments to matplotlib.pyplot.legend()\n '''\n\n lgkwargs = {'title': 'EXPLANATION',\n 'fontsize': self.legend_headingsize,\n 'frameon': False,\n 'loc': 8,\n 'bbox_to_anchor': (0.5, -0.25)}\n lgkwargs.update(kwargs)\n\n mpl.rcParams['font.family'] = self.title_font\n\n\n lg = ax.legend(handles, labels, **lgkwargs)\n\n plt.setp(lg.get_title(), fontsize=self.legend_titlesize)\n #reset rcParams back to default\n mpl.rcParams['font.family'] = self.default_font\n return lg\n\n def axes_numbering(self, ax, format_x=False, enforce_integers=False):\n '''\n Implement these requirements from USGS standards, p 16\n * Use commas in numbers greater than 999\n * Label zero without a decimal point\n * Numbers less than 1 should consist of a zero, a decimal point, and the number\n * Numbers greater than or equal to 1 need a decimal point and trailing zero only where significant figures dictate\n '''\n\n # enforce minimum value of zero on y axis if data is positive\n if self.ymin0 and ax.get_ylim()[0] < 0:\n ax.set_ylim(0, ax.get_ylim()[1])\n\n # so clunky, but this appears to be the only way to do it\n def number_formatting(axis_limits, enforce_integers):\n if -10 > axis_limits[0] or axis_limits[1] > 10 or enforce_integers:\n fmt = '{:,.0f}'\n elif -10 <= axis_limits[0] < -1 or 1 < axis_limits[1] <= 10:\n fmt = '{:,.1f}'\n elif -1 <= axis_limits[0] < -.1 or .1 < axis_limits[1] <= 1:\n fmt = '{:,.2f}'\n else:\n fmt = '{:,.2e}'\n \n def format_axis(y, pos):\n y = fmt.format(y)\n return y\n return format_axis\n\n format_axis = number_formatting(ax.get_ylim(), enforce_integers) \n ax.get_yaxis().set_major_formatter(mpl.ticker.FuncFormatter(format_axis))\n\n if format_x:\n format_axis = number_formatting(ax.get_xlim(), enforce_integers) \n ax.get_xaxis().set_major_formatter(mpl.ticker.FuncFormatter(format_axis))\n \n if enforce_integers:\n ax.get_yaxis().set_major_locator(mpl.ticker.MaxNLocator(integer=True))\n if format_x:\n ax.get_xaxis().set_major_locator(mpl.ticker.MaxNLocator(integer=True))\n \n # correct for edge cases of upper ylim == 1, 10\n # and fix zero to have no decimal places\n def fix_decimal(ticks):\n # ticks are a list of strings\n if float(ticks[-1]) == 10:\n ticks[-1] = '10'\n if float(ticks[-1]) == 1:\n ticks[-1] = '1.0'\n for i, v in enumerate(ticks):\n if float(v) == 0:\n ticks[i] = '0'\n return ticks\n\n try:\n [float(l._text.replace('\\u2212', '-')) for l in ax.get_xticklabels()]\n newxlabels = fix_decimal([fmt.format(float(l._text.replace('\\u2212', '-'))) for l in ax.get_xticklabels()])\n ax.set_xticklabels(newxlabels)\n except:\n pass\n\n try:\n [float(l._text.replace('\\u2212', '-')) for l in ax.get_yticklabels()]\n newylabels = fix_decimal([fmt.format(float(l._text.replace('\\u2212', '-'))) for l in ax.get_yticklabels()])\n ax.set_yticklabels(newylabels)\n except:\n pass\n\n def basemap_credits(self, ax, text, wrap=50, y_offset=-0.01):\n \"\"\"Add basemap credits per the Illustration Standards Guide p27\n \"\"\"\n if wrap is not None:\n text = \"\\n\".join(textwrap.wrap(text, wrap)) #wrap title\n ax.text(0.0, y_offset, text, family=self.basemap_credits_font, fontsize=self.basemap_credits_fontsize,\n transform=ax.transAxes, ha='left', va='top')\n\n def set_style(self, mpl=mpl, style='default', width='double', height='default'):\n \"\"\"\n Set dimmensions of figures to standard report sizes\n\n Not quite sure yet about the cleanest way to implement multiple customizations of the base settings (styles)\n Seaborn's methodology is somewhat complicated, but may be the way to go for multiple figure styles\n (and it also provides the option of viewing the current style settings with the axes_style() command)\n\n\n Parameters\n ----------\n width : string\n Sets the figure width to single or double column\n 'double' (default) or 'single'\n height : string\n Sets the aspect of the plot to the Matplotlib default (6:8), or a tall aspect (7:8)\n 'default' (default) or 'tall'\n \"\"\"\n\n\n if style == 'timeseries':\n self.plotstyle['grid.linewidth'] = 0\n if width == 'single':\n self.plotstyle['xtick.minor.size'] = 0\n\n if width == 'single' and height != 'tall':\n self.plotstyle['figure.figsize'] = self.singlecolumn_size\n\n elif height == 'tall' and width == 'double':\n self.plotstyle['figure.figsize'] = self.doublecolumn_sizeT\n\n elif height == 'tall' and width == 'single':\n self.plotstyle['figure.figsize'] = self.singlecolumn_sizeT\n\n else:\n pass\n\n mpl.rcParams.update(self.plotstyle)\n\n \"\"\"Set the aesthetic style of the plots.\n\n This affects things like the color of the axes, whether a grid is\n enabled by default, and other aesthetic elements.\n\n Parameters\n ----------\n style : dict, None, or one of {darkgrid, whitegrid, dark, white, ticks}\n A dictionary of parameters or the name of a preconfigured set.\n rc : dict, optional\n Parameter mappings to override the values in the preset seaborn\n style dictionaries. This only updates parameters that are\n considered part of the style definition.\n\n Examples\n --------\n >>> set_style(\"whitegrid\")\n\n >>> set_style(\"ticks\", {\"xtick.major.size\": 8, \"ytick.major.size\": 8})\n\n See Also\n --------\n axes_style : return a dict of parameters or use in a ``with`` statement\n to temporarily set the style.\n set_context : set parameters to scale plot elements\n set_palette : set the default color palette for figures\n\n \"\"\"\n\nclass basemap:\n\n figsize = ReportFigures.doublecolumn_sizeT\n\n projection = 'tmerc'\n radii = {'NAD83': (6378137.00, 6356752.314245179),\n 'NAD27': (6378206.4, 6356583.8)}\n\n drawparallels = np.array([True, False, False, False])\n drawmeridians = np.array([False, False, False, True])\n superlabels = [1, 0, 0, 1] # where to label subplot axes (l,r,t,b)\n graticule_text_color = 'k'\n graticule_label_style = None # None or '+/-'\n\n parallels_kw = {'linewidth': 0,\n 'rotation': 90.,\n 'color': '0.85',\n 'size': 8}\n\n meridians_kw = {'linewidth': 0,\n 'color': '0.85',\n 'size': 8}\n\n #resolution of boundary database to use.\n # Can be c (crude), l (low), i (intermediate), h (high), f (full) or None\n Basemap_kwargs = {'resolution': 'i'}\n\n scalebar_params = {'fontsize': 7, 'lineweight': 0.5, 'nticks': 3}\n\n\n def __init__(self, extent, ax=None, proj4=None, epsg=None, datum='NAD27', projection_shapefile=None,\n tick_interval=0.2,\n subplots=(1, 1), figsize='default', wspace=0.02, hspace=0.1,\n parallels='default', meridians='default', parallels_kw={}, meridians_kw={},\n **kwargs):\n\n self.fig = None\n\n if figsize != 'default':\n self.figsize = figsize\n if ax is None:\n # sharex and sharey arguments do not work with basemap!\n self.fig, self.axes = plt.subplots(*subplots, figsize=self.figsize)\n\n elif isinstance(ax, np.ndarray):\n self.axes = ax\n if len(np.shape(ax)) == 1:\n subplots = (1, np.shape(ax)[0])\n else:\n subplots = np.shape(ax)\n else:\n self.axes = np.array([ax])\n\n self.subplots = subplots\n\n self.maps = []\n\n self.extent_proj = extent\n self.proj4 = proj4\n self.epsg = epsg\n self.projection_shapefile = projection_shapefile\n self.datum = datum\n\n # update default basemap setting with supplied keyword args\n self.Basemap_kwargs['rsphere'] = self.radii[self.datum]\n self.Basemap_kwargs.update(kwargs)\n\n self._set_proj4() # establish a proj4 string for basemap projection regardless of input\n\n self._convert_map_extent() # convert supplied map extent to lat/lon\n\n # decide with subplot axes edges to label (sharex/sharey don't work with basemap!)\n self.subplot_ticklabels()\n\n # set graticule positions\n if parallels == 'default':\n self.parallels = np.arange(self.llcrnrlat +.15, self.urcrnrlat, tick_interval)\n else:\n self.parallels = parallels\n if meridians == 'default':\n self.meridians = np.arange(self.llcrnrlon, self.urcrnrlon, tick_interval)\n else:\n self.meridians = meridians\n\n # update default graticule/grid formatting with supplied keywords\n self.parallels_kw.update(parallels_kw)\n self.meridians_kw.update(meridians_kw)\n\n # attributes for storing Map layers\n self.layers = {} # layer dataframes\n self.patches = {} # layer patches\n self.patches_inds = {} # indicies relating patches to attributes in dataframes\n\n '''\n lon_0 is the same as the Central_Meridian in ArcMap (see Layer Properties dialogue)\n lat_0 is same as Latitude_Of_Origin\n llcrnrlon, llcrnrlat, etc. all need to be specified in lat/lon\n\n Note: the major and minor axis radii for the rsphere argument are 6378137.00,6356752.314245179 for NAD83.\n '''\n\n for i, ax in enumerate(self.axes.flat):\n m = Basemap(ax=ax, **self.Basemap_kwargs)\n\n # labels option controls drawing of labels for parallels and meridians (l,r,t,b)\n y = m.drawparallels(self.parallels, labels=self.sp_ticklabels[i][1], ax=ax, **self.parallels_kw)\n x = m.drawmeridians(self.meridians, labels=self.sp_ticklabels[i][0], ax=ax, **self.meridians_kw)\n\n # add tickmarks for the graticules\n self.add_graticule_ticks(m, x, y)\n\n # add custom scalebar to plot (for subplots, scalebar is added only to last subplot)\n #if not subplots:\n # add_scalebar(m, ax, scalebar_params, loc=scalebar_loc, color=scalebar_color, scalebar_pad=scalebar_pad)\n self.maps.append(m)\n\n self.fig.subplots_adjust(wspace=wspace, hspace=hspace)\n\n def _convert_map_extent(self):\n\n # convert map units to lat / lons using pyproj\n #if self.epsg is not None:\n # p1 = pyproj.Proj(\"+init=EPSG:{}\".format(self.epsg))\n #else:\n p1 = pyproj.Proj(self.proj4, errcheck=True, preserve_units=True)\n\n extent = self.extent_proj\n\n self.llcrnrlon, self.llcrnrlat = p1(extent[0], extent[1], inverse=True)\n self.urcrnrlon, self.urcrnrlat = p1(extent[2], extent[3], inverse=True)\n\n self.Basemap_kwargs.update({'llcrnrlon': self.llcrnrlon,\n 'llcrnrlat': self.llcrnrlat,\n 'urcrnrlon': self.urcrnrlon,\n 'urcrnrlat': self.urcrnrlat})\n\n def _read_shapefile_projection(self, shapefile):\n\n crs = fiona.open(shapefile).crs\n\n self.datum = str(crs.get('datum', self.datum))\n self.Basemap_kwargs['projection'] = str(crs.get('proj', None))\n\n for latlon in ['lat_0', 'lat_1', 'lat_2', 'lon_0']:\n self.Basemap_kwargs[latlon] = crs.get(latlon, None)\n\n '''\n {u'datum': u'NAD83',\n u'lat_0': 23,\n u'lat_1': 29.5,\n u'lat_2': 45.5,\n u'lon_0': -96,\n u'no_defs': True,\n u'proj': u'aea',\n u'units': u'm',\n u'x_0': 0,\n u'y_0': 0}\n '''\n\n def _set_proj4(self):\n\n # establish a proj4 string for basemap projection regardless of input\n if self.epsg is not None:\n self.proj4 = to_string(from_epsg(self.epsg))\n\n if self.projection_shapefile is not None:\n self._read_shapefile_projection(self.projection_shapefile)\n self.proj4 = get_proj4(self.projection_shapefile)\n\n def add_graticule_ticks(self, m, x, y):\n\n # add ticks for the graticules (basemap only gives option of lat/lon lines)\n # x and y are instances of drawmeridians and drawparallels objects in basemap\n\n # get the vertices of the lines where they intersect the axes by plumbing the dictionaries y, x, obtained above\n ylpts = [y[lat][0][0].get_data()[1][np.argmin(abs(y[lat][0][0].get_data()[0] - 0))] for lat in list(y.keys())]\n yrpts = [y[lat][0][0].get_data()[1][np.argmin(abs(y[lat][0][0].get_data()[0] - m.urcrnrx))] for lat in list(y.keys())]\n xtpts = [x[lat][0][0].get_data()[0][np.argmin(abs(x[lat][0][0].get_data()[1] - 0))] for lat in list(x.keys())]\n xbpts = [x[lat][0][0].get_data()[0][np.argmin(abs(x[lat][0][0].get_data()[1] - m.urcrnry))] for lat in list(x.keys())]\n\n # now plot the ticks as a scatter\n m.scatter(len(ylpts)*[0], ylpts, 100, c='k', marker='_', linewidths=1, zorder=100)\n m.scatter(len(yrpts)*[m.urcrnrx], yrpts, 100, c='k', marker='_', linewidths=1, zorder=100)\n m.scatter(xtpts, len(xtpts)*[0], 100, c='k', marker='|', linewidths=1, zorder=100)\n m.scatter(xbpts, len(xbpts)*[m.urcrnry], 100, c='k', marker='|', linewidths=1, zorder=100)\n\n def _get_xy_lables(self, drawlabels):\n drawlabels = np.array(drawlabels)\n return self.drawmeridians & drawlabels, self.drawparallels & drawlabels\n\n def subplot_ticklabels(self):\n\n nplots = len(self.axes.flat)\n rows, cols = self.subplots\n\n # determine which subplots are on the outside of the grid\n outside_left = list(range(nplots))[::cols]\n outside_right = list(range(nplots))[cols-1::cols]\n outside_top = list(range(nplots))[:cols]\n outside_bottom = list(range(nplots))[-cols:]\n\n sp_ticklabels = []\n for i in range(rows * cols):\n\n # set the tick labels based on whether the subplot is on the outside (tedious!)\n # (l,r,t,b)\n if nplots == 1:\n xl, yl = self._get_xy_lables([True, True, True, True])\n elif i in outside_left and i in outside_top and i in outside_bottom:\n xl, yl = self._get_xy_lables([True, False, True, True]) # L,R,T,B\n elif i in outside_left and i in outside_top:\n xl, yl = self._get_xy_lables([True, False, True, False])\n elif i in outside_top and i in outside_right and i in outside_bottom:\n xl, yl = self._get_xy_lables([False, True, True, True])\n elif i in outside_top and i not in outside_right:\n xl, yl = self._get_xy_lables([False, False, True, False])\n elif i in outside_top:\n xl, yl = self._get_xy_lables([False, True, True, False])\n elif i in outside_right and i not in outside_bottom:\n xl, yl = self._get_xy_lables([False, True, False, False])\n elif i in outside_right:\n xl, yl = self._get_xy_lables([False, True, False, True])\n elif i in outside_left and i not in outside_bottom:\n xl, yl = self._get_xy_lables([True, False, False, False])\n elif i in outside_left:\n xl, yl = self._get_xy_lables([True, False, False, True])\n else:\n xl, yl = self._get_xy_lables([False, False, False, False])\n\n sp_ticklabels.append([xl, yl])\n\n self.sp_ticklabels = sp_ticklabels\n\n def add_scalebar(self, ax=None, loc='outside_lower_right', color='k', scalebar_pad=0.08,\n length_mi=None,\n from_miles=1609.344):\n\n if ax is None:\n ax = self.axes.flat[-1]\n m = self.maps[-1]\n\n scalebar_params = self.scalebar_params\n\n previousfontfamily = plt.rcParams['font.family']\n plt.rcParams['font.family'] = plt.rcParams['font.family'] = 'Univers 57 Condensed'\n\n # scalebar properties\n units = ['Miles', 'Kilometers']\n\n\n # set scalebar length\n if length_mi is None:\n length_mi = (self.extent_proj[2] - self.extent_proj[0]) / from_miles/3\n\n major_tick_interval = length_mi // scalebar_params['nticks']\n multiplier2 = 0.621371 # multiplier to go from top units to bottom units (e.g. mi per km)\n scalebar_length_mu = major_tick_interval * scalebar_params['nticks'] * from_miles\n\n # scalebar position\n if isinstance(loc, tuple):\n position = [loc[0] * m.urcrnrx, loc[1] * m.urcrnry]\n elif loc == 'inside_upper_right':\n axis_pad = scalebar_pad * m.urcrnrx\n position = [m.urcrnrx - axis_pad * np.sqrt(scalebar_params['fontsize']/6.0) - scalebar_length_mu, m.urcrnry - 0.8*axis_pad]\n elif loc == 'inside_lower_right':\n axis_pad = scalebar_pad * m.urcrnrx\n position = [m.urcrnrx - axis_pad * np.sqrt(scalebar_params['fontsize']/6.0) - scalebar_length_mu, 0 + axis_pad]\n elif loc == 'outside_lower_right':\n axis_pad = scalebar_pad * m.urcrnr\n #position = [m.urcrnrx - axis_pad * np.sqrt(scalebar_params['fontsize']/6.0) - scalebar_length_mu, 0 - axis_pad] # 0.1 * m.urcrnrx]\n position = [0.67 * m.urcrnrx, 0 - scalebar_pad * m.urcrnry] # 0.1 * m.urcrnrx]\n elif loc == 'grid_outside_lower_right':\n axis_pad = scalebar_pad * m.urcrnrx\n position = [m.urcrnrx - axis_pad * np.sqrt(scalebar_params['fontsize']/6.0), 0 - axis_pad]\n elif loc == 'centered':\n axis_pad = 0.6 * scalebar_pad * m.urcrnrx\n position = [0.55 * (m.urcrnrx - scalebar_length_mu), 0 - axis_pad]\n elif loc == 'offcenter':\n axis_pad = 0.6 * scalebar_pad * m.urcrnrx\n position = [0.65 * (m.urcrnrx - scalebar_length_mu), 0 - axis_pad]\n else:\n axis_pad = scalebar_pad * m.urcrnrx\n position = [m.urcrnrx + axis_pad, 0 + axis_pad]\n\n # add bar line\n x = [position[0], position[0] + scalebar_length_mu]\n y = 2*[position[1]]\n\n sb = plt.Line2D(x, y, color=color, zorder=99, lw=scalebar_params['lineweight'])\n sb.set_clip_on(False)\n ax.add_line(sb)\n\n # setup position and length of ticks\n ticks = np.arange(0, length_mi, major_tick_interval, dtype=int)\n if ticks[-1] > length_mi:\n ticks = np.append(ticks, length_mi)\n tick_positions = np.array([ticks * from_miles + position[0], ticks * from_miles * multiplier2 + position[0]])\n tick_length = 0.05 * (tick_positions[0][-1] - tick_positions[0][0])\n y = np.array([[y[0], y[0] + tick_length], [y[0], y[0] - tick_length]])\n\n # convert over to axes fraction, for some reason mpl won't do 'data' coordinates\n # for annotations outside plot area\n tick_positions_ax = tick_positions/(m.urcrnrx)\n tick_length_ax = tick_length/(m.urcrnry)\n y_ax = y/(m.urcrnry)\n valignments = ['bottom','top']\n textpad = [0.5 * tick_length_ax, -0.5 * tick_length_ax] # 0 means that text is right on tick line\n\n # for each unit, then for each tick\n for n in range(2):\n for i in range(len(ticks)):\n\n # set ticks\n l = plt.Line2D(2*[tick_positions[n][i]], y[n], color=color,\n zorder=99, lw=scalebar_params['lineweight'])\n l.set_clip_on(False)\n ax.add_line(l)\n\n # add tick labels\n # -1 to tick labels is ugly kludge in response to changed annotation positioning in Mpl 1.4.3\n ax.annotate('{}'.format(ticks[i]), xy=(tick_positions_ax[n][i], y_ax[n][1]+textpad[n] -1),\n xycoords='axes fraction', fontsize=scalebar_params['fontsize'], horizontalalignment='center',\n color=color, verticalalignment=valignments[n])\n\n # add end l(unit) abels\n ax.annotate(' {}'.format(units[n]), xy=(tick_positions_ax[n][-1], y_ax[n][1]+textpad[n] -1),\n xycoords='axes fraction', fontsize=scalebar_params['fontsize'], horizontalalignment='left',\n color=color, verticalalignment=valignments[n])\n\n plt.rcParams['font.family'] = previousfontfamily\n\n def make_collection(self, shp, index_field=None,\n s=20, fc='0.8', ec='k', lw=0.5, alpha=0.5,\n color_field=None,\n cbar=False, clim=(), cmap='jet', cbar_label=None,\n simplify_patches=100,\n zorder=5,\n convert_coordinates=1,\n remove_offset=True,\n collection_name=None,\n **kwargs):\n\n if collection_name is None:\n collection_name = os.path.split(shp)[-1].split('.')[0]\n df = shp2df(shp)\n\n if index_field is not None:\n df.index = df[index_field]\n\n proj4 = get_proj4(shp)\n\n if proj4 != self.proj4:\n df['geometry'] = projectdf(df, proj4, self.proj4)\n\n # convert projected coordinate units and/or get rid z values if the shapefile has them\n if convert_coordinates != 1 or df.iloc[0]['geometry'].has_z:\n df['geometry'] = [transform(lambda x, y, z=None: (x * convert_coordinates,\n y * convert_coordinates), g)\n for g in df.geometry]\n\n # remove model offset from projected coordinates (llcorner = 0,0)\n if remove_offset:\n df['geometry'] = [translate(g,\n -1 * self.extent_proj[0],\n -1 * self.extent_proj[1]) for g in df.geometry]\n\n if simplify_patches > 0:\n df['geometry'] = [g.simplify(simplify_patches) for g in df.geometry]\n\n if 'Polygon' in df.iloc[0].geometry.type:\n print(\"building PatchCollection...\")\n inds = []\n patches = []\n for i, g in df.geometry.items():\n if g.type != 'MultiPolygon':\n inds.append(i)\n patches.append(PolygonPatch(g))\n else:\n for part in g.geoms:\n inds.append(i)\n patches.append(PolygonPatch(part))\n\n collection = PatchCollection(patches, cmap=cmap,\n facecolor=fc, linewidth=lw, edgecolor=ec, alpha=alpha,\n )\n\n elif 'LineString' in df.geometry[0].type:\n print(\"building LineCollection...\")\n inds = []\n lines = []\n for i, g in df.geometry.items():\n if 'Multi' not in g.type:\n x, y = g.xy\n inds.append(i)\n lines.append(list(zip(x, y)))\n # plot each line in a multilinestring\n else:\n for l in g:\n x, y = l.xy\n inds.append(i)\n lines.append(list(zip(x, y)))\n\n collection = LineCollection(lines, colors=ec, linewidths=lw, alpha=alpha, zorder=zorder, **kwargs)\n #lc.set_edgecolor(ec)\n #lc.set_alpha(alpha)\n #lc.set_lw(lw)\n\n # set the color scheme (could set line thickness by same proceedure)\n if fc in df.columns:\n colors = np.array([df[fc][ind] for ind in inds])\n collection.set_array(colors)\n\n else:\n print(\"plotting points...\")\n x = np.array([g.x for g in df.geometry])\n y = np.array([g.y for g in df.geometry])\n\n collection = self.ax.scatter(x, y, s=s, c=fc, ec=ec, lw=lw, alpha=alpha, zorder=zorder, **kwargs)\n inds = list(range(len(x)))\n\n self.layers[collection_name] = df\n self.collections[collection_name] = collection\n self.collection_inds[collection_name] = inds\n\n return collection\n\n def _load_shapefile(self, shp, index_field, convert_coordinates, remove_offset, simplify):\n\n df = shp2df(shp)\n\n if index_field is not None:\n df.index = df[index_field]\n\n proj4 = get_proj4(shp)\n\n if proj4 != self.proj4:\n df['geometry'] = projectdf(df, proj4, self.proj4)\n\n # convert projected coordinate units and/or get rid z values if the shapefile has them\n if convert_coordinates != 1 or df.iloc[0]['geometry'].has_z:\n df['geometry'] = [transform(lambda x, y, z=None: (x * convert_coordinates,\n y * convert_coordinates), g)\n for g in df.geometry]\n\n # remove model offset from projected coordinates (llcorner = 0,0)\n if remove_offset:\n df['geometry'] = [translate(g,\n -1 * self.extent_proj[0],\n -1 * self.extent_proj[1]) for g in df.geometry]\n\n if simplify > 0:\n df['geometry'] = [g.simplify(simplify) for g in df.geometry]\n return df\n\n def make_patches(self, shp, index_field=None,\n simplify_patches=100,\n convert_coordinates=1,\n remove_offset=True,\n layername=None,\n **kwargs):\n\n if layername is None:\n layername = os.path.split(shp)[-1].split('.')[0]\n\n df = self._load_shapefile(shp, index_field, convert_coordinates, remove_offset, simplify_patches)\n\n print(\"building PatchCollection...\")\n inds = []\n patches = []\n for i, g in df.geometry.items():\n if g.type != 'MultiPolygon':\n inds.append(i)\n patches.append(PolygonPatch(g))\n else:\n for part in g.geoms:\n inds.append(i)\n patches.append(PolygonPatch(part))\n\n self.layers[layername] = df\n self.patches[layername] = patches\n self.patches_inds[layername] = inds # index values (for patches created from multipolygons)\n return patches, inds\n\n def add_shapefile(self, shp, index_field=None, axes=None,\n s=20, fc='0.8', ec='k', lw=0.5, alpha=0.5,\n color_field=None,\n cbar=False, clim=(), cmap='jet', cbar_label=None,\n simplify=100,\n zorder=5,\n convert_coordinates=1,\n remove_offset=True,\n layername=None,\n **kwargs):\n\n if layername is None:\n layername = os.path.split(shp)[-1].split('.')[0]\n\n if layername not in list(self.layers.keys()):\n shpobj = fiona.open(shp)\n if 'Polygon' in shpobj.schema['geometry']:\n self.make_patches(shp, index_field=index_field,\n simplify_patches=simplify,\n zorder=zorder,\n convert_coordinates=convert_coordinates,\n remove_offset=remove_offset,\n layername=layername,\n **kwargs)\n\n self.plot_patches(layername,\n fc=fc, ec=ec, lw=lw, alpha=alpha,\n color_fields=color_field,\n cbar=cbar, clim=(), cmap=cmap, cbar_label=cbar_label,\n zorder=zorder)\n else:\n print(\"geometry type not implemented yet\")\n return\n '''\n if axes is None:\n axes = self.axes.flat\n\n for ax in axes:\n df = self.layers[layername]\n patches = self.patches[layername]\n inds = self.patches_inds[layername]\n\n # set the color scheme\n if color_field is not None:\n colors = np.array([df[color_field][ind] for ind in inds])\n if len(clim) > 0:\n collection.set_clim(clim[0], clim[1])\n collection.set_array(colors)\n\n ax.add_collection(collection)\n\n if cbar:\n self.fig.colorbar(collection, ax=axes, pad=0.03, label=cbar_label)\n '''\n def plot_patches(self, layername=None, patches=None, patches_inds=None,\n color_fields=None, df=None,\n fc='0.5', ec='k', lw=0.5, alpha=0.5, zorder=1,\n clim=(), cmap='jet', normalize_cmap=False,\n cbar=False, cbar_label=False,\n axes=None,\n cbar_kw={},\n **kwargs):\n\n patches_cbar_kw = {'ax': self.axes.ravel().tolist(),\n 'fraction': 0.046,\n 'pad': 0.03,\n 'label': cbar_label}\n\n patches_cbar_kw.update(cbar_kw)\n\n if axes is None:\n axes = self.axes.flat\n\n if not isinstance(color_fields, list):\n color_fields = [color_fields]\n\n # plot patches from the basemap instance\n if layername is not None:\n if df is None:\n df = self.layers[layername]\n\n patches = self.patches[layername]\n inds = self.patches_inds[layername]\n # plot supplied patches (quicker for many basemap plots)\n else:\n patches = patches\n inds = patches_inds\n\n if color_fields[0] is None:\n color_fields = [None] * np.size(self.axes)\n elif len(clim) == 0 or clim == ('min', 'max'):\n clim = (df.min().min(), df.max().max())\n elif clim[0] == 'min':\n clim = (df.min().min(), clim[1])\n elif clim[1] == 'max':\n clim = (clim[0], df.max().max())\n else:\n pass\n\n if normalize_cmap and color_fields[0] is not None:\n cmap = Normalized_cmap(cmap, df[color_fields].values.ravel(), vmin=clim[0], vmax=clim[1]).cm\n\n for i, cf in enumerate(color_fields):\n\n collection = PatchCollection(patches, cmap=cmap,\n facecolor=fc, linewidth=lw, edgecolor=ec, alpha=alpha,\n **kwargs)\n # color patches by values in the included dataframe\n if cf is not None:\n colors = np.array([df[cf][ind] for ind in inds])\n collection.set_array(colors)\n if len(clim) > 0:\n collection.set_clim(clim[0], clim[1])\n\n axes[i].add_collection(collection)\n\n fig = self.fig\n if cbar:\n self.colorbar = fig.colorbar(collection, **patches_cbar_kw)\n\n return collection\n\n def _set_shapefile_colors(self, df, column, inds):\n\n colors = [df[column][ind] for ind in inds]\n\n\nclass Normalized_cmap:\n\n def __init__(self, cmap, values, vmin=None, vmax=None):\n\n self.values = values\n self.vmin = float(vmin)\n self.vmax = float(vmax)\n if isinstance(cmap, str):\n cmap = plt.cm.get_cmap(cmap)\n self.cmap = cmap\n\n self.normalize_cmap()\n #self.start = 0\n #self.stop = 1\n self.cm = self.shiftedColorMap(self.cmap, self.start, self.midpoint, self.stop)\n print(self.start, self.midpoint, self.stop)\n\n def normalize_cmap(self):\n \"\"\"Computes start, midpoint, and end values (between 0 and 1), to make\n a colormap using shiftedColorMap(), which will be\n * centered on zero\n \"\"\"\n\n if self.vmin is None:\n self.vmin = np.min(self.values)\n if self.vmax is None:\n self.vmax = np.max(self.values)\n\n self._compute_midpoint()\n\n def _compute_midpoint(self):\n\n low, high = self.vmin, self.vmax\n start, midpoint, stop = 0.0, 0.5, 1.0\n if high > 0 and low >= 0:\n midpoint = 0.5 + low / (2 * high)\n start = midpoint - 0.0001\n elif high <= 0 and low < 0:\n midpoint = (low - high) / (2 * low)\n stop = midpoint + 0.0001\n elif abs(low) > high:\n stop = (high-low) / (2 * abs(low))\n midpoint = start + abs(low) / (2*abs(low))\n elif abs(low) < high:\n start = (high - abs(low)) / (2 * high)\n midpoint = start + abs(low)/(2* high)\n else:\n pass\n self.start, self.midpoint, self.stop = float(start), float(midpoint), float(stop)\n\n def shiftedColorMap(self, cmap, start=0.0, midpoint=0.5, stop=1.0, name='shiftedcmap'):\n '''\n Function to offset the \"center\" of a colormap. Useful for\n data with a negative min and positive max and you want the\n middle of the colormap's dynamic range to be at zero. From:\n http://stackoverflow.com/questions/7404116/defining-the-midpoint-of-a-colormap-in-matplotlib\n\n Input\n -----\n cmap : The matplotlib colormap to be altered\n start : Offset from lowest point in the colormap's range.\n Defaults to 0.0 (no lower ofset). Should be between\n 0.0 and `midpoint`.\n midpoint : The new center of the colormap. Defaults to\n 0.5 (no shift). Should be between 0.0 and 1.0. In\n general, this should be 1 - vmax/(vmax + abs(vmin))\n For example if your data range from -15.0 to +5.0 and\n you want the center of the colormap at 0.0, `midpoint`\n should be set to 1 - 5/(5 + 15)) or 0.75\n stop : Offset from highets point in the colormap's range.\n Defaults to 1.0 (no upper ofset). Should be between\n `midpoint` and 1.0.\n '''\n\n cdict = {\n 'red': [],\n 'green': [],\n 'blue': [],\n 'alpha': []\n }\n\n # regular index to compute the colors\n reg_index = np.linspace(start, stop, 257)\n\n # shifted index to match the data\n shift_index = np.hstack([\n np.linspace(0.0, midpoint, 128, endpoint=False),\n np.linspace(midpoint, 1.0, 129, endpoint=True)\n ])\n\n for ri, si in zip(reg_index, shift_index):\n r, g, b, a = cmap(ri)\n\n cdict['red'].append((si, r, r))\n cdict['green'].append((si, g, g))\n cdict['blue'].append((si, b, b))\n cdict['alpha'].append((si, a, a))\n\n newcmap = mpl.colors.LinearSegmentedColormap(name, cdict)\n plt.register_cmap(cmap=newcmap)\n\n return newcmap","sub_path":"Figures/report_figs.py","file_name":"report_figs.py","file_ext":"py","file_size_in_byte":39610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"472004563","text":"from selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n\nclass Register_User_Page_Objects:\n Gender_radio_xpath = \"(//input[@type='radio'])[1]\"\n FirstName_textfield_xpath = \"//input[@id='customer_firstname']\"\n LastName_textfield_xpath = \"//input[@id='customer_lastname']\"\n Password_textfield_xpath = \"//input[@id='passwd']\"\n Days_dropdown_xpath = \"//select[@id='days']\"\n Month_dropdown_xpath = \"//select[@id='months']\"\n Years_dropdown_xpath = \"//select[@id='years']\"\n Company_textfield_xpath = \"//input[@id='company']\"\n Address_textfiled_xpath = \"//input[@id='address1']\"\n City_textfield_xpath = \"//input[@id='city']\"\n State_dropdown_xpath = \"//select[@id='id_state']\"\n Zipcode_textfield_xpath = \"//input[@id='postcode']\"\n Phone_textfield_xpath = \"//input[@id='phone_mobile']\"\n Alias_textfield_xpath = \"//input[@id='alias']\"\n Register_button_xpath = \"//Span[text()='Register']\"\n\n def __init__(self,driver):\n self.driver = driver\n\n def test_register_user(self,fn,ln,company,address,city,):\n wait = WebDriverWait(self.driver, 30)\n wait.until(EC.element_to_be_clickable((By.XPATH, self.Gender_radio_xpath)))\n self.driver.find_element_by_xpath(self.Gender_radio_xpath).click()\n self.driver.find_element_by_xpath(self.FirstName_textfield_xpath).send_keys(fn)\n self.driver.find_element_by_xpath(self.LastName_textfield_xpath).send_keys(ln)\n self.driver.find_element_by_xpath(self.Password_textfield_xpath).send_keys(\"Password\")\n day = self.driver.find_element_by_xpath(self.Days_dropdown_xpath)\n month = self.driver.find_element_by_xpath(self.Month_dropdown_xpath)\n year = self.driver.find_element_by_xpath(self.Years_dropdown_xpath)\n sel_day = Select(day)\n sel_day.select_by_value('5')\n sel_mon = Select(month)\n sel_mon.select_by_value('4')\n sel_year = Select(year)\n sel_year.select_by_value('1986')\n self.driver.find_element_by_xpath(self.Company_textfield_xpath).send_keys(company)\n self.driver.find_element_by_xpath(self.Address_textfiled_xpath).send_keys(address)\n self.driver.find_element_by_xpath(self.City_textfield_xpath).send_keys(city)\n state = self.driver.find_element_by_xpath(self.State_dropdown_xpath)\n sel_state = Select(state)\n sel_state.select_by_visible_text('Florida')\n self.driver.find_element_by_xpath(self.Zipcode_textfield_xpath).send_keys('14110')\n self.driver.find_element_by_xpath(self.Phone_textfield_xpath).send_keys('1141452545')\n self.driver.find_element_by_xpath(self.Alias_textfield_xpath).send_keys('Mr')\n self.driver.find_element_by_xpath(self.Register_button_xpath).click()\n\n","sub_path":"PageObjects/RegisterUserPage_Objects.py","file_name":"RegisterUserPage_Objects.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"10233300","text":"#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-\n\nimport copy, os.path as path\nfrom .toolchain import toolchain\nfrom bes.fs.file_util import file_util\nfrom bes.common.object_util import object_util\nfrom bes.common.variable import variable\nfrom bes.system.execute import execute\n\nfrom collections import namedtuple\n\nclass compiler(object):\n\n DEBUG = False\n #DEBUG = True\n \n def __init__(self, build_target):\n self.build_target = build_target\n self.toolchain = toolchain.get_toolchain(self.build_target)\n self.variables = {}\n self.variables.update(self.toolchain.compiler_environment())\n self.variables.update(self.toolchain.compiler_flags_flat())\n\n _target = namedtuple('_target', 'source, object')\n def compile_c(self, sources, objects = None, cflags = None):\n assert sources\n cflags = cflags or []\n sources = object_util.listify(sources)\n if objects:\n objects = object_util.listify(objects)\n targets = self._make_targets(sources, objects)\n\n for src, obj in targets:\n cmd = '$CC $CFLAGS %s -c $(SRC) -o $(OBJ)' % (' '.join(cflags))\n variables = copy.deepcopy(self.variables)\n variables['SRC'] = src\n variables['OBJ'] = obj\n cmd = variable.substitute(cmd, variables)\n print(cmd)\n self._execute_cmd(cmd)\n return targets\n\n def link_exe(self, exe, objects, ldflags = None):\n assert objects\n ldflags = ldflags or []\n objects = object_util.listify(objects)\n cmd = '$CC %s -o %s $LDFLAGS %s' % (' '.join(objects), exe, ' '.join(ldflags))\n cmd = variable.substitute(cmd, self.variables)\n self._execute_cmd(cmd)\n return exe\n \n def make_static_lib(self, lib, objects, arflags = None):\n assert objects\n objects = object_util.listify(objects)\n cmd = '$AR $AR_FLAGS %s %s' % (lib, ' '.join(objects))\n cmd = variable.substitute(cmd, self.variables)\n self._execute_cmd(cmd)\n return lib\n\n def make_shared_lib(self, lib, objects, ldflags = None):\n assert objects\n ldflags = ldflags or []\n objects = object_util.listify(objects)\n cmd = '$CC -shared $LDFLAGS %s %s -o %s' % (' '.join(ldflags), ' '.join(objects), lib)\n cmd = variable.substitute(cmd, self.variables)\n self._execute_cmd(cmd)\n return lib\n \n @classmethod\n def _make_targets(clazz, sources, objects):\n assert sources\n if sources and objects:\n if len(source) != len(objects):\n raise RuntimeError('sources and objects need to have the same number of items.')\n if not objects:\n objects = [ clazz._make_object_filename(s) for s in sources ]\n sources = [ path.abspath(s) for s in sources ]\n objects = [ path.abspath(o) for o in objects ]\n return [ clazz._target(*x) for x in zip(sources, objects) ]\n \n @classmethod\n def _make_object_filename(clazz, source):\n return file_util.remove_extension(source) + '.o'\n \n @classmethod\n def _execute_cmd(clazz, cmd):\n if clazz.DEBUG:\n print('COMPILER CMD: %s' % (cmd))\n return execute.execute(cmd)\n","sub_path":"lib/rebuild/toolchain/compiler.py","file_name":"compiler.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"271859472","text":"# -*- coding: utf-8 -*-\n\"\"\"\nModule for class `Bar2D`\n\nThis file is part of the **WomBat** finite element code\nused for the *Civil Engineering Finite Element Course*\nof *Ecole des Ponts ParisTech* 2017-2018\n\n@author: Jeremy Bleyer, Ecole des Ponts ParisTech,\nLaboratoire Navier (ENPC,IFSTTAR,CNRS UMR 8205)\n@email: jeremy.bleyer@enpc.fr\n\"\"\"\nfrom .generic_element import *\n\nclass Bar2D(Segment):\n \"\"\" A 2D truss element\n\n Bar2D is a Segment-type element (2 end nodes) in 2D\n with 2 degrees of freedom/node :\\n\n\n - **Kinematics**: horizontal, vertical displacement \\\n with a linear interpolation inside the element\n\n .. math:: \\{U\\}=\\\\langle u_x^1,u_y^1,u_x^2,u_y^2\\\\rangle^T\n\n - **Strains**: axial strain :math:`\\epsilon` (constant)\n - **Stresses**: normal force :math:`N` (constant)\n \"\"\"\n def __init__(self,node_list,tag=1):\n \"\"\"\n Parameters\n ----------\n\n node_list : list\n list containing two nodes\n tag : int,str\n tag of physical group\n \"\"\"\n Segment.__init__(self,node_list,tag)\n self.el_dof = 4\n self.node_dof = 2\n self.nb_stresses = 1\n self.kin_field_names = ['U_x','U_y']\n self.strain_field_names = ['eps']\n self.stresses_field_names = ['N']\n self.ext_forces_field_names = ['F_x','F_y']\n\n def rotation_matrix(self):\n \"\"\"\n Rotation matrix :math:`[R]` from global to local frame\n\n shape = (2,4)\n \"\"\"\n T = self.nodes.coor\n tang = T[1,:]-T[0,:]\n L = self.measure()\n t = tang/L\n\n # rotation matrix [r]{U_x,U_y} = {U_t}\n r = np.array([t[0],t[1]])\n # R is such that [R]{U_x1,U_y1,U_x2,U_y2} = {U_t1,U_t2}\n return np.kron(np.eye(2),r) # get a block matrix by repeating [r] twice along the diagonal,\n # equivalent to R = np.bmat([[r,np.zeros((1,2))],[np.zeros((1,2)),r]])\n\n def elementary_stiffness(self,mat,sect):\n \"\"\" Elementary stiffness matrix :math:`[K_e]` shape=(4,4)\n\n elementary stiffness in local frame is\n\n .. math:: [K_{e,loc}]=\\\\dfrac{ES}{L}\\\\begin{bmatrix} 1 & -1 \\\\\\\\ -1 & 1\\end{bmatrix}\n \"\"\"\n L = self.measure()\n E = mat.Young_modulus\n S = sect.area\n R = self.rotation_matrix()\n\n # elementary stiffness matrix in local frame\n Ke_loc = E*S/L*(np.array([[1,-1],[-1,1]]))\n\n # elementary stiffness matrix in global frame [Ke_glob] = [R]^T*[Ke_loc]*[R]\n Ke_glob = np.dot(np.dot(R.T,Ke_loc),R)\n\n return Ke_glob\n\n def elementary_thermal_vector(self,mat,sect,dilat):\n \"\"\" Elementary force vector induced by a thermal strain\n\n Parameters\n ----------\n dilat : float\n uniform thermal dilatation :math:`\\\\delta_{ther}` inside the element\n \"\"\"\n T = self.nodes.coor\n tang = T[1,:]-T[0,:]\n L = self.measure()\n tang = tang/L\n\n E = mat.Young_modulus\n S = sect.area\n\n return E*S*dilat*np.hstack((-tang,tang))\n\n def elementary_distributed_forces(self,el_force):\n \"\"\" Elementary force vector for uniform distributed loading\n\n Parameters\n ----------\n el_force = [fx,fy,cz] : array,list\n contains uniformly distributed forces :math:`(f_x,f_y)`\n\n .. note:: for the Bar2D element cz is ignored\n \"\"\"\n L = self.measure()\n fx,fy,cz = el_force\n return np.tile([fx,fy],2)*L/2.\n\n def deformation(self,Ue):\n \"\"\" Interpolation of the deformed element\n\n Parameters\n ----------\n Ue : ndarray\n nodal displacement of the current element\n\n Returns\n -------\n x_def,y_def : ndarray\n returns deformed position of the two end nodes\n \"\"\"\n Ux = Ue[0::self.node_dof]\n Uy = Ue[1::self.node_dof]\n s = np.linspace(-1,1,2)\n x = self.node_coor()[:,0]\n y = self.node_coor()[:,1]\n x_def = (1-s)/2.*(Ux[0]+x[0])+(1+s)/2.*(Ux[1]+x[1])\n y_def = (1-s)/2.*(Uy[0]+y[0])+(1+s)/2.*(Uy[1]+y[1])\n return x_def,y_def\n\n def stresses(self,Ue,mat,sect):\n \"\"\" Compute generalized stresses\n\n .. math:: \\{\\Sigma\\} = \\{N\\}\n\n Parameters\n ----------\n Ue : ndarray\n nodal values of the displacement\n \"\"\"\n L = self.measure()\n E = mat.Young_modulus\n S = sect.area\n\n #tangential displacement\n Ut = np.dot(self.rotation_matrix(),Ue)\n\n return E*S/L*(Ut[1]-Ut[0])\n\n def elementary_mass(self,mat,sect,lumped=False):\n \"\"\" Elementary mass matrix in global frame shape=(4,4)\n\n Parameters\n ----------\n lumped : bool\n if False, returns the consistent elementary mass matrix\n\n .. math:: [M_e]=\\\\rho S L\\\\begin{bmatrix} 1/3 & 1/6 \\\\\\\\ 1/6 & 1/3\\end{bmatrix}\n\n else, returns the lumped mass matrix\n\n .. math:: [M_e]=\\\\rho S L\\\\begin{bmatrix} 1/2 & 0 \\\\\\\\ 0 & 1/2\\end{bmatrix}\n\n \"\"\"\n L = self.measure()\n\n rho = mat.rho\n S = sect.area\n # elementary mass matrix\n if lumped:\n Me = rho*S*L*np.kron(np.array([[1/2.,0],[0,1/2.]]),np.eye(2))\n else:\n Me = rho*S*L*np.kron(np.array([[1/3.,1/6.],[1/6.,1/3.]]),np.eye(2))\n\n return Me\n\n def internal_forces_nl(self,DUe,Sige,Xe,mat,sect):\n \"\"\"\n Stress update for nonlinear material constitutive law with new internal\n forces contribution, internal variable increments inside the element\n and elementary tangent stiffness matrix\n\n Parameters\n ----------\n DUe : ndarray\n increment of displacement shape=(4,)\n Sige : ndarray\n previous stresses in the element shape=(1,)\n Xe : ndarray\n previous internal variables in the element, shape depends on material\n\n Returns\n -------\n fint : ndarray\n elemental contribution to internal forces vector for new stress shape=(4,)\n sig : ndarray\n new stresses (axial force) shape=(1,)\n dXe : ndarray\n internal variable increment\n Kte : ndarray\n elementary tangent stiffness matrix shape=(4,4)\n \"\"\"\n T = self.nodes.coor\n tang = T[1,:]-T[0,:]\n L = self.measure()\n t = tang/L\n R = self.rotation_matrix()\n\n S = sect.area\n\n\n DUt = np.dot(R,DUe)\n\n delta = (DUt[1]-DUt[0])/L\n\n sig,dXe,Ct = mat.constitutive_relation(delta,Sige[0]/S,Xe)\n sig *= S\n fint = sig*np.hstack((-t,t))\n\n # elementary tangent stiffness matrix in local frame\n Kte_loc = Ct*S/L*(np.array([[1,-1],[-1,1]]))\n\n # elementary tangent stiffness matrix in global frame [Ke_glob] = [R]^T*[Ke_loc]*[R]\n Kte_glob = np.dot(np.dot(R.T,Kte_loc),R)\n\n return fint,sig,dXe,Kte_glob","sub_path":"Code/wombat/element/bar2D.py","file_name":"bar2D.py","file_ext":"py","file_size_in_byte":6990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"597059766","text":"def call_counter(func):\n def helper(*args, **kwargs):\n helper.calls += 1\n return func(*args, **kwargs)\n helper.calls = 0\n helper.__name__ = func.__name__\n return helper\n\n\ndef memoize(func):\n mem = {}\n\n def memoizer(*args, **kwargs):\n key = str(args) + str(kwargs)\n if key not in mem:\n mem[key] = func(*args, **kwargs)\n return mem[key]\n return memoizer\n\n\n@call_counter\n@memoize\ndef levenshtein(s, t):\n if s == \"\":\n return len(t)\n if t == \"\":\n return len(s)\n if s[-1] == t[-1]:\n cost = 0\n else:\n cost = 1\n\n res = min([levenshtein(s[:-1], t)+1,\n levenshtein(s, t[:-1])+1,\n levenshtein(s[:-1], t[:-1]) + cost])\n return res\n\n\ndef iterative_levenshtein(s, t, **weight_dict):\n \"\"\" \n iterative_levenshtein(s, t) -> ldist\n ldist is the Levenshtein distance between the strings \n s and t.\n For all i and j, dist[i,j] will contain the Levenshtein \n distance between the first i characters of s and the \n first j characters of t\n\n weight_dict: keyword parameters setting the costs for characters,\n the default value for a character will be 1\n \"\"\"\n rows = len(s)+1\n cols = len(t)+1\n\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n w = dict((x, (1, 1, 1)) for x in alphabet + alphabet.upper())\n if weight_dict:\n w.update(weight_dict)\n\n dist = [[0 for x in range(cols)] for x in range(rows)]\n # source prefixes can be transformed into empty strings\n # by deletions:\n for row in range(1, rows):\n dist[row][0] = dist[row-1][0] + w[s[row-1]][0]\n # target prefixes can be created from an empty source string\n # by inserting the characters\n for col in range(1, cols):\n dist[0][col] = dist[0][col-1] + w[t[col-1]][1]\n\n for col in range(1, cols):\n for row in range(1, rows):\n deletes = w[s[row-1]][0]\n inserts = w[t[col-1]][1]\n subs = max((w[s[row-1]][2], w[t[col-1]][2]))\n if s[row-1] == t[col-1]:\n subs = 0\n else:\n subs = subs\n dist[row][col] = min(dist[row-1][col] + deletes,\n dist[row][col-1] + inserts,\n dist[row-1][col-1] + subs) # substitution\n for r in range(rows):\n print(dist[r])\n\n return dist[row][col]\n","sub_path":"src/advanced/levenshtein.py","file_name":"levenshtein.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"1957199","text":"\"\"\"Test for stocal.examples\n\nMost tests simply check that the example can be run without error.\n\"\"\"\nimport unittest\nimport sys\nfrom stocal.tests.test_transitions import TestReactionRule, TestMassAction\n\nfrom stocal.examples.pre2017 import DegradationRule\nfrom stocal.examples.pre2017 import LigationRule\nfrom stocal.examples.pre2017 import AutoCatalysisRule\n\n\nclass TestBrusselator(unittest.TestCase):\n \"\"\"Test examples.brusselator\"\"\"\n def setUp(self):\n self.stdout = sys.stdout\n sys.stdout = open('/dev/null', 'w')\n\n def tearDown(self):\n sys.stdout = self.stdout\n\n def test_example(self):\n \"\"\"test running the module\"\"\"\n import stocal.examples.brusselator\n\n\nclass TestEvents(unittest.TestCase):\n \"\"\"Test examples.events\"\"\"\n def test_example(self):\n \"\"\"test process instantiation\"\"\"\n from stocal.examples.events import process\n for _ in process.trajectory({}, steps=100):\n pass\n\n\nclass TestPre2017(unittest.TestCase):\n \"\"\"Test examples.pre2017\"\"\"\n def test_example(self):\n \"\"\"test process instantiation\"\"\"\n from stocal.examples.pre2017 import process\n for _ in process.trajectory({}, steps=100):\n pass\n\n\nclass TestPre2017Rule(TestReactionRule):\n \"\"\"Base class for rules used in pre2017\"\"\"\n def setUp(self):\n self.rule = self.Rule()\n\n def num_novel_reactions(self, *reactants):\n \"\"\"Number of transitions returned by novel_reactions\"\"\"\n return sum(1 for _ in self.rule.novel_reactions(*reactants))\n\n\nclass TestPre2017DegradationRule(TestPre2017Rule):\n \"\"\"Tests pre2017.DegradationRule\"\"\"\n Rule = DegradationRule\n\n def test_novel_reactions_number_of_reactions(self):\n \"\"\"Assert correct number of inferred transitions\"\"\"\n for i in range(1, 11):\n reactant = i*'a'\n self.assertEqual(self.num_novel_reactions(reactant), (i-1))\n\n def test_infer_transitions_length_of_products(self):\n \"\"\"Assert correct lengths of transition products\"\"\"\n for i in range(1, 11):\n reactant = i*'a'\n for trans in self.rule.novel_reactions(reactant):\n l = sum(n*len(p) for p, n in trans.products.items())\n self.assertEqual(l, i)\n\n\nclass TestPre2017Degradation(TestMassAction):\n \"\"\"Tests pre2017.Degradation.Transition\"\"\"\n class Transition(DegradationRule.Transition):\n \"\"\"Provides default constant for Reaction tests\"\"\"\n def __init__(self, reactants, products, c=1.):\n super(TestPre2017Degradation.Transition, self).__init__(\n reactants, products, c)\n\n\nclass TestPre2017LigationRule(TestPre2017Rule):\n \"\"\"Tests for pre2017.LigationRule\"\"\"\n Rule = LigationRule\n\n def test_novel_reactions_number_of_reactions(self):\n \"\"\"Assert correct number of inferred transitions\"\"\"\n self.assertEqual(self.num_novel_reactions('a', 'b'), 2)\n self.assertEqual(self.num_novel_reactions('a', 'a'), 2)\n\n\nclass TestPre2017Ligation(TestMassAction):\n \"\"\"Tests for pre2017.Ligation.Transition\"\"\"\n class Transition(LigationRule.Transition):\n \"\"\"Provides default constant for Reaction tests\"\"\"\n def __init__(self, reactants, products, c=1.):\n super(TestPre2017Ligation.Transition, self).__init__(\n reactants, products, c)\n\n\nclass TestPre2017AutoCatalysisRule(TestPre2017Rule):\n \"\"\"Tests for pre2017.AutoCatalysisRule\"\"\"\n Rule = AutoCatalysisRule\n\n def test_novel_reactions_number_of_reactions(self):\n \"\"\"Assert correct number of inferred transitions\"\"\"\n self.assertEqual(self.num_novel_reactions('a', 'b', 'aa'), 0)\n self.assertEqual(self.num_novel_reactions('a', 'b', 'ab'), 1)\n self.assertEqual(self.num_novel_reactions('a', 'b', 'ba'), 1)\n self.assertEqual(self.num_novel_reactions('a', 'a', 'aa'), 2)\n self.assertEqual(self.num_novel_reactions('ab', 'abab', 'ababab'), 2)\n\n\nclass TestPre2017AutoCatalysis(TestMassAction):\n \"\"\"Tests for pre2017.AutoCatalysis.Transition\"\"\"\n class Transition(AutoCatalysisRule.Transition):\n \"\"\"Provides default constant for Reaction tests\"\"\"\n def __init__(self, reactants, products, c=1.):\n super(TestPre2017AutoCatalysis.Transition, self).__init__(\n reactants, products, c)\n\n\nclass TestTypedRules(TestReactionRule):\n from stocal.examples.typed_rules import Polymerization as Rule\n from stocal.examples.typed_rules import ABlock, BBlock\n\n def test_infer_transitions_signature(self):\n rule = self.Rule()\n transitions = list(rule.infer_transitions({self.ABlock('a'): 2},\n {self.BBlock('z'): 1}))\n self.assertEqual(len(transitions), 2)\n\n transitions = list(rule.infer_transitions({self.ABlock('a'): 1},\n {self.ABlock('a'): 1, self.BBlock('z'): 1}))\n self.assertEqual(len(transitions), 0)\n\n\nclass TestTemperatureCycle(unittest.TestCase):\n \"\"\"Test temperature_cycle example\"\"\"\n def test_example(self):\n \"\"\"test process instantiation\"\"\"\n from stocal.examples.temperature_cycle import process\n for _ in process.trajectory({}, steps=100):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"stocal/tests/test_examples.py","file_name":"test_examples.py","file_ext":"py","file_size_in_byte":5330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"107938174","text":"n=int(input())\nl=list(map(int,input().split()))\nx=[]\nc=1\na=l\nfor i in range(n):\n\tb=a[i]\n\ta[i]=1\n\tfor j in a:\n\t\tc=c*j\n\tx.append(str(c))\n\tc=1\n\ta[i]=b\nprint(\" \".join(x))\n","sub_path":"product_list_except_that_ele.py","file_name":"product_list_except_that_ele.py","file_ext":"py","file_size_in_byte":167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"3534638","text":"import com.ihsan.foundation.pobjecthelper as phelper\r\n\r\ndef formSetDataEx(UIDefList, Parameter):\r\n UIDefList.SetData('uipmc', Parameter.FirstRecord.key)\r\n\r\ndef SimpanData(config, parameter, returnpacket):\r\n rec = parameter.uipmc.GetRecord(0)\r\n app_id = rec.key.split('=')\r\n config.BeginTransaction()\r\n try:\r\n helper = phelper.PObjectHelper(config)\r\n iAppt = helper.GetObject('MustahiqCorporate', app_id[-1])\r\n #iAppt = config.AccessPObject(app_id)\r\n iAppt.MustahiqName = rec.MustahiqName\r\n iAppt.MustahiqAddress = rec.MustahiqAddress\r\n iAppt.MustahiqAddressKelurahan = rec.MustahiqAddressKelurahan\r\n iAppt.MustahiqAddressKecamatan = rec.MustahiqAddressKecamatan\r\n iAppt.MustahiqPostalCode = rec.MustahiqPostalCode\r\n iAppt.MustahiqReferenceBy = rec.MustahiqReferenceBy\r\n iAppt.MustahiqPhoneNumber = rec.MustahiqPhoneNumber\r\n iAppt.CPName = rec.CPName\r\n iAppt.CPPhoneNumber = rec.CPPhoneNumber\r\n iAppt.CPMobileNumber = rec.CPMobileNumber\r\n iAppt.IdPropinsi = rec.GetFieldByName('LPropinsi.IdPropinsi')\r\n for i in range(parameter.uipBankAccount.recordCount):\r\n acc = parameter.uipBankAccount.GetRecord(i)\r\n BankKey = acc.BankAccountId\r\n if BankKey==0:\r\n BankKey = acc.key\r\n bAcc = helper.CreatePObject('MustahiqBankAccount', BankKey)\r\n bAcc.MustahiqId = iAppt.MustahiqId\r\n bAcc.BankAccountName = acc.BankAccountName\r\n bAcc.BankAccountNo = acc.BankAccountNo\r\n bAcc.IsDefault = acc.IsDefault\r\n bAcc.BankCode = acc.GetFieldByName('LBank.BankCode')\r\n else:\r\n bAcc = helper.GetObject('MustahiqBankAccount', BankKey)\r\n bAcc.MustahiqId = iAppt.MustahiqId\r\n bAcc.BankAccountName = acc.BankAccountName\r\n bAcc.BankAccountNo = acc.BankAccountNo\r\n bAcc.IsDefault = acc.IsDefault\r\n bAcc.BankCode = acc.GetFieldByName('LBank.BankCode')\r\n config.Commit()\r\n except:\r\n config.Rollback()\r\n raise\r\n","sub_path":"dialogs/Mustahiq/fMustahiqCorpEdit_data.py","file_name":"fMustahiqCorpEdit_data.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"225180738","text":"# coding=utf-8\nimport os\n\nfrom django.contrib import admin\nfrom django.utils.html import format_html\nfrom numpy.core.defchararray import strip\nfrom pip._vendor.distlib._backport import shutil\n\nfrom ModelToSQL.settings import BASE_DIR, TEMP_IMAGE_DIR\n#from splice.app import handleSplice\n#from identify.app import handleIdentify\nfrom preprocess.app import handlePreprocess\nfrom common import generic\nfrom offlineTask.models import OfflineTask, SingleImageInfo, UploadForm, OfflineMapManage\nimport datetime\nfrom identify.tasks import handleIdentify\nfrom splice.tasks import handleSplice\nfrom App.detect_project.predict_my import func_predict\n\nclass OfflineTaskAdmin(generic.BOAdmin):\n\n def identify_status(self):\n if self.identify_status == 'u':\n return '未识别'\n elif self.identify_status == 'd':\n return '已确认'\n elif self.identify_status == 'p':\n url = '/admin/offlineTask/predictresult/%s/' % (self.id) # 跳转的超链接\n url_text = '请确认识别结果' # 显示的文本\n return format_html(u'{}'.format(url, url_text))\n identify_status.allow_tags = True\n identify_status.short_description = '识别状态'\n\n def splice_status(self):\n if self.splice_status == 'u':\n return '未拼接'\n elif self.splice_status == 'd':\n return '已完成'\n elif self.splice_status == 'p':\n return '正在拼接'\n splice_status.allow_tags = True\n splice_status.short_description = '拼接状态'\n\n def preprocess_status(self):\n if self.preprocess_status == 'u':\n return '未处理'\n elif self.preprocess_status == 'd':\n return '已完成'\n elif self.preprocess_status == 'p':\n return '正在预处理'\n preprocess_status.allow_tags = True\n preprocess_status.short_description = '预处理状态'\n\n def comparison_status(self):\n if self.comparison_status == 'u':\n return '未比对'\n elif self.comparison_status == 'd':\n return '已完成'\n elif self.comparison_status == 'p':\n return '正在比对'\n comparison_status.allow_tags = True\n comparison_status.short_description = '比对状态'\n\n list_per_page = 10\n actions_on_bottom = True\n actions_on_top = False\n list_display = ['begin', 'title', identify_status, splice_status, preprocess_status, comparison_status]\n list_display_links = ['title']\n list_filter = ['title']\n #search_fields = ['title']\n fields = (\n ('title'),('description'),('imageUploadPath')\n )\n form = UploadForm\n actions = ['image_todo']\n date_hierarchy = 'begin'\n\n def get_queryset(self, request):\n return super(OfflineTaskAdmin,self).get_queryset(request).filter(end__gt=datetime.date.today())\n\n def image_todo(self,request,queryset):\n global title\n identifyNum = 0\n spliceNum = 0\n users = OfflineTask.objects.all()\n if queryset is not None:\n for title in queryset:\n for user in users:\n if user.id == title.id:\n model_image_list = user.imagesOriginPathList.split(\",\")\n if model_image_list is not None:\n for item in model_image_list:\n newItem = item.replace(\"'\", '').replace(\"[\", '').replace(\"]\",'').replace(' ','')\n queryset.update(preprocess_status='p')\n handlePreprocess(user,newItem)\n identifyNum = identifyNum + 1\n spliceNum = spliceNum + 1\n if identifyNum%10 == 0:\n queryset.update(identify_status='p')\n print(\"起进程识别程序\")\n handleIdentify.delay(user)\n if spliceNum%10 == 0:\n queryset.update(splice_status='p')\n print(\"起进程拼接程序\")\n handleSplice.delay(user)\n queryset.update(splice_status='d',preprocess_status='d')\n image_todo.short_description = \"开始处理\"\n\nclass OfflineMapManageAdmin(admin.ModelAdmin):\n list_per_page = 10\n actions_on_bottom = True\n actions_on_top = False\n list_display = ['addTime','mapNickName','mapDescription']\n list_display_links = ['mapNickName']\n fields = (\n ('mapNickName'), ('mapDescription')\n )\n date_hierarchy = 'addTime'\n\nadmin.site.register(OfflineTask, OfflineTaskAdmin)\nadmin.site.register(OfflineMapManage, OfflineMapManageAdmin)\n","sub_path":"offlineTask/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"621626071","text":"#!/usr/bin/python3\nimport random\nimport rl_base\n\nSEPARATOR = \"_\"\nDISCOUNT_RATE = 0.7\n\n\nclass ReinformacementLearning(rl_base.RLBase): \n\n def __init__(self, simulator):\n \"\"\"\n Constructor of a model based reinforcement learning\n \"\"\"\n rl_base.RLBase.__init__(self, simulator)\n # values_map is the value-functions from one state at time t to a real \n # number\n self._values_map = {}\n self.init_values_map()\n # transition_map is the transition-function from one state to another\n # state with an action to a probability\n self._transition_map = {}\n self.init_transition_map()\n # quality_map is the q-function from one state and an action at time t \n # to a real number\n self._quality_map = {}\n # policy_map is the pi-function from one state to an action\n self._policy_map = {}\n\n\n def value_iteration(self, epsilon):\n \"\"\"\n Perform value iteration\n \"\"\"\n max_value_diff = float(\"inf\")\n while max_value_diff >= epsilon:\n self._t += 1\n for from_state in self._states_set:\n for encoded_action in self._actions_set:\n # set quality for each state-action combination\n self.set_quality(self._t, from_state, encoded_action)\n # update the policy and value using the max quality action at \n # the current state\n max_qtsa_action, max_qtsa = self.get_max_quality(self._t, from_state)\n self.set_policy(from_state, max_qtsa_action)\n self.set_value(self._t, from_state, max_qtsa)\n max_value_diff = self.get_max_value_diff(self._t)\n # print(self._t)\n return self._policy_map\n\n\n def get_action(self):\n \"\"\"\n Get an action to execute from the curren state\n \"\"\"\n from_state = self.get_cur_state()\n action = self._policy_map.get(from_state)\n if action is None:\n return None, None, float(\"-inf\")\n action_decoded = self.decode_action(action)\n # quality = self.get_quality(self._t, from_state, action)\n return action_decoded.get(\"ax\"), action_decoded.get(\"ay\"), 0\n\n\n def set_policy(self, from_state, action):\n \"\"\"\n Set policy for from_state to action\n \"\"\"\n self._policy_map[from_state] = action\n\n\n def get_max_value_diff(self, t):\n \"\"\"\n Get the max diff of values in the state set\n \"\"\"\n max_diff = float(\"-inf\")\n for from_state in self._states_set:\n diff = abs(\n self.get_value(t, from_state) - self.get_value(t-1, from_state))\n max_diff = max(max_diff, diff)\n return max_diff\n\n\n def set_quality(self, t, from_state, action):\n \"\"\"\n Set the quality value\n \"\"\"\n if not self._quality_map.get(t):\n self._quality_map[t] = {}\n qt = self._quality_map.get(t)\n if not qt.get(from_state):\n qt[from_state] = {}\n qts = qt.get(from_state)\n\n if (self.will_crash(from_state, action) or \n self.will_stay(from_state, action)):\n # Set invalid states to negative infinity so they are the smallest\n qts[action] = float(\"-inf\")\n else:\n qts[action] = self.get_quality(t, from_state, action)\n\n\n def get_quality(self, t, from_state, action):\n \"\"\"\n Calculate the quality value\n \"\"\"\n sigma = 0\n for to_state in self._states_set:\n sigma += (self.get_transition(from_state, action, to_state) * \n self.get_value(t-1, to_state))\n return self.reward(from_state, action) + self._gamma * sigma\n\n\n def get_max_quality(self, t, from_state):\n \"\"\"\n Get the max quality for the state at given time.\n \"\"\"\n max_qtsa = float(\"-inf\")\n max_action = \"\"\n qt = self._quality_map.get(self._t)\n if qt is not None:\n qts = qt.get(from_state)\n if qts is not None:\n for action in qts:\n qtsa = qts.get(action)\n if qtsa > max_qtsa:\n max_qtsa = qtsa\n max_action = action\n return max_action, max_qtsa\n\n\n def init_values_map(self):\n \"\"\"\n Initialize the value lookups by specifiying the V0 lookup.\n \"\"\"\n for state in self._states_set:\n self.set_value(0, state, 0)\n\n def set_value(self, t, from_state, value):\n \"\"\"\n Set value for the time and the state\n \"\"\"\n v_lookup = self._values_map.get(t)\n if v_lookup is None:\n v_lookup = {}\n self._values_map[t] = v_lookup\n v_lookup[from_state] = value\n\n\n def get_value(self, t, from_state):\n \"\"\"\n Get value for the time and the state\n \"\"\"\n vt = self._values_map.get(t)\n if vt is not None:\n return vt.get(from_state) or 0\n return 0\n \n\n def init_transition_map(self):\n \"\"\"\n Inititalize the transition map with all reachable state from all state\n \"\"\"\n count = 0\n for from_state in self._states_set:\n count += 1\n self._transition_map[from_state] = {}\n from_decoded = self.decode_state(from_state)\n for encoded_action in self._actions_set:\n if self._simulator.track.isFinish(\n from_decoded.get(\"x\"), from_decoded.get(\"y\")):\n # Do not record transition for the finish state\n continue\n\n if not self.will_crash(from_state, encoded_action):\n to_state = self.get_cur_state()\n self._transition_map[from_state][encoded_action] = to_state\n\n\n def get_transition(self, from_state, encoded_action, to_state):\n \"\"\"\n Get the transition. Reachable to_state returns 1. Unreachable returns 0.\n \"\"\"\n if (self._transition_map.get(from_state) and \n self._transition_map.get(from_state).get(encoded_action) == to_state):\n return 1\n else:\n return 0\n","sub_path":"Project7/rl_model_based.py","file_name":"rl_model_based.py","file_ext":"py","file_size_in_byte":6234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"235189487","text":"#!/usr/bin/env python\n#coding=utf-8\n\nfrom aliyunsdkcore.client import AcsClient\nfrom aliyunsdkecs.request.v20140526.DescribeEipAddressesRequest import DescribeEipAddressesRequest\nfrom aliyunsdkecs.request.v20140526.ReleaseEipAddressRequest import ReleaseEipAddressRequest\nfrom aliyunsdkecs.request.v20140526.UnassociateEipAddressRequest import UnassociateEipAddressRequest\nfrom aliyunsdkecs.request.v20140526.AllocateEipAddressRequest import AllocateEipAddressRequest\nfrom aliyunsdkecs.request.v20140526.AssociateEipAddressRequest import AssociateEipAddressRequest\nfrom aliyunsdkalidns.request.v20150109.UpdateDomainRecordRequest import UpdateDomainRecordRequest\nimport json\nimport time\n\n# Aliyun access key\nclient = AcsClient('AccessKeyID', 'AccessKeySecret', 'RegionId')\necsInstanceId=\"ecsInstanceId\"\ndnsRecordId=\"dnsRecordId\"\n\n# AllocationId\nrequest = DescribeEipAddressesRequest()\nrequest.set_accept_format('json')\nresponse = client.do_action_with_exception(request)\neipInstanceId=json.loads(str(response, encoding='utf-8'))['EipAddresses']['EipAddress'][0]['AllocationId']\nprint(\"eip get info done.\")\n\n# UnassociateEip\nrequest = UnassociateEipAddressRequest()\nrequest.set_accept_format('json')\nrequest.set_InstanceId(ecsInstanceId)\nrequest.set_AllocationId(eipInstanceId)\nresponse = client.do_action_with_exception(request)\nprint(\"ecs unassociate eip address done.\")\n\n# Take a rest and too tired\ntime.sleep(3)\n\n# ReleaseEipAddress\nrequest = ReleaseEipAddressRequest()\nrequest.set_accept_format('json')\nrequest.set_AllocationId(eipInstanceId)\nresponse = client.do_action_with_exception(request)\nprint(\"eip release instance done.\")\n\n# AllocateEipAddress\nrequest = AllocateEipAddressRequest()\nrequest.set_accept_format('json')\nrequest.set_Bandwidth(\"1\")\nrequest.set_ISP(\"BGP\")\nrequest.set_InternetChargeType(\"PayByTraffic\")\nresponse = client.do_action_with_exception(request)\neipAddress=json.loads(str(response, encoding='utf-8'))['EipAddress']\neipInstanceId=json.loads(str(response, encoding='utf-8'))['AllocationId']\nprint(\"eip allocate done.\")\n\n# Take a rest and too tired\ntime.sleep(3)\n\n# AssociateEipAddress\nrequest = AssociateEipAddressRequest()\nrequest.set_accept_format('json')\nrequest.set_InstanceId(ecsInstanceId)\nrequest.set_AllocationId(eipInstanceId)\nresponse = client.do_action_with_exception(request)\nprint(\"ecs associate eip address done.\")\n\n# UpdateDomainRecord\nrequest = UpdateDomainRecordRequest()\nrequest.set_accept_format('json')\nrequest.set_RecordId(dnsRecordId)\nrequest.set_RR(\"i.love.china\")\nrequest.set_Type(\"a\")\nrequest.set_Value(eipAddress)\nrequest.set_TTL(60)\nresponse = client.do_action_with_exception(request)\nprint(\"update dns record done.\")\n\n# Good lucky\nprint(\"--------Cordage---------\")\nprint(\"| Please enjoy |\")\nprint(\"------I Love China------\")\n","sub_path":"src/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"65687265","text":"\"\"\"\n{\n \"author\": \"Yucheng Huang\",\n \"difficulty\": \"easy\",\n \"link\": \"https://leetcode.com/problems/power-of-three/description/\",\n \"beats\": 0.1752,\n \"category\": [\"math\"],\n \"tags\": [],\n \"questions\": []\n}\n\"\"\"\n\nclass Solution:\n def isPowerOfThree(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n res = 1\n while res <= n:\n if res == n:\n return True\n res *= 3\n return False","sub_path":"solutions/326.naive.py","file_name":"326.naive.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"78600669","text":"# Brittany Manuel -- CTEC 121 -- April 30, 2014\n# 3.4 Python Homework\n# !/usr/bin/env python3\n# File: week2.py\n\n\n\n\n\n# Programming Exercise 1\n# A program to calculate the volume and area of a sphere given the radius\n\nimport math\n\ndef sphere():\n\n\tprint (\"This program will calculate the volume and area of a sphere.\")\n\tprint ()\n\n\tradius = eval(input(\"Do not include units. What is the radius of the sphere? \"))\n\tvolume = ((4 / 3) * math.pi * (radius ** 3))\n\tarea = 4 * math.pi * (radius **2)\n\n\tprint ()\n\tprint (\"The volume of a sphere with the radius of\", radius, \"is\", round(volume, 2),\". The area of the sphere is\", round(area, 2), \".\")\n\t\nsphere()\n\n\n\n\n\n\n# Programming Exercise 3\n# A program to calculate molecular weight of hydrocarbons.\n\ndef hydrocarbons():\n\n\tprint (\"This program will calculate the weight of a hydrocarbon based on the number of hydrogen, carbon and oxygen atoms.\")\n\tprint ()\n\n\th, c, o = eval(input(\"Do not include units. Enter the hydrogen, carbon and oxygen amounts respectively separated by commas: \"))\n\t\n#\tprint (h, c, o)\n\t\n\ttotal_h = 1.0079 * h\n\ttotal_c = 12.011 * c\n\ttotal_o = 15.994 * o\n\n\ttotal_weight = total_h + total_c + total_o\n\n\tprint ()\n\tprint (\"For hydrogen\", h, \"carbon\", c, \"oxygen\", o, \"the total weight of each was:\", total_h, total_c, total_o,\". The total hydrocarbon weight is\", total_weight,\".\")\n\nhydrocarbons ()\n\n\n\n\n\n#Programming Exercise 5\n#A program to calculate coffee shipping cost.\n\ndef coffee():\n\n\tprint (\"This program will calculate the purchase and shipping cost from the Konditorei coffee shop.\")\n\tprint ()\n\n\tpounds = eval(input(\"Please input how many pounds of coffee you would like to purchase: \"))\n\t\t\n\tprice = 10.50\n\tshipping = 0.86\n\tflat_fee = 1.50\n\n\tcoffee_cost = (pounds * price)\n\tshipping_cost = (pounds * shipping) + flat_fee\n\n\ttotal_cost = coffee_cost + shipping_cost\n\n\tprint ()\n\tprint (\"For \", pounds, \"pounds of coffee it costs $\", round(coffee_cost, 2),\".\")\n\tprint (\"The cost of shipping the Konditorei coffee is, $\", round(shipping_cost, 2), \".\")\n\tprint (\"The total purchase price is, $\", round(total_cost, 2), \".\")\n\ncoffee ()\n\n\n\n\n\n#Programming Exercise 7\n#A program to calculate distance.\n\nimport math\ndef distance():\n\n\tprint (\"This program will calculate the distance between two points (x, y).\")\n\tprint ()\n\n\tx1, y1, x2, y2 = eval(input(\"Please input four points. In respective order to the first set of x, y followed by the second set of x, y. Inputs are to be separated by a comma: \"))\n\t\t\n\ttotal_distance = math.sqrt (((x2 - x1)**2) + ((y2 - y1) ** 2))\n\n\tprint ()\n\tprint (\"For the ordered pairs (\", x1, \",\", y1, \") and (\", x2, \",\", y2, \") the total distance is\", round(total_distance, 2))\n\ndistance ()\n\n\n\n\n\n# Programming Exercise 9\n# A program to calculate area of a triangle.\n\nimport math\ndef triangle():\n\n\tprint (\"This program will calculate the area of a tringle when given the length of its three sides a, b, and c.\")\n\tprint ()\n\n\ta, b, c = eval(input(\"Please input the three sides of a tringle. Inputs are separated by commas: \"))\n\t\t\n\ts = (a + b + c) / 2.0\n\n\t# print (s)\n\n\tarea = math.sqrt (s * (s - a) * (s - b) * (s - c))\n\n\t# print (area)\n\n\tprint ()\n\tprint (\"For the triagnel lengths of\", a, \",\", b, \", and\", c, \"the area of this tringle is, \", round(area, 4), \".\")\n\ntriangle ()\n\n\n\n\n\n#Programming Exercise 10\n#A program to calculate length of a ladder.\n\nimport math\ndef ladder():\n\n\tprint (\"This program will calculate the length of a ladder required to reach a given height when leaning against a house.\")\n\tprint ()\n\n\theight, degrees = eval(input(\"Please input the height of the ladder and the angle that the ladder is leaning in degrees. Separated by commas: \"))\n\t\t\n\tradian = (math.pi / 180) * degrees\n\n\tlength = height / (math.sin(radian))\n\n\tprint ()\n\tprint (\"For a ladder with the height of\", height, \", the length needed for a\", degrees, \"degree angle is\", round(length, 2))\n\nladder ()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Week 3/Calculate.py","file_name":"Calculate.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"60641428","text":"import pygame\nfrom pygame.locals import *\nfrom sys import exit\nfrom random import *\n\npygame.init()\npygame.display.set_caption('PID Controller Simulator')\n\nscreen_size = (1000, 500)\nscreen_color = (0, 0 ,0)\n\nscreen = pygame.display.set_mode(screen_size, 0, 32)\nscreen.fill(screen_color)\n\ncar_img = pygame.image.load(\"car.png\")\n\ndef draw_map(x1, y1, x2, y2):\n\t#Draw the Edge of the map\n\tmap_color = (0, 100, 100)\n\tmap_edge = (x1, y1)\n\tmap_edge_end = (x2, y2)\n\tpygame.draw.rect(screen, map_color, Rect(map_edge, map_edge_end))\n\t#generate the road\n\troad_color = (100, 100, 100)\n\troad_pos = (250, 250)\n\troad_radius = 240\n\tpygame.draw.circle(screen, road_color, road_pos, road_radius)\n\tpygame.draw.circle(screen, map_color, road_pos, 200)\n\ndef load_car(x, y):\n\tcar_img = pygame.image.load(\"car.png\")\n\tscreen.blit(car_img, (x, y))\n\ndef car_turn(x, y, angle):\n\tcar_image = pygame.transform.rotate(car_img, angle)\n\tscreen.blit(car_image, (x, y))\n\ndef check_key_event():\n\tfor event in pygame.event.get():\n\t\tif event.type == KEYDOWN:\n\t\t\tif(event.key == K_LEFT):\n\t\t\t\tcar_turn(10, 10, -10)\n\t\t\tif(event.key == K_RIGHT):\n\t\t\t\tcar_turn(10, 10, 10)\n\ndef run():\n\tdraw_map(10, 10, 480, 480)\n\tload_car(15, 240)\n\n\twhile 1:\n\t\tcheck_key_event()\n\t\tpygame.display.update()\n\nrun()\n","sub_path":"simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"494169758","text":"class Prostokat:\n def __init__(self,a,b):\n self.a = a\n self.b = b\n self.pole = a*b\n def __add__(self,other):\n return self.pole + other.pole\np1=Prostokat(2,3)\np2=Prostokat(2,4)\n\nwynik = p1+p2\nprint(wynik)\n","sub_path":"10-SoftwareTesting/zad3.py","file_name":"zad3.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"634366873","text":"from typing import Any\nfrom typing import Callable\nfrom typing import cast\nfrom typing import List\nfrom typing import Optional\nfrom typing import Type\nfrom typing import Union\n\nfrom fastapi_crudrouter.core import CRUDGenerator\nfrom fastapi_crudrouter.core import NOT_FOUND\nfrom fastapi_crudrouter.core._types import DEPENDENCIES\nfrom fastapi_crudrouter.core._types import PAGINATION\nfrom fastapi_crudrouter.core._types import PYDANTIC_SCHEMA as SCHEMA\n\nfrom pydantic_aioredis.store import Store\n\n\nCALLABLE = Callable[..., SCHEMA]\nCALLABLE_LIST = Callable[..., List[SCHEMA]]\n\n\nclass PydanticAioredisCRUDRouter(CRUDGenerator[SCHEMA]):\n def __init__(\n self,\n schema: Type[SCHEMA],\n store: Store,\n create_schema: Optional[Type[SCHEMA]] = None,\n update_schema: Optional[Type[SCHEMA]] = None,\n prefix: Optional[str] = None,\n tags: Optional[List[str]] = None,\n paginate: Optional[int] = None,\n get_all_route: Union[bool, DEPENDENCIES] = True,\n get_one_route: Union[bool, DEPENDENCIES] = True,\n create_route: Union[bool, DEPENDENCIES] = True,\n update_route: Union[bool, DEPENDENCIES] = True,\n delete_one_route: Union[bool, DEPENDENCIES] = True,\n delete_all_route: Union[bool, DEPENDENCIES] = True,\n **kwargs: Any\n ) -> None:\n super().__init__(\n schema=schema,\n create_schema=create_schema,\n update_schema=update_schema,\n prefix=prefix,\n tags=tags,\n paginate=paginate,\n get_all_route=get_all_route,\n get_one_route=get_one_route,\n create_route=create_route,\n update_route=update_route,\n delete_one_route=delete_one_route,\n delete_all_route=delete_all_route,\n **kwargs\n )\n self.store = store\n self.store.register_model(self.schema)\n\n def _get_all(self, *args: Any, **kwargs: Any) -> CALLABLE_LIST:\n async def route(\n pagination: PAGINATION = self.pagination,\n ) -> List[SCHEMA]:\n skip, limit = pagination.get(\"skip\"), pagination.get(\"limit\")\n skip = cast(int, skip)\n models = await self.schema.select(skip=skip, limit=limit)\n return models if models is not None else []\n\n return route\n\n def _get_one(self, *args: Any, **kwargs: Any) -> CALLABLE:\n async def route(item_id: str) -> SCHEMA:\n model = await self.schema.select(ids=[item_id])\n if model is None:\n raise NOT_FOUND\n return model[0]\n\n return route\n\n def _create(self, *args: Any, **kwargs: Any) -> CALLABLE:\n async def route(model: self.create_schema) -> SCHEMA: # type: ignore\n model = self.schema(**model.dict())\n await self.schema.insert(model)\n return model\n\n return route\n\n def _update(self, *args: Any, **kwargs: Any) -> CALLABLE:\n async def route(item_id: str, model: self.update_schema) -> SCHEMA: # type: ignore\n if await self.schema.select(ids=[item_id]) is None:\n raise NOT_FOUND\n await self.schema.update(item_id, data=model.dict())\n result = await self.schema.select(ids=item_id)\n return result[0]\n\n return route\n\n def _delete_all(self, *args: Any, **kwargs: Any) -> CALLABLE_LIST:\n async def route() -> List[SCHEMA]:\n await self.schema.delete()\n return []\n\n return route\n\n def _delete_one(self, *args: Any, **kwargs: Any) -> CALLABLE:\n async def route(item_id: str) -> SCHEMA:\n model = await self.schema.select(ids=[item_id])\n if model is None:\n raise NOT_FOUND\n await self.schema.delete(ids=[item_id])\n return model[0]\n\n return route\n","sub_path":"pydantic_aioredis/ext/FastAPI/crudrouter.py","file_name":"crudrouter.py","file_ext":"py","file_size_in_byte":3864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"120343032","text":"import random as rd\nimport numpy as np\n\n\"\"\"\nUse case:\n myData = Data_user(data_file_path)\n myData.split_set(0.8, 0.1) # portion of train set and development set\n myData.prepare_data()\n\n # get train batch\n rating, output_mask, input_mask, flag = myData.get_batch_train() # when epoch ends, it returns (None, None, None, False)\n\n # development RMSE\n rating, output_mask, input_mask, flag = myData.get_batch_dev(batch_size)\n\n # after you train for an epoch\n myData.renew_train()\n myData.renew_dev()\n myData.shuffle_data()\n\n # test RMSE\n rating, output_mask, input_mask, flag = myData.get_batch_test(batch_size)\n\"\"\"\n\n\nclass Data_user():\n def __init__(self, data_directory):\n self.used_train = 0\n self.used_dev = 0\n self.used_test = 0\n index = 0\n self.movieID2index = {}\n self.userList = {}\n with open(data_directory, 'r') as f:\n for line in f.readlines():\n userID, movieID, rating, timeStamp = line.split('::')\n timeStamp = timeStamp.strip()\n if int(movieID) not in self.movieID2index:\n self.movieID2index[int(movieID)] = index\n index += 1\n\n if userID in self.userList:\n self.userList[userID].append((int(movieID), int(float(rating)), int(timeStamp)))\n else:\n self.userList[userID] = [(int(movieID), int(float(rating)), int(timeStamp))]\n\n self.M = len(self.movieID2index) # number of movies\n self.user = len(self.userList) # number of users\n\n self.all_records = np.zeros((self.user, self.M)) # rating matrix (user by movies)\n self.output_mask = np.ones((self.user, self.M), dtype=bool)\n self.input_mask = np.ones((self.user, self.M), dtype=bool)\n self.timestamp = np.zeros((self.user, self.M))\n\n def prepare_data(self):\n i = 0\n all_keys = list(self.userList.keys())\n rd.shuffle(all_keys)\n keys_train_dev, keys_test = all_keys[0: self.num_train + self.num_dev], all_keys[self.num_train + self.num_dev:]\n for key in keys_train_dev:\n ratingsTriples = self.userList[key]\n \"\"\"ratings before i would be trainset, exclusive, that is [0, i-1]\"\"\"\n splitPoint = rd.randint(1, len(ratingsTriples) - 1)\n rd.shuffle(ratingsTriples)\n matrix_rating, input_mask, output_mask, timestamp = self.triples2vector(ratingsTriples[0: splitPoint - 1],\n ratingsTriples[splitPoint:])\n self.all_records[i] = matrix_rating\n self.input_mask[i] = input_mask\n self.output_mask[i] = output_mask\n i += 1\n\n for key in keys_test:\n ratingsTriples = self.userList[key]\n splitPoint = rd.randint(1, len(ratingsTriples) - 1)\n rd.shuffle(ratingsTriples)\n matrix_rating, input_mask, output_mask, timestamp = self.triples2vector(ratingsTriples[0: splitPoint - 1],\n ratingsTriples[splitPoint:])\n self.all_records[i] = matrix_rating\n self.input_mask[i] = input_mask\n self.output_mask[i] = output_mask\n self.timestamp[i] = timestamp\n i += 1\n\n def shuffle_data(self):\n i = 0\n keys_train_dev, keys_test = list(self.userList.keys())[0: self.num_dev + self.num_train], list(self.userList.keys())[self.num_dev + self.num_train:]\n rd.shuffle(keys_train_dev)\n for key in keys_train_dev:\n ratingsTriples = self.userList[key]\n \"\"\"ratings before i would be trainset, exclusive, that is [0, i-1]\"\"\"\n splitPoint = rd.randint(1, len(ratingsTriples) - 1)\n rd.shuffle(ratingsTriples)\n matrix_rating, input_mask, output_mask, matrix_timestamp = self.triples2vector(ratingsTriples[0: splitPoint - 1], ratingsTriples[splitPoint:])\n\n self.all_records[i] = matrix_rating\n self.input_mask[i] = input_mask\n self.output_mask[i] = output_mask\n self.timestamp[i] = matrix_timestamp\n i += 1\n\n def triples2vector(self, triples_input, triples_output):\n matrix_input = np.zeros((1, self.M))\n matrix_output = np.zeros((1, self.M))\n matrix_timestamp = np.zeros((1, self.M))\n\n for triple in triples_input:\n matrix_input[0, self.movieID2index[triple[0]]] = triple[1]\n matrix_timestamp[0, self.movieID2index[triple[0]]] = triple[2]\n input_mask = matrix_input > 0\n\n for triple in triples_output:\n matrix_output[0, self.movieID2index[triple[0]]] = triple[1]\n matrix_timestamp[0, self.movieID2index[triple[0]]] = triple[2]\n output_mask = matrix_output > 0\n\n if np.sum(np.ones((1, self.M))[np.multiply(input_mask, output_mask)]) > 0:\n print('There is overlapping')\n\n return matrix_input + matrix_output, input_mask, output_mask, matrix_timestamp\n\n def split_set(self, ratio_train, ratio_dev):\n self.num_train = int(self.user * ratio_train)\n self.num_dev = int(self.user * ratio_dev)\n self.num_test = self.user - self.num_train - self.num_dev\n\n self.index_list_train = list(range(0, self.num_train))\n self.index_list_dev = list(range(self.num_train, self.num_train + self.num_dev))\n self.index_list_test = list(range(self.num_train + self.num_dev, self.user))\n\n def get_batch_train(self, batch_size):\n if self.used_train + batch_size >= self.num_train:\n return None, None, None, False, None\n\n ratings = np.zeros((batch_size, self.M))\n out_mask = np.ones((batch_size, self.M), dtype=bool)\n in_mask = np.ones((batch_size, self.M), dtype=bool)\n timestamp = np.zeros((batch_size, self.M))\n for i in range(0, batch_size):\n ratings[i] = self.all_records[self.index_list_train[i + self.used_train], :]\n out_mask[i] = self.output_mask[self.index_list_train[i + self.used_train], :]\n in_mask[i] = self.input_mask[self.index_list_train[i + self.used_train], :]\n timestamp[i] = self.timestamp[self.index_list_train[i + self.used_train], :]\n self.used_train += batch_size\n\n return ratings, out_mask, in_mask, True, timestamp\n\n def get_batch_dev(self, batch_size):\n if self.used_dev + batch_size >= self.num_dev:\n return None, None, None, False\n ratings = np.zeros((batch_size, self.M))\n out_mask = np.ones((batch_size, self.M), dtype=bool)\n in_mask = np.ones((batch_size, self.M), dtype=bool)\n timestamp = np.zeros((batch_size, self.M))\n for i in range(0, batch_size):\n ratings[i] = self.all_records[self.index_list_dev[i + self.used_dev], :]\n out_mask[i] = self.output_mask[self.index_list_dev[i + self.used_dev], :]\n in_mask[i] = self.input_mask[self.index_list_dev[i + self.used_dev], :]\n timestamp[i] = self.timestamp[self.index_list_dev[i + self.used_dev], :]\n self.used_dev += batch_size\n return ratings, out_mask, in_mask, True, timestamp\n\n def get_batch_test(self, batch_size):\n if self.used_test + batch_size >= self.num_test:\n return None, None, None, False,None\n ratings = np.zeros((batch_size, self.M))\n out_mask = np.ones((batch_size, self.M), dtype=bool)\n in_mask = np.ones((batch_size, self.M), dtype=bool)\n timestamp = np.zeros((batch_size, self.M))\n for i in range(0, batch_size):\n ratings[i] = self.all_records[self.index_list_test[i + self.used_test], :]\n out_mask[i] = self.output_mask[self.index_list_test[i + self.used_test], :]\n in_mask[i] = self.input_mask[self.index_list_test[i + self.used_test], :]\n timestamp[i] = self.timestamp[self.index_list_test[i + self.used_test], :]\n self.used_test += batch_size\n return ratings, out_mask, in_mask, True, timestamp\n\n def renew_train(self):\n self.used_train = 0\n rd.shuffle(self.index_list_train)\n self.prepare_data()\n\n def renew_test(self):\n self.used_test = 0\n\n def renew_dev(self):\n self.used_dev = 0\n rd.shuffle(self.index_list_train)\n\n\nif __name__ == '__main__':\n myData = Data_user('../ml-1m/ratings.dat')\n myData.split_set(0.8, 0.1)\n myData.prepare_data()\n\n # index = 0\n # while True:\n # index += 1\n # print(index)\n #\n # r, i_m, o_m, flag = myData.get_batch_train(512)\n # if flag == False:\n # break\n #\n # myData.renew_train()\n # while True:\n # index += 1\n # print(index)\n #\n # r, i_m, o_m, flag = myData.get_batch_train(512)\n # if flag == False:\n # break\n\n x, input_m, output_m, flag, t_1 = myData.get_batch_train(512)\n myData.renew_test()\n test_x, input_m_t, output_m_t, _, t_2 = myData.get_batch_train(512)\n\n #\n print(x)\n print(t_1)\n # print(x[output_m])\n print(test_x)\n print(t_2)\n\n myData.renew_train()\n myData.renew_test()\n myData.shuffle_data()\n\n x, input_m, output_m, flag, t_1 = myData.get_batch_train(512)\n myData.renew_test()\n test_x, input_m_t, output_m_t, _, t_2 = myData.get_batch_train(512)\n\n print(x)\n print(t_1)\n # print(x[output_m])\n print(test_x)\n print(t_2)\n # print(output_m_t)\n # count = 0\n # for key in myData.userList:\n # if len(myData.userList[key]) >= 30:\n # count += 1\n # print('%d users' % count)\n\n","sub_path":"old_implement/Data_timestamp.py","file_name":"Data_timestamp.py","file_ext":"py","file_size_in_byte":9683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"264890029","text":"#!/usr/bin/env python\n\"\"\"\nThis module contains the variables used to run barotropic_spectral.py\n\"\"\"\nimport os\n \n# Integration options\ndt = 200 # Timestep (seconds)\nntimes = 1060 # Number of time steps to integrate\nplot_freq = 6 # Frequency of output plots in hours (if 0, no plots are made)\nM = None # Truncation (if None, defaults to # latitudes)\nr = 0.2 # Coefficient for Robert Filter\ntopo = 'isolated_mountain' #'isolated_mountain' # Topography (Earth, Mars, flat, isolated_mountain, block)\nsmooth_topo = 1 # Smooth the topography by using a Guassian filter\nintegration_method = 'rk4' # Integration method ('leapfrog', 'rk4')\nfluid_height = 10000 # Fluid height (m).\n\n# Idealized Initial Conditions (for idealized flow...future models will allow for realistic initial conditions)\nmag = 20 # Max base state zonal wind speed.\nA = 1.5 * 8e-5 # The vorticity perturbation of the flow (set to 0 for no perturbation).\nm = 4 # Zonal wavenumber around the sphere for the perturbation.\npert_center_lat = 45 # Center latitude of the sinusoidal vorticity perturbation\npert_width = 15 # Latitudinal width of the vorticity perturbation\n\n# Extra vorticity forcing\nuse_forcing = False # Add a synthetic hurricane or extra forcing to the model.\nforcing_lat = 10 # Latitude center of the forcing\nforcing_lon = 180 # Longitude center of the forcing\nforcing_amp = 10e-10 # Amplitude of the forcing (s^-2)\nforcing_time = 700 # Number of seconds to apply the forcing\n\n# I/O parameters\nfigdir = os.path.join(os.getcwd(), 'figures') # Figure directory\n\n# Diffusion parameters\ndiff_opt = 'des' # Hyperdiffusion option ('off' = none, 'del4' = del^4, 'des' = DES)\nk = 2.338e16 # Diffusion coefficient for del^4 hyperdiffusion (diff_opt='del4')\nnu = 1E-4 # Dampening coefficient for DES hyperdiffusion (diff_opt='des')\nfourier_inc = 1 # Fourier increment for computing dampening eddy sponge (diff_opt='des')\n\n# Constants\nRe = 6378100. # Radius of earth (m)\nomega = 7.292E-5 # Earth's angular momentum (s^-1)\ng = 9.81 # Gravity (m s^-2)\n","sub_path":"namelist.py","file_name":"namelist.py","file_ext":"py","file_size_in_byte":2256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61140834","text":"\"\"\"Archive views\n\nCopyright 2015 Archive Analytics Solutions - University of Liverpool\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\nimport collections\nimport json\nimport requests\nimport os\nfrom django.http import (\n StreamingHttpResponse,\n Http404,\n HttpResponse,\n)\nfrom django.core.exceptions import PermissionDenied\nfrom django.shortcuts import (\n render,\n redirect\n)\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\n\nfrom archive.forms import (\n CollectionForm,\n CollectionNewForm,\n ResourceForm,\n ResourceNewForm\n)\n\nfrom activity.signals import (\n new_resource_signal,\n new_collection_signal,\n edited_resource_signal,\n edited_collection_signal\n)\n\nfrom indigo.models import (\n Collection,\n Group,\n Resource,\n SearchIndex\n)\nfrom indigo.models.errors import (\n CollectionConflictError,\n ResourceConflictError\n)\nfrom indigo.metadata import (\n get_resource_keys,\n get_collection_keys\n)\nfrom indigo.util import (\n merge,\n)\n\n\n\ndef notify_agent(resource_id, event=\"\"):\n from nodes.client import choose_client\n client = choose_client()\n client.notify(resource_id, event)\n \n \n# TODO: Move this to a helper\ndef get_extension(name):\n _, ext = os.path.splitext(name)\n if ext:\n return ext[1:].upper()\n return \"UNKNOWN\"\n\n\n# noinspection PyUnusedLocal\n@login_required()\ndef home(request):\n return redirect('archive:view', path='')\n\n\n##############################################################################\n# Collection specific view functions\n##############################################################################\n@login_required()\ndef view_resource(request, path):\n resource = Resource.find(path)\n if not resource:\n raise Http404()\n\n if not resource.user_can(request.user, \"read\"):\n raise PermissionDenied\n\n container = Collection.find(resource.container)\n if not container:\n # TODO: the container has to be there. If not it may be a network\n # issue with Cassandra so we try again before raising an error to the\n # user\n container = Collection.find(resource.container)\n if not container:\n return HttpResponse(status=408,\n content=\"Unable to find parent container '{}'\".format(resource.container))\n\n paths = []\n full = \"\"\n for p in container.path.split('/'):\n if not p:\n continue\n full = u\"{}/{}\".format(full, p)\n paths.append((p, full))\n\n ctx = {\n \"resource\": resource.full_dict(request.user),\n \"container\": container,\n \"container_path\": container.path,\n \"collection_paths\": paths\n }\n return render(request, 'archive/resource/view.html', ctx)\n\n\n@login_required\ndef new_resource(request, parent):\n parent_collection = Collection.find(parent)\n # Inherits perms from container by default.\n if not parent_collection:\n raise Http404()\n\n # User must be able to write to this collection\n if not parent_collection.user_can(request.user, \"write\"):\n raise PermissionDenied\n\n keys = get_resource_keys()\n mdata = collections.OrderedDict()\n for k in keys:\n mdata[k] = \"\"\n if not mdata:\n mdata[\"\"] = \"\"\n\n read_access, write_access = parent_collection.get_acl_list()\n initial = {\n 'metadata': json.dumps(mdata),\n 'read_access': read_access,\n 'write_access': write_access\n }\n\n if request.method == 'POST':\n form = ResourceNewForm(request.POST, files=request.FILES, initial=initial)\n if form.is_valid():\n data = form.cleaned_data\n try:\n blob_id = data['file'].read()\n url = \"cassandra://{}\".format(blob_id)\n\n name = data['name']\n metadata = {}\n\n for k, v in json.loads(data['metadata']):\n if k in metadata:\n if isinstance(metadata[k], list):\n metadata[k].append(v)\n else:\n metadata[k] = [metadata[k], v]\n else:\n metadata[k] = v\n\n resource = Resource.create(container=parent_collection.path,\n name=name,\n metadata=metadata,\n url=url,\n mimetype=data['file'].content_type,\n username=request.user.name,\n size=data['file'].size)\n resource.create_acl_list(data['read_access'], data['write_access'])\n messages.add_message(request, messages.INFO,\n u\"New resource '{}' created\" .format(resource.get_name()))\n except ResourceConflictError:\n messages.add_message(request, messages.ERROR,\n \"That name is in use within the current collection\")\n\n return redirect('archive:view', path=parent_collection.path)\n else:\n form = ResourceNewForm(initial=initial)\n\n ctx = {\n \"form\": form,\n \"container\": parent_collection,\n \"groups\": Group.objects.all()\n }\n return render(request, 'archive/resource/new.html', ctx)\n\n\n@login_required\ndef edit_resource(request, path):\n # Requires edit on resource\n resource = Resource.find(path)\n if not resource:\n raise Http404()\n\n container = Collection.find(resource.container)\n if not container:\n raise Http404()\n\n if not resource.user_can(request.user, \"edit\"):\n raise PermissionDenied\n\n if request.method == \"POST\":\n form = ResourceForm(request.POST)\n if form.is_valid():\n metadata = {}\n for k, v in json.loads(form.cleaned_data['metadata']):\n if k in metadata:\n if isinstance(metadata[k], list):\n metadata[k].append(v)\n else:\n metadata[k] = [metadata[k], v]\n else:\n metadata[k] = v\n\n try:\n data = form.cleaned_data\n resource.update(metadata=metadata, username=request.user.name)\n resource.create_acl_list(data['read_access'], data['write_access'])\n \n return redirect('archive:resource_view', path=resource.path)\n except ResourceConflictError:\n messages.add_message(request, messages.ERROR,\n \"That name is in use withinin the current collection\")\n else:\n md = resource.get_cdmi_metadata()\n metadata = json.dumps(md)\n if not md:\n metadata = '{\"\":\"\"}'\n\n read_access, write_access = resource.get_acl_list()\n initial_data = {'name': resource.name, 'metadata': metadata,\n 'read_access': read_access,\n 'write_access': write_access\n }\n form = ResourceForm(initial=initial_data)\n\n ctx = {\n \"form\": form,\n \"resource\": resource,\n \"container\": container,\n \"groups\": Group.objects.all()\n }\n\n return render(request, 'archive/resource/edit.html', ctx)\n\n\n@login_required\ndef delete_resource(request, path):\n resource = Resource.find(path)\n if not resource:\n raise Http404\n\n if not resource.user_can(request.user, \"delete\"):\n raise PermissionDenied\n\n container = Collection.find(resource.container)\n if request.method == \"POST\":\n resource.delete(username=request.user.name)\n messages.add_message(request, messages.INFO,\n \"The resource '{}' has been deleted\".format(resource.name))\n return redirect('archive:view', path=container.path)\n\n # Requires delete on resource\n ctx = {\n \"resource\": resource,\n \"container\": container,\n }\n\n return render(request, 'archive/resource/delete.html', ctx)\n\n\n##############################################################################\n# Collection specific view functions\n##############################################################################\n\n@login_required()\ndef view_collection(request, path):\n if not path:\n path = '/'\n collection = Collection.find(path)\n\n if not collection:\n raise Http404()\n\n if not collection.user_can(request.user, \"read\") and not collection.is_root:\n # If the user can't read, then return 404 rather than 403 so that\n # we don't leak information.\n raise Http404()\n\n paths = []\n full = \"\"\n for p in collection.path.split('/'):\n if not p:\n continue\n full = u\"{}/{}\".format(full, p)\n paths.append((p, full))\n\n children_c, children_r = collection.get_child()\n children_c.sort(key=lambda x: x.lower())\n children_r.sort(key=lambda x: x.lower())\n ctx = {\n 'collection': collection.to_dict(request.user),\n 'children_c': [Collection.find(merge(path,c)).to_dict(request.user) for c in children_c],\n 'children_r': [Resource.find(merge(path,c)).simple_dict(request.user) for c in children_r],\n 'collection_paths': paths,\n 'empty': len(children_c) + len(children_r) == 0,\n }\n\n return render(request, 'archive/index.html', ctx)\n\n\ndef search(request):\n query = request.GET.get('q')\n collection = request.GET.get('collection')\n \n ctx = {\n \"q\": query\n }\n\n terms = [x.lower() for x in query.split(' ')]\n \n results = SearchIndex.find(terms, request.user)\n \n if collection:\n results = [el for el in results if el['path'].startswith(collection)]\n \n ctx['results'] = results\n ctx['total'] = len(ctx['results'])\n ctx['highlights'] = terms\n\n return render(request, 'archive/search.html', ctx)\n\n\ndef search2(request):\n query = request.GET.get('q')\n\n ctx = {\n \"q\": query\n }\n\n terms = [x.lower() for x in query.split(' ')]\n\n ctx['results'] = SearchIndex.find(terms, request.user)\n ctx['total'] = len(ctx['results'])\n ctx['highlights'] = terms\n\n return render(request, 'archive/search.html', ctx)\n\n\n@login_required\ndef new_collection(request, parent):\n parent_collection = Collection.find(parent)\n\n if not parent_collection.user_can(request.user, \"write\"):\n raise PermissionDenied\n\n keys = get_collection_keys()\n mdata = collections.OrderedDict()\n for k in keys:\n mdata[k] = \"\"\n if not mdata:\n mdata[\"\"] = \"\"\n\n read_access, write_access = parent_collection.get_acl_list()\n initial = {\n 'metadata': json.dumps(mdata),\n \"read_access\": read_access,\n \"write_access\": write_access\n }\n form = CollectionNewForm(request.POST or None, initial=initial)\n if request.method == 'POST':\n if form.is_valid():\n data = form.cleaned_data\n try:\n name = data['name']\n parent = parent_collection.path\n metadata = {}\n\n for k, v in json.loads(data['metadata']):\n if k in metadata:\n if isinstance(metadata[k], list):\n metadata[k].append(v)\n else:\n metadata[k] = [metadata[k], v]\n else:\n metadata[k] = v\n\n collection = Collection.create(name=name,\n container=parent,\n metadata=metadata,\n username=request.user.name)\n collection.create_acl_list(data['read_access'], data['write_access'])\n messages.add_message(request, messages.INFO,\n u\"New collection '{}' created\" .format(collection.name))\n return redirect('archive:view', path=collection.path)\n except CollectionConflictError:\n messages.add_message(request, messages.ERROR,\n \"That name is in use in the current collection\")\n except ResourceConflictError:\n messages.add_message(request, messages.ERROR,\n \"That name is in use in the current collection\")\n\n groups = Group.objects.all()\n return render(request, 'archive/new.html', {'form': form, \"parent\": parent_collection, \"groups\": groups})\n\n\n@login_required\ndef edit_collection(request, path):\n coll = Collection.find(path)\n if not coll:\n raise Http404\n\n if not coll.user_can(request.user, \"edit\"):\n raise PermissionDenied\n\n if request.method == \"POST\":\n form = CollectionForm(request.POST)\n if form.is_valid():\n metadata = {}\n for k, v in json.loads(form.cleaned_data['metadata']):\n if k in metadata:\n if isinstance(metadata[k], list):\n metadata[k].append(v)\n else:\n metadata[k] = [metadata[k], v]\n else:\n metadata[k] = v\n\n try:\n data = form.cleaned_data\n coll.update(metadata=metadata, username=request.user.name)\n coll.create_acl_list(data['read_access'], data['write_access'])\n return redirect('archive:view', path=coll.path)\n except CollectionConflictError:\n messages.add_message(request, messages.ERROR,\n \"That name is in use in the current collection\")\n else:\n md = coll.get_cdmi_metadata()\n metadata = json.dumps(md)\n if not md:\n metadata = '{\"\":\"\"}'\n read_access, write_access = coll.get_acl_list()\n initial_data = {'name': coll.name,\n 'metadata': metadata,\n 'read_access': read_access,\n 'write_access': write_access}\n form = CollectionForm(initial=initial_data)\n\n groups = Group.objects.all()\n return render(request, 'archive/edit.html', {'form': form, 'collection': coll, 'groups': groups})\n\n\n@login_required\ndef delete_collection(request, path):\n \"delete_coll\"\n coll = Collection.find(path)\n if not coll:\n raise Http404\n\n if not coll.user_can(request.user, \"delete\"):\n raise PermissionDenied\n\n if request.method == \"POST\":\n parent_coll = Collection.find(coll.path)\n if parent_coll:\n parent_path = parent_coll.container\n else:\n # Just in case\n parent_path = ''\n Collection.delete_all(coll.path, username=request.user.name)\n messages.add_message(request, messages.INFO,\n u\"The collection '{}' has been deleted\".format(coll.name))\n return redirect('archive:view', path=parent_path)\n\n return render(request, 'archive/delete.html', {'collection': coll})\n\n\n@login_required\ndef download(request, path):\n \"\"\"\n Requests for download are redirected to the agent via the agent,\n but for debugging the requests are served directly.\n\n We will send appropriate user auth to the agent.\n \"\"\"\n resource = Resource.find(path)\n if not resource:\n raise Http404\n\n if not resource.user_can(request.user, \"read\"):\n raise PermissionDenied\n\n if resource.is_reference:\n r = requests.get(resource.url, stream=True)\n resp = StreamingHttpResponse(streaming_content=r,\n content_type=resource.get_mimetype())\n else:\n resp = StreamingHttpResponse(streaming_content=resource.chunk_content(),\n content_type=resource.get_mimetype())\n resp['Content-Disposition'] = u'attachment; filename=\"{}\"'.format(resource.name)\n\n return resp\n\n\n@login_required\ndef preview(request, path):\n \"\"\"\n Find the preview of the resource with the given ID and deliver it. This will\n be rendered in the iframe of the resource view page.\n \"\"\"\n resource = Resource.find(path)\n if not resource:\n raise Http404\n\n preview_info = {\n # \"type\": \"image\",\n # \"url\": \"http://.....\"\n }\n\n return render(request, 'archive/preview.html', {'preview': preview_info})\n","sub_path":"indigo-web/archive/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":16955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"370044397","text":"import math\nimport statistics\nfrom nominalOps import classifer\n\n\ndef avg(attr):\n masterList = []\n for vals in range(0, len(attr)):\n print (attr[vals].keys())\n dictSum = attr[vals].keys()\n for i in range(0, len(dictSum)):\n for j in range(0, len(dictSum[i])):\n intCast = attr()\n masterList.append()\n # print \"avg: \" + str(float(summation / len(attr)))\n return\n\n\ndef sigma(mean, listYN):\n masterList = []\n for vals in range(0, len(listYN)):\n tempList = listYN[vals].keys()\n masterList.append(tempList)\n statistics.variance(tempList, mean)\n return math.sqrt(listYN)\n # print \"attrLen: \" + str(len(attr))\n # print len(listYN)\n # print str(float(sum([pow(val - mean, 2) for val in listYN])))\n # variance = float(sum([pow(val - mean, 2) for val in listYN]) / float(len(listYN) - 1))\n # print \"variance: \" + str(variance)\n # return float(math.sqrt(variance))\n\n\ndef pdf(x, mean, stdev):\n print (\"stdv: \" + str(stdev))\n exponent = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2))))\n return (1 / (math.sqrt(2 * math.pi) * stdev)) * exponent\n\n\ndef numeric_value(attributeToUse, list_of_numerics, input_x):\n list_yes, list_no, list_tot = classifer(list_of_numerics)\n attr = list_yes[attributeToUse]\n mean_yes = avg(list_yes)\n stdev_yes = sigma(mean_yes, list_yes)\n yesPDF = pdf(input_x, mean_yes, stdev_yes)\n print (\"no start\")\n print (\"\\n\\n\")\n print (len(list_no))\n attr = list_no[attributeToUse]\n mean_no = avg(list_no)\n stdev_no = sigma(mean_no, list_no)\n noPDF = pdf(input_x, mean_no, stdev_no)\n return yesPDF, noPDF\n","sub_path":"oldFiles/evenMoreTrash.py","file_name":"evenMoreTrash.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"88477887","text":"\"\"\"cli.py\nArgparse based CLI for fauxmo. Helps provide console_script. Also initializes\n\"\"\"\n\nimport argparse\nimport sys\nfrom .fauxmo import main\nimport logging\nimport logging.handlers\n\n\ndef cli():\n \"\"\"Parse command line options, provide entry point for console scripts\"\"\"\n\n arguments = sys.argv[1:]\n parser = argparse.ArgumentParser(description=\"Emulate Belkin Wemo devices \"\n \"for use with Amaazon Echo\")\n parser.add_argument(\"-v\", \"--verbose\", help=\"increase verbosity (may \"\n \"repeat up to -vv)\", action=\"count\", default=1)\n parser.add_argument(\"-c\", \"--config\", help=\"specify alternate config file\")\n args = parser.parse_args(arguments)\n\n logging.basicConfig(\n format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S'\n )\n\n logger = logging.getLogger(\"fauxmo\")\n handler = logging.handlers.SysLogHandler()\n logger.addHandler(handler)\n\n # args.verbose defaults to 1 -> 30 == logging.WARNING\n verbosity = max(40 - 10 * args.verbose, 10)\n logger.setLevel(verbosity)\n\n main(config_path=args.config, verbosity=verbosity)\n","sub_path":"fauxmo/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"628296047","text":"#!/usr/bin/env python\r\n\r\nfrom __future__ import print_function\r\n\r\nimport sys\r\nimport rospy\r\nfrom beginner_tutorials.srv import add_two_ints as a2i\r\n\r\ndef add_two_ints_client(x, y):\r\n rospy.wait_for_service('add_two_ints')\r\n try:\r\n add_two_ints = rospy.ServiceProxy('add_two_ints', a2i)\r\n resp1 = add_two_ints(x, y)\r\n print(resp1)\r\n return resp1.sum\r\n except rospy.ServiceException as e:\r\n print(\"Service call failed: %s\"%e)\r\n\r\ndef usage():\r\n return f\"{sys.argv[0]} [x y]\"\r\n\r\nif __name__ == \"__main__\":\r\n if len(sys.argv) == 3:\r\n x = int(sys.argv[1])\r\n y = int(sys.argv[2])\r\n else:\r\n print(usage())\r\n sys.exit(1)\r\n print(f\"Requesting {x} + {y}...\")\r\n print(f\"{x} + {y} = {add_two_ints_client(x, y)}\")","sub_path":"catkin_ws/src/beginner_tutorials/scripts/add_two_ints_client.py","file_name":"add_two_ints_client.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"130506439","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"This hook ensures MunkiAdmin scripts are executable.\"\"\"\n\nimport argparse\nimport os\n\n\ndef build_argument_parser():\n \"\"\"Build and return the argument parser.\"\"\"\n\n parser = argparse.ArgumentParser(\n description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter\n )\n parser.add_argument(\"filenames\", nargs=\"*\", help=\"Filenames to check.\")\n return parser\n\n\ndef main(argv=None):\n \"\"\"Main process.\"\"\"\n\n # Parse command line arguments.\n argparser = build_argument_parser()\n args = argparser.parse_args(argv)\n\n retval = 0\n for filename in args.filenames:\n if not os.access(filename, os.X_OK):\n print(\"{}: not executable\".format(filename))\n retval = 1\n\n return retval\n\n\nif __name__ == \"__main__\":\n exit(main())\n","sub_path":"pre_commit_hooks/check_munkiadmin_scripts.py","file_name":"check_munkiadmin_scripts.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"395254321","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = u'Danil Kuznetsov'\nSITENAME = u'/var/log'\nSITEURL = 'http://localhost:8000'\n\nPATH = 'content'\n\nDISPLAY_PAGES_ON_MENU = True\n\nTIMEZONE = 'Europe/Kiev'\n\nDEFAULT_LANG = u'ru'\n\nTHEME = \"themes/pelican-bootstrap3\"\n\n# Feed generation is usually not desired when developing\nFEED_ALL_RSS = 'feeds/all.rss.xml'\nCATEGORY_FEED_RSS = 'feeds/%s.rss.xml'\n\n\nSTATIC_PATHS = ['images','extra/favicon.ico']\n\nEXTRA_PATH_METADATA = {\n 'extra/favicon.ico': {'path': 'favicon.ico'}\n}\n\n# Blogroll\nMENUITEMS = [(\"About\",\"/about.html\"),(\"Links\",\"/links.html\")]\n\n# Social widget\nSOCIAL = (('github', 'http://github.com/danilkuznetsov'),)\n\n#DEFAULT_PAGINATION = 5\nDISPLAY_PAGES_ON_MENU = False\nDISPLAY_CATEGORIES_ON_MENU = False\n\nDISPLAY_TAGS_ON_SIDEBAR = True\n\nTAG_CLOUD_MAX_ITEMS = 10\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n\nPAGINATION_PATTERNS = (\n (1, '{base_name}/', '{base_name}/index.html'),\n (2, '{base_name}/page/{number}/', '{base_name}/page/{number}/index.html'),\n)\n\nTAG_URL = 'tag/{slug}/'\nTAG_SAVE_AS = 'tag/{slug}/index.html'\nTAGS_URL = 'tags/'\nTAGS_SAVE_AS = 'tags/index.html'\n\nAUTHOR_URL = 'author/{slug}/'\nAUTHOR_SAVE_AS = 'author/{slug}/index.html'\nAUTHORS_URL = 'authors/'\nAUTHORS_SAVE_AS = 'authors/index.html'\n\nCATEGORY_URL = 'category/{slug}/'\nCATEGORY_SAVE_AS = 'category/{slug}/index.html'\nCATEGORYS_URL = 'categories/'\nCATEGORYS_SAVE_AS = 'categories/index.html'","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"442608570","text":"import os \r\nimport os.path \r\nimport json\r\nimport time\r\nimport re\r\n\r\nimport FuncParsKinopoisk_0_0_3 as FPK\r\n\r\n\r\n\r\ntimeStart = time.strftime(\"%d-%m-%Y %H.%M.%S\", time.localtime())\r\nprint('Start at ' + timeStart)\r\n\r\npath_FileSaveResult = 'json/result_DateAboutAllFilms .json'\r\n# path_FileSaveResult = 'json/result_DateAboutAllFilms TEST .json'\r\n\r\ncount_LinksToFilm = 1\r\ncount_proxyIP = 0\r\n\r\n# Инициализация работы программы \r\nif os.path.isfile(path_FileSaveResult):\r\n\twith open(path_FileSaveResult, 'r', encoding = 'utf-8') as file_handle:\r\n\t\tdict_ = json.load(file_handle)\r\n\t\tcount_LinksToFilm = int(dict_[0]['count_LinksToFilm'])+1\t# что бы избежать повторов т.е. count_LinksToFilm = номеру последней оброботтаной ссылки\r\n\t\r\n\r\nwith open('json/arrLinksAllFilms 22-06-2020 09.11.09 .json') as file_handle:\t# получаю ссылки из файла в список\r\n list_LinksToFilm = json.load(file_handle)\r\n\r\n# with open('Proxylist/proxylist 05-08-2020 20.00.19 .json') as file_handle:\t# получаю прокси из файла в список\r\nwith open('Proxy/Proxylist/proxylist 17-08-2020 10.10.53 .json') as file_handle:\t# получаю прокси из файла в список\r\n list_Proxy = json.load(file_handle)\r\n\r\n\r\n# for Link_ToFilm in list_LinksToFilm:\r\nwhile count_LinksToFilm < len(list_LinksToFilm):\r\n\tLink_ToFilm = list_LinksToFilm[count_LinksToFilm]\t# для продолжаения работы программы с места остановки\r\n\tprint(str(count_LinksToFilm) + '. ' + Link_ToFilm)\r\n\t\r\n\twhile count_proxyIP < len(list_Proxy):\r\n\t\tproxyIP = list_Proxy[count_proxyIP]\r\n\r\n\t\tprint(' ' + str(count_proxyIP) + '. ' + str(proxyIP))\r\n\r\n\t\thtml = FPK.requestsURLThroughProxy(Link_ToFilm,proxyIP,_timeout=5)\r\n\r\n\t\tcount_proxyIP += 1\r\n\t\tif html:\r\n\t\t\tif FPK.pageCapcha(html):\r\n\t\t\t\tcontinue \r\n\t\t\tdict_Result = FPK.parsDateFilms(html)\r\n\t\t\t# заполняю поле 'Id_kinopisk'\r\n\t\t\tdict_Result['Id_kinopisk'] = re.sub(r'[(https://www\\.kinopoisk\\.ru/film/)/]','',Link_ToFilm)\r\n\t\t\tFPK.save_Result(dict_Result,path_FileSaveResult,count_LinksToFilm)\r\n\t\t\tprint(dict_Result)\r\n\t\t\tbreak\r\n\telse:\t\t# для запуска перебора списка прокси по новому кругу\r\n\t\tcount_proxyIP = 0 \r\n\t\tcontinue\r\n\tcount_LinksToFilm += 1\r\n\t# if count_LinksToFilm > 10:\r\n\t# \tbreak\r\n\r\n\r\n\r\n\r\ntimeFinish = time.strftime(\"%d-%m-%Y %H.%M.%S\", time.localtime())\r\nprint('Finish at ' + timeFinish)\r\n\r\n\r\n\r\n\r\n\r\n# Добавить автоматическое выключение комьпютера \r\n\r\n\r\n\r\n\r\n","sub_path":"Pars_Date_about_AllFilms 0.0.1.py","file_name":"Pars_Date_about_AllFilms 0.0.1.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"147362317","text":"#!/usr/bin/env python\n\nPKG = 'object_detection'\nimport roslib; roslib.load_manifest(PKG)\nimport numpy as np\nimport os\nimport six.moves.urllib as urllib\nimport sys\nimport tarfile\nimport tensorflow as tf\nimport zipfile\nimport label_map_util\nimport visualization_utils as vis_util\nimport numpy as np\nimport cv2\nimport os, rospkg\n\nfrom collections import defaultdict\nfrom io import StringIO\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\n\nif tf.__version__ != '1.4.0':\n raise ImportError('Please upgrade your tensorflow installation to v1.4.0!')\n\nrp = rospkg.RosPack()\nSCRIPT_PATH = os.path.join(rp.get_path(\"object_detection\"), \"scripts\")\n\n# What model to use.\nMODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'\nMODEL_PATH = os.path.join(SCRIPT_PATH, 'models', MODEL_NAME)\n\n# Path to frozen detection graph.\n# This is the actual model that is used for the object detection.\nPATH_TO_CKPT = os.path.join(MODEL_PATH, 'frozen_inference_graph.pb')\n\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = os.path.join(SCRIPT_PATH, 'data', 'mscoco_label_map.pbtxt')\n\nNUM_CLASSES = 90\n\ndetection_graph = tf.Graph()\nwith detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\nlabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)\ncategories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)\ncategory_index = label_map_util.create_category_index(categories)\n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\n# For the sake of simplicity we will use only 2 images:\n# image1.jpg\n# image2.jpg\n# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.\nPATH_TO_TEST_IMAGES_DIR = 'dataset/test_images'\nTEST_IMAGE_PATHS = [os.path.join(SCRIPT_PATH, PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3)]\n\n# Size, in inches, of the output images.\nIMAGE_SIZE = (12, 8)\n\nwith detection_graph.as_default():\n with tf.Session(graph=detection_graph) as sess:\n # Definite input and output Tensors for detection_graph\n image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n detection_boxes = detection_graph.get_tensor_by_name(\n 'detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n detection_scores = detection_graph.get_tensor_by_name(\n 'detection_scores:0')\n detection_classes = detection_graph.get_tensor_by_name(\n 'detection_classes:0')\n num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n cap = cv2.VideoCapture(1)\n while(True):\n # Capture frame-by-frame\n ret, image_np = cap.read()\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_np, axis=0)\n # Actual detection.\n (boxes, scores, classes, num) = sess.run(\n [detection_boxes, detection_scores, detection_classes,\n num_detections],\n feed_dict={image_tensor: image_np_expanded})\n # Visualization of the results of a detection.\n vis_util.visualize_boxes_and_labels_on_image_array(\n image_np,\n np.squeeze(boxes),\n np.squeeze(classes).astype(np.int32),\n np.squeeze(scores),\n category_index,\n use_normalized_coordinates=True,\n line_thickness=4)\n # Display the resulting frame\n cv2.imshow('frame',image_np)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n\n","sub_path":"scripts/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":4294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62611776","text":"from os.path import join\nfrom time import time\n\nimport pytest\nfrom numpy import array, pi\nfrom numpy.testing import assert_allclose\n\nfrom Tests import save_validation_path as save_path\nfrom pyleecan.Classes.ImportGenVectLin import ImportGenVectLin\nfrom pyleecan.Classes.ImportMatrixVal import ImportMatrixVal\nfrom pyleecan.Classes.InputCurrent import InputCurrent\nfrom pyleecan.Classes.MagFEMM import MagFEMM\nfrom pyleecan.Classes.OPdq import OPdq\nfrom pyleecan.Classes.Simu1 import Simu1\nfrom pyleecan.Functions.load import load\nfrom pyleecan.Functions.Plot import dict_2D\nfrom pyleecan.definitions import DATA_DIR\n\n\n@pytest.mark.long_5s\n@pytest.mark.MagFEMM\n@pytest.mark.IPMSM\n@pytest.mark.parallel\n@pytest.mark.periodicity\n@pytest.mark.SingleOP\ndef test_FEMM_parallelization_mag():\n \"\"\"test parallelization of FEMM to get B, Tem, PhiWind\"\"\"\n\n Toyota_Prius = load(join(DATA_DIR, \"Machine\", \"Toyota_Prius.json\"))\n\n simu = Simu1(name=\"test_FEMM_parallelization_mag\", machine=Toyota_Prius)\n\n # Definition of a sinusoidal current\n simu.input = InputCurrent()\n simu.input.OP = OPdq(Id_ref=-100, Iq_ref=200, N0=2000)\n simu.input.Nt_tot = 16 # Number of time step\n simu.input.Na_tot = 1024 # Spatial discretization\n\n # Definition of the magnetic simulation\n simu.mag = MagFEMM(\n type_BH_stator=2,\n type_BH_rotor=2,\n is_periodicity_a=True,\n is_periodicity_t=True,\n )\n simu2 = simu.copy()\n simu2.mag.nb_worker = 2\n\n # simlation with Nt_tot < nb_worker\n simu3 = simu.copy()\n simu3.mag.nb_worker = 8\n simu3.input.Nt_tot = 4\n\n start = time()\n out = simu.run()\n time1 = time() - start\n\n start = time()\n out2 = simu2.run()\n time2 = time() - start\n print(\n \"Execution with one worker: {:.1f}s ||| {:d} workers {:.1f}\".format(\n time1, simu2.mag.nb_worker, time2\n )\n )\n simu3.run()\n\n # Plot the result by comparing the first two simulation\n out.mag.B.plot_2D_Data(\n \"angle{°}\",\n \"time[0]\",\n data_list=[out2.mag.B],\n legend_list=[\"Serial\", \"Parallelization\"],\n save_path=join(save_path, simu.name + \"_B_t0.png\"),\n is_show_fig=False,\n **dict_2D\n )\n\n out.mag.B.plot_2D_Data(\n \"angle{°}\",\n \"time[0]\",\n data_list=[out2.mag.B],\n legend_list=[\"Serial\", \"Parallelization\"],\n save_path=join(save_path, simu.name + \"_B_t1.png\"),\n is_show_fig=False,\n **dict_2D\n )\n\n out.mag.Tem.plot_2D_Data(\n \"time\",\n data_list=[out2.mag.Tem],\n legend_list=[\"Periodic\", \"Full\"],\n save_path=join(save_path, simu.name + \"_Tem.png\"),\n is_show_fig=False,\n **dict_2D\n )\n\n out.mag.Phi_wind_stator.plot_2D_Data(\n \"time\",\n \"phase[]\",\n data_list=[out2.mag.Phi_wind_stator],\n legend_list=[\"Periodic\", \"Full\"],\n save_path=join(save_path, simu.name + \"_Phi_wind_stator.png\"),\n is_show_fig=False,\n **dict_2D\n )\n\n assert_allclose(\n out.mag.B.components[\"tangential\"].values,\n out2.mag.B.components[\"tangential\"].values,\n rtol=1e-5,\n atol=1e-6,\n )\n\n assert_allclose(\n out.mag.B.components[\"radial\"].values,\n out2.mag.B.components[\"radial\"].values,\n rtol=1e-5,\n atol=1e-5,\n )\n\n assert_allclose(out.mag.Tem.values, out2.mag.Tem.values, rtol=1e-5, atol=1e-5)\n\n return out, out2\n\n\n@pytest.mark.long_5s\n@pytest.mark.MagFEMM\n@pytest.mark.SPMSM\n@pytest.mark.parallel\n@pytest.mark.MeshSol\n@pytest.mark.periodicity\n@pytest.mark.SingleOP\ndef test_FEMM_parallelization_meshsolution():\n \"\"\"test parallelization of FEMM to get meshsolution\"\"\"\n\n SPMSM_003 = load(join(DATA_DIR, \"Machine\", \"SPMSM_003.json\"))\n simu = Simu1(name=\"test_FEMM_parallelization_meshsolution\", machine=SPMSM_003)\n\n # Definition of the enforced output of the electrical module\n N0 = 3000\n Is = ImportMatrixVal(\n value=array(\n [\n [6.97244193e-06, 2.25353053e02, -2.25353060e02],\n [-2.60215295e02, 1.30107654e02, 1.30107642e02],\n [-6.97244208e-06, -2.25353053e02, 2.25353060e02],\n [2.60215295e02, -1.30107654e02, -1.30107642e02],\n ]\n )\n )\n time = ImportGenVectLin(start=0, stop=0.015, num=4, endpoint=True)\n angle = ImportGenVectLin(start=0, stop=2 * pi, num=1024, endpoint=False)\n\n simu.input = InputCurrent(\n Is=Is,\n Ir=None, # No winding on the rotor\n OP=OPdq(N0=N0),\n time=time,\n angle=angle,\n angle_rotor_initial=0.5216 + pi,\n )\n\n # Definition of the magnetic simulation (no symmetry)\n simu.mag = MagFEMM(\n type_BH_stator=2,\n type_BH_rotor=2,\n is_periodicity_a=False,\n is_periodicity_t=False,\n is_get_meshsolution=True,\n nb_worker=1,\n )\n simu.force = None\n simu.struct = None\n simu2 = simu.copy()\n simu2.mag.nb_worker = 3\n simu2.name += \"_parallel\"\n\n out = simu.run()\n out2 = simu2.run()\n\n # %%\n # Plots solution computed without parallelization\n out.mag.meshsolution.plot_mesh(\n save_path=join(save_path, simu.name + \"_mesh_not_parallel.png\"),\n is_show_fig=False,\n )\n\n out.mag.meshsolution.plot_mesh(\n group_names=\"stator core\",\n save_path=join(save_path, simu.name + \"_mesh_stator_not_parallel.png\"),\n is_show_fig=False,\n )\n\n out.mag.meshsolution.plot_mesh(\n group_names=[\"stator core\", \"/\", \"airgap\", \"stator winding\"],\n save_path=join(\n save_path,\n simu.name + \"_mesh_stator_interface_not_parallel.png\",\n ),\n is_show_fig=False,\n )\n\n out.mag.meshsolution.plot_contour(\n label=\"\\mu\",\n save_path=join(save_path, simu.name + \"_mu_not_parallel.png\"),\n is_show_fig=False,\n )\n out.mag.meshsolution.plot_contour(\n label=\"B\",\n save_path=join(save_path, simu.name + \"_B_not_parallel.png\"),\n is_show_fig=False,\n )\n out.mag.meshsolution.plot_contour(\n label=\"H\",\n save_path=join(save_path, simu.name + \"_H_not_parallel.png\"),\n is_show_fig=False,\n )\n\n # %%\n # Plots solution computed with parallelization\n out2.mag.meshsolution.plot_mesh(\n save_path=join(save_path, simu.name + \"_mesh_parallel.png\"), is_show_fig=False\n )\n\n out2.mag.meshsolution.plot_mesh(\n group_names=\"stator core\",\n save_path=join(save_path, simu.name + \"_mesh_stator_parallel.png\"),\n is_show_fig=False,\n )\n\n out2.mag.meshsolution.plot_mesh(\n group_names=[\"stator core\", \"/\", \"airgap\", \"stator winding\"],\n save_path=join(\n save_path,\n simu.name + \"_mesh_stator_interface_parallel.png\",\n ),\n is_show_fig=False,\n )\n\n out2.mag.meshsolution.plot_contour(\n label=\"\\mu\",\n save_path=join(save_path, simu.name + \"_mu_parallel.png\"),\n is_show_fig=False,\n )\n out2.mag.meshsolution.plot_contour(\n label=\"B\",\n save_path=join(save_path, simu.name + \"_B_parallel.png\"),\n is_show_fig=False,\n )\n out2.mag.meshsolution.plot_contour(\n label=\"H\",\n save_path=join(save_path, simu.name + \"_H_parallel.png\"),\n is_show_fig=False,\n )\n\n return out, out2\n\n\nif __name__ == \"__main__\":\n\n out, out2 = test_FEMM_parallelization_mag()\n # out3, out4 = test_FEMM_parallelization_meshsolution()\n","sub_path":"Tests/Validation/Magnetics/test_FEMM_parallelization.py","file_name":"test_FEMM_parallelization.py","file_ext":"py","file_size_in_byte":7479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"23121412","text":"# Read in and write EER JSON objects for transformations\n# Authors: St John Grimbly\n# Date Created: 30 August 2019\n# Version: Alpha v1.0\n\n# Launch virtual environemnet in terminal using 'source venv/bin/activate'\n\nimport json\nfrom Main import *\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS\n\nWebServer = Flask(__name__)\ncors = CORS(WebServer)\n\ndef transform(json_file, file_type):\n \"\"\"\n Given a json_file and the type of file (ARM/EER), contact the back-end classes and transform the file.\n Return the transformed file\n\n Parameters\n ----------\n json_file: The JSON ARM/EER file\n\n file_type: The type of the JSON file. i.e. ARM or EER\n Returns\n -------\n ARMToEER(json_file) or EERToARM(json_file): Transformed file\n \"\"\"\n\n print (\"At transform method\")\n fileType = determine_model_type(json_file)\n if (fileType == \"ARM\"):\n return ARMToEER(json_file)\n return EERToARM(json_file)\n\ndef determine_model_type(json_file):\n \"\"\"\n Given a json_file, determine the type of the JSON file representation.\n\n Parameters\n ----------\n json_file: The JSON ARM/EER file\n\n Returns\n -------\n String 'EER' or 'ARM'\n \"\"\"\n \n if 'entities' in json_file: \n return 'EER'\n return 'ARM'\n\n@WebServer.route('/')\ndef index():\n '''Index page for the server root directory.'''\n # TO DO: Display Markdown user guide for this application\n return (\"WELCOME. THIS IS A SERVER ENDPOINT FOR CONVERTING BETWEEN \" \n \"ARM AND EER MODELS.\")\n\n@WebServer.route('/api/transform', methods=['GET','POST'])\ndef transform_view():\n '''API endpoint for the transform method used in the JavaScript front-end.'''\n json_file = request.get_json(force=True)# JSON Dictionary\n \n #json_file = request.json\n if not json_file:\n return \"No file\"\n \n file_type = determine_model_type(json_file)\n transformed_file, log = transform(json_file, file_type)\n transformed_file['log'] = log\n\n return transformed_file \n\nif __name__ == '__main__':\n WebServer.run(debug=True, host='0.0.0.0')","sub_path":"Back-end/WebServer.py","file_name":"WebServer.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"209227829","text":"for _ in range(int(input())):\n p = input()\n s = int(input())\n arr = input()[1:-1].split(',')\n if s == 0:\n arr = []\n rStatus = False\n start = 0\n end = 0\n for i in p:\n if i == 'R':\n rStatus = not rStatus\n elif i == 'D' and rStatus:\n end += 1\n elif i == 'D' and not rStatus:\n start += 1\n\n if start + end <= s:\n result = arr[start:s - end]\n if rStatus:\n print('[' + ','.join(result[::-1]) + ']')\n else:\n print('[' + ','.join(result) + ']')\n else:\n print(\"error\")\n","sub_path":"문제솔루션/문자열/G5_AC_5430/이규연/G5_AC.py","file_name":"G5_AC.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"444807397","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport scipy as sp\nimport pandas as pd\nimport pprint\nimport math\nimport pickle\nimport sklearn\nimport xgboost\nimport lightgbm\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.base import BaseEstimator\nfrom sklearn.base import RegressorMixin\nfrom sklearn.base import TransformerMixin\n\n\ndef main():\n id_feature_name = \"Id\"\n label_feature_name = \"SalePrice\"\n\n train_df, test_df = load_train_test_files()\n trainable_df = drop_id_feature(train_df, id_feature_name)\n preditable_df = drop_id_feature(test_df, id_feature_name)\n model = train_regression_model(trainable_df, label_feature_name)\n predictions = predict_test_dataset(model, preditable_df)\n submission_df = pd.DataFrame({\n \"Id\": test_df[id_feature_name],\n \"SalePrice\": predictions\n })\n export_submission_file(submission_df)\n \"\"\"\n tune_regression_model(trainable_df, label_feature_name)\n \"\"\"\n\n\ndef titanic_main():\n #train_csv_file_path = \"./train_fe1.csv\"\n train_csv_file_path = \"./train_fe1.csv\"\n test_csv_file_path = \"./test_fe1.csv\"\n\n dataset = pd.read_csv(train_csv_file_path)\n #test_dataset = pd.read_csv(test_csv_file_path)\n\n view_sample_dataset(dataset)\n drop_useless_features(dataset)\n train_model(dataset)\n\n\ndef load_train_test_files():\n print(\"\\n[Debug] Load the train and test files: \")\n train_csv_file_path = \"./generated/train_feature.csv\"\n test_csv_file_path = \"./generated/test_feature.csv\"\n train_df = pd.read_csv(train_csv_file_path)\n test_df = pd.read_csv(test_csv_file_path)\n print(\"Read train file: {} and test file: {}\".format(train_csv_file_path,\n test_csv_file_path))\n\n return train_df, test_df\n\n\ndef view_sample_dataset(dataset):\n print(\"\\n[Debug] Print the sample of the dataset: \")\n dataset_sample = dataset.head(1)\n print(dataset_sample)\n\n\ndef drop_useless_features(dataset):\n print(\"\\n[Debug] Drop the useless features of the dataset: \")\n useless_feature_name_array = [\"Unnamed: 0\"]\n print(\"Drop the features: {}\".format(useless_feature_name_array))\n dataset.drop(useless_feature_name_array, axis=1, inplace=True)\n\n\ndef drop_id_feature(df, id_feature_name):\n \"\"\"\n Return: the dataframe without the id feature.\n \"\"\"\n print(\"\\n[Debug] Drop the id feature: \")\n print(\"Drop id feature: {}\".format(id_feature_name))\n return df.drop(id_feature_name, axis=1, inplace=False)\n\n\ndef train_regression_model(df, label_feature_name):\n print(\"\\n[Debug] Train the regression model: \")\n\n train_X, train_Y, test_X, test_Y = _split_train_test_feature_label(\n df, label_feature_name)\n model = xgboost.XGBRegressor()\n\n model1 = xgboost.XGBRegressor(\n colsample_bytree=0.4603,\n gamma=0.0468,\n learning_rate=0.05,\n max_depth=3,\n min_child_weight=1.7817,\n n_estimators=2200,\n reg_alpha=0.4640,\n reg_lambda=0.8571,\n subsample=0.5213,\n silent=1,\n random_state=7,\n nthread=-1)\n model2 = sklearn.ensemble.GradientBoostingRegressor() # 0.13\n model3 = sklearn.ensemble.RandomForestRegressor() # 0.15\n model4 = lightgbm.LGBMRegressor(\n objective='regression',\n num_leaves=5, # 0.21\n learning_rate=0.05,\n n_estimators=720,\n max_bin=55,\n bagging_fraction=0.8,\n bagging_freq=5,\n feature_fraction=0.2319,\n feature_fraction_seed=9,\n bagging_seed=9,\n min_data_in_leaf=6,\n min_sum_hessian_in_leaf=11)\n\n model = AveragingModels([model1, model2])\n \"\"\"\n from keras.models import Sequential\n from keras.layers import Dense, Dropout\n\n model = Sequential()\n model.add(Dense(64, input_dim=289, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(64, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(1, activation='sigmoid'))\n\n model.compile(loss='mean_squared_error', optimizer='rmsprop')\n\n model.fit(train_X.as_matrix(), train_Y.as_matrix(),\n epochs=20,\n batch_size=128)\n score = model.evaluate(test_X.as_matrix(), test_Y.as_matrix(), batch_size=128)\n \"\"\"\n \"\"\"\n import tensorflow as tf\n feature_columns = df.columns.values.tolist()\n model = tf.estimator.DNNRegressor(feature_columns=feature_columns, hidden_units=[10, 10, 10], activation_fn=tf.nn.relu, optimizer=\"Adam\")\n\n train_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\": train_X.as_matrix()},\n y=train_Y.as_matrix(),\n num_epochs=None,\n shuffle=True)\n\n model.train(input_fn=train_input_fn, steps=20000)\n \"\"\"\n\n model = _train_with_model(model, train_X, train_Y)\n _compute_target_score_for_test(model, test_X, test_Y)\n\n return model\n\n\ndef _split_train_test_feature_label(df, label_feature_name):\n print(\"\\n[Debug] Split the train/test feature/label dataset: \")\n\n #train, test = train_test_split(df, test_size=0.3, random_state=0, stratify=df[label_feature_name])\n train, test = train_test_split(df, test_size=0.2, random_state=0)\n\n train_X = train.drop(label_feature_name, axis=1, inplace=False)\n train_Y = train[label_feature_name]\n test_X = test.drop(label_feature_name, axis=1, inplace=False)\n test_Y = test[label_feature_name]\n\n return train_X, train_Y, test_X, test_Y\n\n\ndef _train_with_model(model, train_X, train_Y):\n print(\"\\n[Debug] Train wth the model: \")\n\n model.fit(train_X, train_Y)\n print(\"Success to train the model: {}\".format(model))\n\n return model\n\n\ndef _compute_target_score_for_test(model, test_X, test_Y):\n print(\"\\n[Debug] Compute the target score for test dataset: \")\n\n predict_Y = model.predict(test_X)\n\n # TODO: Prevent from getting negative number\n predict_Y = predict_Y.clip(min=1)\n\n root_mean_square_error = mean_squared_error(\n np.log(test_Y), np.log(predict_Y))\n score = math.sqrt(root_mean_square_error)\n print(\"The target score is: {}\".format(score))\n\n return score\n\n\ndef tune_regression_model(df, label_feature_name):\n print(\"\\n[Debug] Tune the regression model: \")\n \"\"\"\n train_X, train_Y, test_X, test_Y = _split_train_test_feature_label(df, label_feature_name)\n pickle.dump(train_X, open(\"generated/train_X.pickle\", \"wb\"))\n pickle.dump(train_Y, open(\"generated/train_Y.pickle\", \"wb\"))\n pickle.dump(test_X, open(\"generated/test_X.pickle\", \"wb\"))\n pickle.dump(test_Y, open(\"generated/test_Y.pickle\", \"wb\"))\n \"\"\"\n\n train_X = pickle.load(open(\"generated/train_X.pickle\", \"rb\"))\n train_Y = pickle.load(open(\"generated/train_Y.pickle\", \"rb\"))\n test_X = pickle.load(open(\"generated/test_X.pickle\", \"rb\"))\n test_Y = pickle.load(open(\"generated/test_Y.pickle\", \"rb\"))\n\n # Refer to http://scikit-learn.org/stable/modules/linear_model.html\n model = sklearn.linear_model.LinearRegression() # 1.02\n model = sklearn.linear_model.Ridge(alpha=0.5) # 0.68\n model = sklearn.linear_model.RidgeCV(alphas=[0.1, 1.0, 10.0]) # 0.17\n model = sklearn.linear_model.Lasso(alpha=0.1) # 0.78\n model = sklearn.linear_model.LassoLars(alpha=0.1) # 0.77\n model = sklearn.linear_model.ElasticNet(alpha=0.1) # 0.17\n model = sklearn.linear_model.BayesianRidge(n_iter=300) # 0.17\n model = sklearn.linear_model.ARDRegression() # 0.16\n model = sklearn.linear_model.HuberRegressor() # 0.22\n model = sklearn.linear_model.Perceptron() # 0.41\n model1 = xgboost.XGBRegressor() # 0.13\n model2 = xgboost.XGBRegressor(\n colsample_bytree=0.4603,\n gamma=0.0468,\n learning_rate=0.05,\n max_depth=3,\n min_child_weight=1.7817,\n n_estimators=2200,\n reg_alpha=0.4640,\n reg_lambda=0.8571,\n subsample=0.5213,\n silent=1,\n random_state=7,\n nthread=-1)\n model3 = sklearn.ensemble.GradientBoostingRegressor() # 0.13\n model4 = sklearn.ensemble.RandomForestRegressor() # 0.15\n model5 = lightgbm.LGBMRegressor(\n objective='regression',\n num_leaves=5, # 0.21\n learning_rate=0.05,\n n_estimators=720,\n max_bin=55,\n bagging_fraction=0.8,\n bagging_freq=5,\n feature_fraction=0.2319,\n feature_fraction_seed=9,\n bagging_seed=9,\n min_data_in_leaf=6,\n min_sum_hessian_in_leaf=11)\n\n model = AveragingModels([model1, model2, model3])\n\n model = _train_with_model(model, train_X, train_Y)\n _compute_target_score_for_test(model, test_X, test_Y)\n\n return model\n\n\ndef predict_test_dataset(model, df):\n print(\"\\n[Debug] Predict with the model: \")\n\n predictions = model.predict(df)\n print(\"Success to predict with the model\")\n print(predictions)\n\n return predictions\n\n\ndef export_submission_file(submission_df):\n print(\"\\n[Debug] Export to submission file: \")\n my_submission_file_path = \"./generated/my_submission.csv\"\n print(\"Export the submission to file: {}\".format(my_submission_file_path))\n submission_df.to_csv(my_submission_file_path, index=False)\n\n\ndef train_regression_model_old(df, test_df):\n #model = RandomForestRegressor()\n model = GradientBoostingRegressor()\n\n #selected_feature_name_array = ['GarageArea','YearRemodAdd','YearBuilt','1stFlrSF', '2ndFlrSF', 'TotalBsmtSF', 'BsmtUnfSF']\n selected_feature_name_array = [\n 'YearRemodAdd', 'YearBuilt', '1stFlrSF', '2ndFlrSF'\n ]\n X_train = df[selected_feature_name_array]\n y_train = df[\"SalePrice\"]\n\n model.fit(X_train, y_train)\n print(\"Success to train the model\")\n\n y_pred = model.predict(X_train)\n root_mean_square_error = mean_squared_error(np.log(y_train), np.log(y_pred))\n score = math.sqrt(root_mean_square_error)\n print(\"The target score is: {}\".format(score))\n\n X_test = test_df[selected_feature_name_array]\n predictions = model.predict(X_test)\n print(predictions)\n\n submission = pd.DataFrame({\"Id\": test_df[\"Id\"], \"SalePrice\": predictions})\n my_submission_file_path = \"./generated/my_submission.csv\"\n print(\"Export the submission to file: {}\".format(my_submission_file_path))\n submission.to_csv(my_submission_file_path, index=False)\n\n\ndef train_model(dataset):\n print(\"\\n[Debug] Train the model of the dataset: \")\n\n train, test = train_test_split(\n dataset, test_size=0.3, random_state=0, stratify=dataset['Survived'])\n train_X = train[train.columns[1:]]\n train_Y = train[train.columns[:1]]\n test_X = test[test.columns[1:]]\n test_Y = test[test.columns[:1]]\n all_X = dataset[dataset.columns[1:]]\n all_Y = dataset['Survived']\n\n print(train_X.head(1))\n\n model = svm.SVC(kernel='rbf', C=1, gamma=0.1)\n model.fit(train_X, train_Y)\n prediction1 = model.predict(test_X)\n print('Accuracy for rbf SVM is ', metrics.accuracy_score(\n prediction1, test_Y))\n\n model = svm.SVC(kernel='linear', C=0.1, gamma=0.1)\n model.fit(train_X, train_Y)\n prediction2 = model.predict(test_X)\n print('Accuracy for linear SVM is', metrics.accuracy_score(\n prediction2, test_Y))\n\n model = LogisticRegression()\n model.fit(train_X, train_Y)\n prediction3 = model.predict(test_X)\n print('The accuracy of the Logistic Regression is', metrics.accuracy_score(\n prediction3, test_Y))\n\n model = DecisionTreeClassifier()\n model.fit(train_X, train_Y)\n prediction4 = model.predict(test_X)\n print('The accuracy of the Decision Tree is', metrics.accuracy_score(\n prediction4, test_Y))\n\n model = KNeighborsClassifier()\n model.fit(train_X, train_Y)\n prediction5 = model.predict(test_X)\n print('The accuracy of the KNN is', metrics.accuracy_score(\n prediction5, test_Y))\n\n model = GaussianNB()\n model.fit(train_X, train_Y)\n prediction6 = model.predict(test_X)\n print('The accuracy of the NaiveBayes is', metrics.accuracy_score(\n prediction6, test_Y))\n\n model = RandomForestClassifier(n_estimators=100)\n model.fit(train_X, train_Y)\n prediction7 = model.predict(test_X)\n print('The accuracy of the Random Forests is', metrics.accuracy_score(\n prediction7, test_Y))\n \"\"\"\n from sklearn.model_selection import GridSearchCV\n C=[0.05,0.1,0.2,0.3,0.25,0.4,0.5,0.6,0.7,0.8,0.9,1]\n gamma=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]\n kernel=['rbf','linear']\n hyper={'kernel':kernel,'C':C,'gamma':gamma}\n gd=GridSearchCV(estimator=svm.SVC(),param_grid=hyper,verbose=True)\n gd.fit(X,Y)\n print(gd.best_score_)\n print(gd.best_estimator_)\n\n\n n_estimators=range(100,1000,100)\n hyper={'n_estimators':n_estimators}\n gd=GridSearchCV(estimator=RandomForestClassifier(random_state=0),param_grid=hyper,verbose=True)\n gd.fit(X,Y)\n print(gd.best_score_)\n print(gd.best_estimator_)\n \"\"\"\n\n model = svm.SVC(kernel='rbf', C=1, gamma=0.1)\n model.fit(train_X, train_Y)\n prediction1 = model.predict(test_X)\n print('Accuracy for rbf SVM is ', metrics.accuracy_score(\n prediction1, test_Y))\n\n test_csv_file_path = \"./test_fe1.csv\"\n test_dataset = pd.read_csv(test_csv_file_path)\n new_test_data = test_dataset.drop([\"PassengerId\"], axis=1, inplace=False)\n new_test_data = new_test_data.drop([\"Unnamed: 0\"], axis=1, inplace=False)\n #new_test_data = new_test_data.drop([\"Survived\"], axis=1, inplace=False)\n #import ipdb;ipdb.set_trace()\n\n predictions = model.predict(new_test_data)\n submission = pd.DataFrame({\n \"PassengerId\": test_dataset[\"PassengerId\"],\n \"Survived\": predictions\n })\n submission.to_csv(\"submission_fe1.csv\", index=False)\n\n\nclass AveragingModels(BaseEstimator, RegressorMixin, TransformerMixin):\n def __init__(self, models):\n self.models = models\n\n def fit(self, X, y):\n #self._models = [clone(x) for x in self.models]\n self._models = self.models\n for model in self._models:\n model.fit(X, y)\n return self\n\n def predict(self, X):\n predictions = np.column_stack([model.predict(X) for model in self._models])\n return np.mean(predictions, axis=1)\n\n\nif __name__ == \"__main__\":\n #smoke_main()\n main()\n","sub_path":"house_price/4_train_model.py","file_name":"4_train_model.py","file_ext":"py","file_size_in_byte":13892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"390299843","text":"from time import sleep\nfrom python_rucaptcha import ReCaptchaV2\n\ncommand_exec ='https://aleksandrkuzhele1:sxi8y58EkWTvHGNboy33@hub-cloud.browserstack.com/wd/hub'\n\nform_url = 'http://www.123formbuilder.com/form-5012215/online-order-form'\n\n######## XPATHs ###############\nXNameForm = \"//h1[text()='Order Form']\"\nXFirstName = \"//input[@placeholder='First']\"\nXLastName = \"//input[@placeholder='Last']\"\nXEmail = \"//input[@type='email']\"\nXPhone = \"//input[@placeholder='### ### #### ']\"\nXQuantity = \"//input[@type='number']\"\nXCalendar = \"//body/form[@id='form']/div/div/div/div/div/div/div[2]\"\nXStreet1 = \"//input[@placeholder='Street Address']\"\nXStreet2 = \"//input[@placeholder='Street Address Line 2']\"\nXCity = \"//input[@placeholder='City']\"\nXRegion = \"//input[@placeholder='Region']\"\nXZipCode = \"//input[@placeholder='Postal / Zip Code']\"\nXCountry = \"//input[@placeholder='Country']\"\nXSelCountry = \"//*[contains(text(), 'Zambia')]\"\nXExtText = \"//input[@type='text'][@data-role='other']\"\n\ndef SolveCapcha():\n # Введите ключ от сервиса RuCaptcha, из своего аккаунта\n RUCAPTCHA_KEY = \"53da620a6ac51a8ad6adc5bc9bac7822\"\n # G-ReCaptcha ключ сайта\n SITE_KEY = \"6LdMNiMTAAAAAGr0ibqKRZc3e5Z6wfLBraX9NuOY\"\n # Ссылка на страницу с капчёй\n PAGE_URL = \"http://www.123formbuilder.com/form-5012215/online-order-form\"\n # Возвращается JSON содержащий информацию для решения капчи\n user_answer = ReCaptchaV2.ReCaptchaV2(rucaptcha_key=RUCAPTCHA_KEY).captcha_handler(site_key=SITE_KEY, page_url=PAGE_URL)\n #if not user_answer['error']:\n # решение капчи\n # print('captchaSolve: ', user_answer['captchaSolve'])\n # print('taskId ', user_answer['taskId'])\n #elif user_answer['error']:\n # Тело ошибки, если есть\n # print(user_answer['errorBody']['text'])\n # print(user_answer['errorBody']['id'])\n sleep(2)\n #driver.execute_script(\"document.getElementById('text_field').value+='{0}'\".format(foo))\n capt = user_answer['captchaSolve']\n #вставляем в скрытое поле\n return str(\"javascript:document.getElementById('g-recaptcha-response').value = '{0}';\".format(capt))\n\n\n\n\n\n","sub_path":"BrowserStack/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"83246217","text":"import random\nimport math\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\nimport matplotlib.patches as patches\nimport numpy as np\n\n# Input parameters\nRoomWidth = 500.0 # room width in centi metres\nRoomHeight = 500.0 # room height in centi metres\ngrid_size = 5 # centi-metres\n\nMAX_COLUMN = math.ceil(RoomWidth/grid_size)\nMAX_ROW = math.ceil(RoomWidth/grid_size)\n\nallOBSvertex = [[(70,120),(70,300),(200,300),(200,220),(350,220),(350,120)],\n [(15,435),(70,490),(120,445),(65,390)],\n [(485,435),(430,490),(380,445),(435,390)]]\n\nTxLocation = (250,500)\nc1 = []\nc2 = 0\ncover2 = []\ncov = []\nT = []\nTxcoverage = 0\nfor k in range(MAX_ROW):\n c1.append([0]*MAX_COLUMN)\n T.append([0]*MAX_COLUMN)\nfor x in range(MAX_COLUMN) :\n for y in range(MAX_ROW) :\n c1[x][y] = 0.0\n T[x][y] = 0.0\n#mirror = (['R',250,10,150,0]) #wallSide,position,distance,mirror_width,angle\n\nwall_axis = [[[0,0],[RoomWidth,0]],[[0,0],[0,RoomHeight]],[[0,RoomHeight],[RoomWidth,RoomHeight]],[[RoomWidth,RoomHeight],[RoomWidth,0]]]\n\nclass PixelPlane() :\n def __init__(self,MAX_ROW,MAX_COLUMN) :\n self.MAX_ROW = MAX_ROW\n self.MAX_COLUMN = MAX_COLUMN \n self.pixel_intensity = []\n for k in range(self.MAX_ROW):\n self.pixel_intensity.append([0]*self.MAX_COLUMN)\n for x in range(self.MAX_COLUMN) :\n for y in range(self.MAX_ROW) :\n self.pixel_intensity[x][y] = 0.0\n\n\ndef intersect(x1,y1,x2,y2,x3,y3,x4,y4,debug=False):\n if debug:\n print(\"========= Start Intersect =========\")\n print(x1,y1,x2,y2,x3,y3,x4,y4)\n denominator = (x1-x2)*(y3-y4) - (y1-y2)*(x3-x4)\n if debug:\n print(denominator)\n if denominator!=0:\n Px = (x1*y2 - y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4)\n Px = Px/denominator\n Py = (x1*y2 - y1*x2)*(y3-y4) - (y1-y2)*(x3*y4-y3*x4)\n Py = Py/denominator\n if debug:\n print(Px,Py)\n onSegment1 = False\n onSegment2 = False\n\n alpha = 0.00001\n if ((Px>=x1-alpha and Px <= x2+alpha) or (Px>=x2-alpha and Px <= x1+alpha)) and ((Py>=y1-alpha and Py <= y2+alpha) or (Py>=y2-alpha and Py <= y1+alpha)):\n onSegment2 = True\n if ((Px>=x3-alpha and Px <= x4+alpha) or (Px>=x4-alpha and Px <= x3+alpha)) and ((Py>=y3-alpha and Py <= y4+alpha) or (Py>=y4-alpha and Py <= y3+alpha)):\n onSegment1 = True\n\n if debug:\n print(onSegment1,onSegment2)\n\n if onSegment1 == True and onSegment2 == True:\n return (True,Px,Py)\n else:\n return (False,Px,Py)\n else:\n return (False,'Parallel')\n\nclass Mirror():\n def __init__(self,wallSide,position,distance,mirror_width,angle):\n self.wallSide = wallSide\n self.position = position\n self.distance = distance\n self.mirror_width = mirror_width\n self.angle = angle\n mirror_loc = self.mirror_install(wallSide,position,distance,mirror_width,angle)\n self.mirror_loc = mirror_loc\n self.mirror_pixel_list = self.mirror_pixel_plane(mirror_loc[0],mirror_loc[1],mirror_loc[2],mirror_loc[3])\n self.project_pixel_list = self.pixel_mirror_projection()\n \n # ** TEST MULTIPLE RAYS ADD\n #self.project_pixel_list = self.shotgun(2) #Experiment (Multiple rays)\n \n self.mirror_reflect_points = self.mirror_reflect_points()\n self.tx_mirror_perp = self.perp_toMirror(TxLocation[0],TxLocation[1],mirror_loc[0],mirror_loc[1],mirror_loc[2],mirror_loc[3])\n ##print(\"self.tx_mirror_perp =\",self.tx_mirror_perp) \n all_mirror_reflect_points = self.mirror_reflect_points\n self.ray_to_object_list = self.ray_to_object() \n self.all_ray_coverage_list = self.all_ray_coverage()\n #self.count_coverage()\n \n def mirror_install(self,wallSide,position,distance,mirror_width,angle): # (Wall,location,distance from wall,mirror length, angle) \n if wallSide == 'Right' or wallSide == 'R':\n #print('R')\n #At angle = 0 \n x1 = RoomWidth - distance\n y1 = position - mirror_width/2\n x2 = RoomWidth - distance\n y2 = position + mirror_width/2\n \n #With angle\n x1 = x1 - np.cos(np.deg2rad(90+angle))*mirror_width/2\n y1 = y1 + ((mirror_width/2)-np.cos(np.deg2rad(angle))*mirror_width/2)\n x2 = x2 + np.cos(np.deg2rad(90+angle))*mirror_width/2\n y2 = y2 - ((mirror_width/2)-np.cos(np.deg2rad(angle))*mirror_width/2)\n \n elif wallSide == 'Left' or wallSide == 'L':\n #print('LEFT')\n x1 = distance\n y1 = position + mirror_width/2\n x2 = distance\n y2 = position - mirror_width/2\n\n #with angle\n x1 = x1 - np.cos(np.deg2rad(90-angle))*mirror_width/2\n y1 = y1 - ((mirror_width/2)-np.cos(np.deg2rad(angle))*mirror_width/2)\n x2 = x2 + np.cos(np.deg2rad(90-angle))*mirror_width/2\n y2 = y2 + ((mirror_width/2)-np.cos(np.deg2rad(angle))*mirror_width/2)\n\n elif wallSide == 'Top' or wallSide == 'T' :\n print('Top')\n x1 = position - mirror_width/2\n y1 = RoomHeight - distance\n x2 = position + mirror_width/2\n y2 = RoomHeight - distance\n \n #with angle\n x1 = x1 + ((mirror_width/2)-np.cos(np.deg2rad(angle))*mirror_width/2)\n y1 = y1 - np.cos(np.deg2rad(90-angle))*mirror_width/2\n x2 = x2 - ((mirror_width/2)-np.cos(np.deg2rad(angle))*mirror_width/2)\n y2 = y2 + np.cos(np.deg2rad(90-angle))*mirror_width/2\n\n elif wallSide == 'Bottom' or wallSide == 'B' : \n print('Bottom')\n x1 = position - mirror_width/2\n y1 = distance\n x2 = position + mirror_width/2\n y2 = distance\n\n #with angle\n x1 = x1 + mirror_width/2 - (mirror_width/2*(np.cos(np.deg2rad(angle))))\n y1 = y1 - ((mirror_width/2)*np.cos(np.deg2rad(90-angle)))\n x2 = x2 - (mirror_width/2) + (mirror_width/2*(np.cos(np.deg2rad(angle))))\n y2 = y2 + (np.cos(np.deg2rad(90-angle)))*mirror_width/2\n\n #print(x1/grid_size,y1/grid_size,x2/grid_size,y2/grid_size)\n #print(x1,y1,x2,y2)\n return x1,y1,x2,y2\n \n def mirror_pixel_plane(self,x1,y1,x2,y2):\n mirror_plane = []\n for px in range(int(math.floor(min([x1,x2])/grid_size)),(int(math.ceil(max([x1,x2])/grid_size)+1))):\n for py in range(int(math.floor(min([y1,y2])/grid_size)),(int(math.ceil(max([y1,y2])/grid_size)+1))):\n pix_sides = [[px,py,px+1,py],[px,py,px,py+1],[px,py+1,px+1,py+1],[px+1,py,px+1,py+1]]\n ##print(\"pix sides =\",pix_sides)\n pix_sides = np.multiply(pix_sides,grid_size) \n for side in pix_sides:\n mirror_on_grid = intersect(x1,y1,x2,y2,side[0],side[1],side[2],side[3])\n if mirror_on_grid[0] == True:\n if px< MAX_COLUMN and py < MAX_ROW:\n mirror_plane.append([px,py])\n break\n return mirror_plane\n\n def pixel_mirror_projection(self):\n project_pixel_list=[] #List for projection pixel position into exact mirror line\n #mid_pixel_list = [[x+0.5,y+0.5] for [x,y] in self.mirror_pixel_list] #<-- If want all rays from mirror\n mid_pixel_list = [[x-0.5,y-0.5] for [x,y] in self.light_on_mirror(tx_id)] #<-- only light part can reflect\n #print(\"Mid pix =\",mid_pixel_list) \n for i in range(len(mid_pixel_list)):\n project_pixel_list.append(mid_pixel_list[i])\n if i+1 < len(mid_pixel_list):\n project_pixel_list.append([np.mean([mid_pixel_list[i][0],mid_pixel_list[i+1][0]]),np.mean([mid_pixel_list[i][1],mid_pixel_list[i+1][1]])]) \n #print('mirror_pixel_list',self.mirror_pixel_list)\n #print('project_pixel_list',project_pixel_list) \n return project_pixel_list \n \n def mirror_reflect_points(self):\n all_reflect_points = []\n pixel_to_loc = [[px*grid_size,py*grid_size] for [px,py] in self.project_pixel_list]\n for loc in pixel_to_loc:\n point = self.perp_toMirror(loc[0],loc[1],self.mirror_loc[0],self.mirror_loc[1],self.mirror_loc[2],self.mirror_loc[3])\n all_reflect_points.append(point)\n \n #print(\"all reflect points = \",all_reflect_points)\n return all_reflect_points\n \n def reference_point_mirror(self,x1,y1):\n reference_point_mirror = [x1-(self.tx_mirror_perp[0]-x1),y1-(self.tx_mirror_perp[1]-y1)]\n #print(\"ref point mirror = \",reference_point_mirror) \n return reference_point_mirror\n \n def reference_point_reflect(self,x1,y1):\n reference_point_mirror = self.reference_point_mirror(x1,y1)\n reference_point_reflect = [reference_point_mirror[0]-(self.tx_mirror_perp[0]-TxLocation[0]),reference_point_mirror[1]+(TxLocation[1]-self.tx_mirror_perp[1])] \n return reference_point_reflect\n \n def all_mirror_plane_to_wall(self): #find intersect points between mirror plane and wall \n x1 = self.mirror_loc[0]\n y1 = self.mirror_loc[1]\n x2 = self.mirror_loc[2]\n y2 = self.mirror_loc[3]\n all_mirror_plane_to_wall = []\n for wall in wall_axis:\n mirror_plane_to_wall = self.room_wall_intersect(np.array([x1,y1]),np.array([x2,y2]),np.array(wall[0]),np.array(wall[1]))\n if mirror_plane_to_wall[0]>=0 and mirror_plane_to_wall[0]<=RoomWidth and mirror_plane_to_wall[1]>=0 and mirror_plane_to_wall[1]<=RoomHeight:\n all_mirror_plane_to_wall.append(mirror_plane_to_wall)\n #print(all_mirror_plane_to_wall)\n return all_mirror_plane_to_wall\n \n def wall_position(self,x1,y1): \n all_mirror_plane_to_wall = self.all_mirror_plane_to_wall()\n reference_point_reflect = self.reference_point_reflect(x1,y1)\n for wall in wall_axis:\n wall_position1 = self.room_wall_intersect(np.array([x1,y1]),np.array([reference_point_reflect[0],reference_point_reflect[1]]),np.array(wall[0]),np.array(wall[1]))\n #print(\"wall chk :\",wall_position1)\n if wall_position1[0]>=0 and wall_position1[0]<=RoomWidth and wall_position1[1]>=0 and wall_position1[1]<=RoomHeight:\n mirror_intersect = intersect(all_mirror_plane_to_wall[0][0],all_mirror_plane_to_wall[0][1],all_mirror_plane_to_wall[1][0],all_mirror_plane_to_wall[1][1],TxLocation[0],TxLocation[1],wall_position1[0],wall_position1[1])\n refPoint_mir_wall_intersect = intersect(reference_point_reflect[0],reference_point_reflect[1],wall_position1[0],wall_position1[1],all_mirror_plane_to_wall[0][0],all_mirror_plane_to_wall[0][1],all_mirror_plane_to_wall[1][0],all_mirror_plane_to_wall[1][1])\n \n if mirror_intersect[0] == False:\n if refPoint_mir_wall_intersect[0]==False:\n break\n else:\n pass\n #print(\"but through mirror !! sorry let's seek another wall... \")\n #print(wall_position1)\n #plt.plot([wall_position1[0],x1],[wall_position1[1],y1],'r:',alpha=0.5)\n #print(wall)\n return wall_position1 #return to wall in all_ray_list\n \n def all_ray_list(self):\n ray_list =[]\n for p in self.mirror_reflect_points: \n wall = self.wall_position(p[0],p[1])\n if wall[0]>=0 and wall[0]<=500 and wall[1]>=0 and wall[1]<=500 :\n ray_list.append([p[0],p[1],wall[0],wall[1]])\n return ray_list\n \n def light_on_mirror(self,tx_id): \n light_on_mirror = []\n for px,py in self.mirror_pixel_list:\n cover = True\n for tx_plane in tx_id.all_tx_plane_id:\n if tx_plane.pixel_intensity[px][py]==0.0:\n cover = False\n break\n if cover==True:\n light_on_mirror.append([px,py]) \n return light_on_mirror\n\n def ray_to_object(self):\n ray_to_object_list = self.all_ray_list() #Initial rays from ray list\n i = 0\n for ray in ray_to_object_list:\n ray_distance = np.hypot(ray[2]-ray[0],ray[3]-ray[1]) \n for obs in all_obs_id:\n for k in range(len(obs.obsX)):\n x3 = obs.obsX[k]\n y3 = obs.obsY[k]\n x4 = obs.obsX[(k+1)%len(obs.obsX)]\n y4 = obs.obsY[(k+1)%len(obs.obsY)]\n result = intersect(ray[0],ray[1],ray[2],ray[3],x3,y3,x4,y4)\n if result[0] == True:\n distance = np.hypot(ray[0]-result[1],ray[1]-result[2]) \n if distance < ray_distance:\n ray_distance = distance \n ray_to_object_list[i][2] = result[1] #change wall[0] of ray_list[i] to be result[1]\n ray_to_object_list[i][3] = result[2]\n i+=1\n \n #print(\"ray_to_object_list =\",ray_to_object_list) \n return ray_to_object_list \n \n def all_ray_coverage(self):\n ray_coverage_list = []\n for ray in self.ray_to_object_list: \n ray_coverage_list.append(self.mirror_pixel_plane(ray[0],ray[1],ray[2],ray[3])) \n #print(ray_coverage_list)\n return ray_coverage_list\n \n def count_coverage(self):\n self.ray_pixel_coverage = PixelPlane(MAX_ROW,MAX_COLUMN) \n for ray in self.all_ray_coverage_list: #self.all_ray_coverage_list = self.all_ray_coverage()\n #print(ray)\n for gx,gy in ray:\n if not math.isclose(c1[gx][gy],5.0) : \n if not math.isclose(c1[gx][gy],2.0) :\n global c2 \n c2 = c2 + 1\n self.ray_pixel_coverage.pixel_intensity[gx][gy] = 2.0\n c1[gx][gy] = 2.0\n ##print(\"set coverage at \",gx,gy) \n \n #count = sum(self.ray_pixel_coverage.pixel_intensity) # <-- some computer cannot run \"sum\"\n count = 0\n for gx in range(MAX_COLUMN):\n for gy in range(MAX_ROW):\n if self.ray_pixel_coverage.pixel_intensity[gx][gy] == 2.0:\n count +=1\n \n \n count_percent = (count*100)/(MAX_ROW*MAX_COLUMN)\n \n # For compare with light coverage without mirror\n tx_cov_count = 0\n improve_coverage_from_light = count\n for px in range(MAX_COLUMN):\n for py in range(MAX_ROW):\n cover = True\n for tx_plane in tx_id.all_tx_plane_id:\n if tx_plane.pixel_intensity[px][py]==0.0:\n cover = False\n break\n if cover==True:\n T[px][py] = 2.0\n tx_cov_count+=1\n if self.ray_pixel_coverage.pixel_intensity[px][py] == 2.0:\n improve_coverage_from_light -= 1\n global Txcoverage\n Txcoverage = tx_cov_count \n tx_cov_count_percent = (tx_cov_count*100)/(MAX_ROW*MAX_COLUMN)\n improve_percent = improve_coverage_from_light*100/(MAX_ROW*MAX_COLUMN)\n new_overall_covearge = tx_cov_count + improve_coverage_from_light\n new_overall_covearge_percent = (new_overall_covearge*100)/(MAX_ROW*MAX_COLUMN)\n cover2.append(new_overall_covearge) \n #print(\"Mirror's Light Coverage Area (Pixels) =\",count)\n #print(\"Mirror's Light Coverage Percent =\",count_percent,\"%\")\n #print(\"Transmitter Coverage Area =\",tx_cov_count)\n #print(\"Transmitter Coverage Percent =\",tx_cov_count_percent,\"%\")\n #print(\"Mirror's Improved Area (reflect to shadow area) =\", improve_coverage_from_light)\n #print(\"Mirror's Improved Percent =\",improve_percent,\"%\")\n #print(\"New Coverage Area =\",new_overall_covearge)\n #print(\"New Covearge Area Percent =\",new_overall_covearge_percent,\"%\")\n \n return count,count_percent,tx_cov_count,improve_coverage_from_light,improve_percent,new_overall_covearge,new_overall_covearge \n \n\n def perp_toMirror(self,tx,ty,rx1,ry1,rx2,ry2): #Find the point that perpendicular to mirror\n x1=rx1\n y1=ry1\n x2=rx2\n y2=ry2\n x3=tx\n y3=ty\n k = ((y2-y1) * (x3-x1) - (x2-x1) * (y3-y1)) / ((y2-y1)**2 + (x2-x1)**2)\n x4 = x3 - k * (y2-y1)\n y4 = y3 + k * (x2-x1)\n ##print(x4,y4) # point perpend to mirror\n return (x4,y4)\n \n def perp(self,a) : #vector\n b = np.empty_like(a)\n b[0] = -a[1]\n b[1] = a[0]\n return b\n\n def room_wall_intersect(self,p1,p2, q1,q2) :\n da = p2-p1\n db = q2-q1\n dp = p1-q1\n dap = self.perp(da)\n denom = np.dot( dap, db)\n num = np.dot( dap, dp )\n return (num / denom.astype(float))*db + q1\n \n def shotgun(self,multiple): # On experiment // build multiple rays between 2 rays\n new_mirror_reflect_point_list = []\n for k in range(len(self.project_pixel_list)-1):\n px = self.project_pixel_list[k][0]\n pxx = self.project_pixel_list[k+1][0]\n py = self.project_pixel_list[k][1]\n pyy = self.project_pixel_list[k+1][1]\n add_px=[]\n add_py=[]\n for m in range(multiple):\n x_step = (pxx-px)/multiple\n add_px.append(px+x_step)\n y_step = (pyy-py)/multiple\n add_py.append(py+y_step)\n\n #print(\"add_px =\",add_px)\n #add_py = np.arange(py,pyy,(pyy-py)/multiple)\n for i in range(multiple):\n new_mirror_reflect_point_list.append([add_px[i],add_py[i]])\n\n new_mirror_reflect_point_list.append(self.project_pixel_list[k+1])\n #print(\"New multiple rays (shotgun) =\",new_mirror_reflect_point_list )\n return new_mirror_reflect_point_list\n\nclass Obstacle():\n def __init__(self,obsX,obsY,grid_size):\n self.obsX = obsX #obsX\n self.obsY = obsY #obsY\n self.grid_size = grid_size\n self.obs_plane = PixelPlane(MAX_ROW,MAX_COLUMN)\n self.px_max = math.ceil(max(obsX)/grid_size)\n self.py_max = math.ceil(max(obsY)/grid_size)\n self.px_min = math.floor(min(obsX)/grid_size)\n self.py_min = math.floor(min(obsY)/grid_size)\n self.pixel_count = 0\n self.setPixel()\n self.countPixel()\n\n def setPixel(self):\n for py in range(self.py_min,self.py_max+1):\n for px in range(self.px_min,self.px_max+1):\n cnt_crosspoint_r = 0\n cnt_crosspoint_l = 0\n x = px*self.grid_size\n y = py*self.grid_size \n is_edge = False\n for k in range(len(self.obsX)): \n x1 = x\n y1 = y\n x2 = self.px_max*self.grid_size\n y2 = y\n x3 = self.obsX[k]\n y3 = self.obsY[k]\n x4 = self.obsX[(k+1)%len(self.obsX)]\n y4 = self.obsY[(k+1)%len(self.obsY)]\n \n result = intersect(x1,y1,x2,y2,x3,y3,x4,y4)\n if result[0]==True:\n Xx = result[1] \n Xy = result[2] \n if Xx == x3 and Xy == y3: \n if y4= x3 and x1 <= x4) or (x1>=x4 and x1 <= x3):\n is_edge = True\n self.obs_plane.pixel_intensity[int(x1/self.grid_size)][int(y1/self.grid_size)] = 1.0\n #print([int(x1/self.grid_size)][int(y1/self.grid_size)])\n break\n\n x2 = self.px_min*self.grid_size\n result = intersect(x1,y1,x2,y2,x3,y3,x4,y4)\n if result[0]==True:\n Xx = result[1]\n Xy = result[2] \n if Xx == x3 and Xy == y3:\n if y4= x3 and x1 <= x4) or (x1>=x4 and x1 <= x3):\n is_edge = True\n self.obs_plane.pixel_intensity[int(x1/self.grid_size)][int(y1/self.grid_size)] = 1.0\n break\n \n if is_edge==False: \n if cnt_crosspoint_r%2==1 or cnt_crosspoint_l%2==1:\n self.obs_plane.pixel_intensity[int(x1/self.grid_size)][int(y1/self.grid_size)] = 1.0 \n\n def countPixel(self):\n px_cnt = 0\n for gx in range(MAX_COLUMN):\n for gy in range(MAX_ROW):\n if self.obs_plane.pixel_intensity[gx][gy] == 1.0:\n px_cnt+=1\n #print(\"Pixel Count =\",px_cnt)\n \n self.pixel_count = px_cnt\n### create Pixel Class\nclass Display() :\n def __init__(self,MAX_ROW,MAX_COLUMN,grid_size) :\n self.MAX_ROW = MAX_ROW\n self.MAX_COLUMN = MAX_COLUMN\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(111,aspect='equal')\n self.ax.set_xlim([-grid_size,MAX_COLUMN*grid_size])\n self.ax.set_ylim([-grid_size,MAX_ROW*grid_size])\n self.grid_size = grid_size\n self.pixel_id = []\n self.createpixel()\n plt.show(block=False)\n \n def createpixel(self): \n for k in range (self.MAX_COLUMN):\n self.pixel_id.append([0]*self.MAX_ROW)\n for x in range (self.MAX_COLUMN) :\n for y in range (self.MAX_ROW) :\n self.pixel_id[x][y] = self.ax.add_patch(\n patches.Rectangle(\n ((x-0.5)*self.grid_size,(y-0.5)*self.grid_size), # (x,y)\n self.grid_size, # width\n self.grid_size, # height\n color = 'salmon',alpha=0.1,ec='lightgrey'))\n\n def draw_obstacle(self,obs_id,color):\n obstacle_plane = obs_id.obs_plane\n \n for x in range (self.MAX_COLUMN):\n for y in range (self.MAX_ROW):\n if obstacle_plane.pixel_intensity[x][y]>0.0:\n c1[x][y] = 5.0\n self.pixel_id[x][y].set_facecolor(color)\n self.pixel_id[x][y].set_alpha(0.5)\n\n X = [k for k in obs_id.obsX]\n X.append(obs_id.obsX[0])\n Y = [k for k in obs_id.obsY]\n Y.append(obs_id.obsY[0]) \n self.ax.plot(X,Y,'-b')\n\n \n X = [obs_id.px_min,obs_id.px_max,obs_id.px_max,obs_id.px_min,obs_id.px_min]\n Y = [obs_id.py_min,obs_id.py_min,obs_id.py_max,obs_id.py_max,obs_id.py_min]\n X = [k*self.grid_size for k in X]\n Y = [k*self.grid_size for k in Y]\n self.ax.plot(X,Y,color='gray',alpha=0.3)\n self.fig.show()\n \n def draw_tx(self,tx_id):\n self.ax.plot(tx_id.xloc,tx_id.yloc,marker='o',color='red',alpha=1)\n for px in range (self.MAX_COLUMN):\n for py in range (self.MAX_ROW):\n cover = True\n for tx_plane in tx_id.all_tx_plane_id:\n if tx_plane.pixel_intensity[px][py]==0.0:\n cover = False\n break\n if cover==True:\n self.pixel_id[px][py].set_facecolor('g')\n self.pixel_id[px][py].set_alpha(0.5)\n self.fig.show()\n \n def draw_mirror(self,mirror_id): \n wallSide=mirror_id.wallSide\n position =mirror_id.position\n distance =mirror_id.distance\n mirror_width =mirror_id.mirror_width\n angle =mirror_id.angle\n \n mirro_loc = mirror_id.mirror_loc\n x1 = mirro_loc[0]\n y1 = mirro_loc[1]\n x2 = mirro_loc[2]\n y2 = mirro_loc[3]\n \n self.ax.plot([x1,x2],[y1,y2],marker='s',color='red') \n if mirror_id.wallSide == 'R' :\n self.ax.plot([np.average([x1,x2]),RoomWidth],[position,position],marker='o',color='b')\n elif mirror_id.wallSide == 'L' :\n self.ax.plot([0,np.average([x1,x2])],[position,position],marker='o',color='b')\n elif mirror_id.wallSide == 'T' :\n self.ax.plot([position,position],[np.average([y1,y2]),RoomHeight],marker='o',color='b')\n elif mirror_id.wallSide == 'B' :\n self.ax.plot([position,position],[0,np.average([y1,y2])],marker='o',color='b')\n \n\n for gx,gy in mirror_id.mirror_pixel_list:\n self.pixel_id[gx][gy].set_facecolor('yellow')\n \n self.fig.show() \n \n def draw_ray(self,mirror_id):\n ray_list = mirror_id.all_ray_list() \n for ray in ray_list:\n x1=ray[0] \n y1=ray[1]\n x2=ray[2] \n y2=ray[3]\n self.ax.plot([x1,x2],[y1,y2],color='gold',linestyle=':',alpha=0.5)\n \n def draw_ray_to_object(self,mirror_id):\n ray_list = mirror_id.ray_to_object() \n for ray in ray_list:\n x1=ray[0]\n y1=ray[1]\n x2=ray[2]\n y2=ray[3]\n self.ax.plot([x1,x2],[y1,y2],color='red',linestyle=':',alpha=0.2)\n \n def draw_ray_coverage(self,mirror_id):\n for ray_cov in mirror_id.all_ray_coverage_list: #/grid\n for gx,gy in ray_cov:\n if not math.isclose(c1[gx][gy],5.0) :\n self.pixel_id[gx][gy].set_facecolor('blue')\n self.pixel_id[gx][gy].set_alpha(0.2)\n self.fig.show()\n \n \nclass Transmitter():\n def __init__(self,TxLocation,grid_size,all_obs_id):\n self.xloc = TxLocation[0] \n self.yloc = TxLocation[1]\n self.grid_size = grid_size\n self.all_obs_id = all_obs_id\n \n self.all_tx_plane_id = []\n for obs in all_obs_id:\n self.set_pixel_coverage(obs)\n self.count_coverage()\n def set_pixel_coverage(self,obs): \n tx_plane_id = PixelPlane(MAX_ROW,MAX_COLUMN)\n self.all_tx_plane_id.append(tx_plane_id) \n #### Find coverage area\n x1 = self.xloc\n y1 = self.yloc \n for px2 in range(MAX_COLUMN):\n for py2 in range(MAX_ROW):\n if obs.obs_plane.pixel_intensity[px2][py2]==0.0:\n x2 = px2*grid_size\n y2 = py2*grid_size\n light_blocked = False\n for k in range(len(obs.obsX)):\n x3 = obs.obsX[k]\n y3 = obs.obsY[k]\n x4 = obs.obsX[(k+1)%len(obs.obsX)]\n y4 = obs.obsY[(k+1)%len(obs.obsY)]\n result = intersect(x1,y1,x2,y2,x3,y3,x4,y4)\n if result[0]==True:\n light_blocked = True \n break\n if light_blocked == False:\n tx_plane_id.pixel_intensity[int(x2/grid_size)][int(y2/grid_size)] = 1.0\n def count_coverage(self):\n pass\n\n\nmyDisplay = Display(MAX_ROW,MAX_COLUMN,grid_size) \n\n\nall_obs_id = []\nfor obs_vertex in allOBSvertex:\n obsX = [k[0] for k in obs_vertex]\n obsY = [k[1] for k in obs_vertex]\n all_obs_id.append(Obstacle(obsX,obsY,grid_size))\n \nmyDisplay.draw_obstacle(all_obs_id[0],'tan')\nmyDisplay.draw_obstacle(all_obs_id[1],'chocolate')\nmyDisplay.draw_obstacle(all_obs_id[2],'chocolate')\n\ntx_id = Transmitter(TxLocation,grid_size,all_obs_id)\nmyDisplay.draw_tx(tx_id)\n'''\nnum_of_mirror = 4\nmirrorDisplays = []\n\nfor i in range(num_of_mirror):\n myDisplay2 = Display(MAX_ROW,MAX_COLUMN,grid_size)\n myDisplay2.draw_tx(tx_id)\n \n myDisplay2.draw_obstacle(all_obs_id[0],'tan')\n myDisplay2.draw_obstacle(all_obs_id[1],'chocolate')\n myDisplay2.draw_obstacle(all_obs_id[2],'chocolate')\n mirrorDisplays.append(myDisplay2)\n''' \nobs_pixels =0\nfor obs in all_obs_id:\n #print(\"Pixel count =\",obs.pixel_count)\n obs_pixels += obs.pixel_count\n \n \nfig = plt.figure()\n\nax = fig.add_subplot(111)\n#ax1 = fig.add_subplot(111)\ncolorlist = ['blue','green','magenta','orange','red','brown','pink','grey','black']\n\nax.legend()\n\nfor index,max_angle in enumerate(range(5,50,5)):\n size = []\n covlist = []\n all_myMirror = []\n for s in range(0,50,10):\n c1 = []\n c2 = 0\n cover2 = []\n cov = []\n T = []\n Txcoverage = 0\n \n for k in range(MAX_ROW):\n c1.append([0]*MAX_COLUMN)\n T.append([0]*MAX_COLUMN)\n for x in range(MAX_COLUMN) :\n for y in range(MAX_ROW) :\n c1[x][y] = 0.0\n T[x][y] = 0.0\n\n for angle in range(-max_angle,max_angle+1,1):\n mirror = (['R',125,30,s,angle],['L',125,30,s,angle],['L',375,30,s,angle],['L',375,30,s,angle])\n for i in range (len(mirror)):\n mir = mirror[i]\n myMirror = Mirror(mir[0],mir[1],mir[2],mir[3],mir[4]) \n all_myMirror.append(myMirror)\n covv = myMirror.count_coverage()\n \n size.append(s)\n c22 = c2\n for x in range(MAX_COLUMN) :\n for y in range(MAX_ROW) :\n if math.isclose(T[x][y],2.0) : \n if math.isclose(c1[x][y],2.0) :\n c22 -= 1\n \n cov = Txcoverage+c22\n #print(obs_pixels)\n #print(Txcoverage)\n cov_percent = cov*100/((MAX_ROW*MAX_COLUMN)-obs_pixels)\n #print(cov_percent)\n covlist.append(cov_percent)\n #print(covlist)\n #print(covlist)\n ax.plot(size,covlist, color = colorlist[index], marker = 'D', linestyle = '-',label='R&L-max angle ={}'.format(max_angle))\n #line = mlines.Line2D(color=colorlist[index], marker = 'D', label='R&L-max angle ={}'.format(max_angle))\n\n\nax.set_xlabel('Reflector size (cm)')\nax.set_ylabel('Signal Coverage (%)')\nplt.yticks(range(60,105,5))\nplt.xticks(range(0,75,5))\n \nplt.grid()\nplt.legend()\n\nplt.show()\n\n#\n","sub_path":"graph4rotatable.py","file_name":"graph4rotatable.py","file_ext":"py","file_size_in_byte":31363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"388076056","text":"\n# Import the WSRC module that provides all of the code\n# to run a waterswap simulation\nfrom Sire.Tools import WSRC\n\n# Import the Units module so that we can specify the dimensions\n# (units) of input parameters\nfrom Sire.Units import *\n\n# Import the Stream module so that we can save restart files\nimport Sire.Stream\n\n# Create a dictionary of parameters for waterswap\nparams = {}\n\n# Give the name of the input amber topology and coordinate files\n# that contain the solvated, bound protein-ligand system\nparams[\"protein topfile\"] = \"proteinbox.top\"\nparams[\"protein crdfile\"] = \"proteinbox.crd\"\n\n## Specify the name of one of the residues in the ligand to be swapped.\n# The WSRC module will find the ligand molecule by looking for the first\n# molecule loaded that contains a residue with this name\nparams[\"ligand name\"] = \"ose\"\n\n# Specify the radius of the reflection sphere\nparams[\"reflection radius\"] = 10 * angstroms\n\n# Specify the temperature of the simulation\nparams[\"temperature\"] = 25 * celsius\n\n# Specify the lambda values to use\nparams[\"lambda values\"] = [ 0.01, 0.025, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.49,\n 0.51, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.975, 0.99 ]\nparams[\"lambda values\"] = [ 0.01, 0.3, 0.7, 0.99 ]\n\n# Specify the number of RETI iterations\nparams[\"nmoves\"] = 10\n\n# Specify the number of Monte Carlo moves to perform per RETI iteration\nparams[\"nsubmoves\"] = 100\n\nparams[\"waterbox only\"] = True\n\n# Specify the number of equilibration moves to perform when setting up the system\nparams[\"nequilmoves\"] = 50\n\n# Switch to use the TIP4P water model\n# params[\"water model\"] = \"tip4p\"\n\n# Specify the frequency of updating the residue- and water-based energy monitors\nparams[\"energy monitor frequency\"] = 5\n\n# I want to save the PDBs for debugging...\nparams[\"save pdb\"] = True\n\nparams[\"pdb frequency\"] = 5\n\nparams[\"restart\tfrequency\"] = 6\n\n# Actually run the simulation :-)\nWSRC.run(params)\n\n# Note that you can resume the simulation by rerunning this script. The script\n# records its progress so will always resume from where it last finished. This\n# means that you can increase the number of RETI iterations by increasing\n# params[\"nsubmoves\"] and rerunning the script.\n\n# If you want the simulation to be restarted from the beginning, you need to\n# remove all restart and output files, e.g. by running \"rm -rf output *.s3\"\n","sub_path":"corelib/examples/wsrc/runwsrc.py","file_name":"runwsrc.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236026954","text":"from train_eval.cnn_train_eval import *\nfrom data.dataset import *\nfrom models.cnn_model import *\n#from train_eval.rnn_train_eval import *\n#from models.rnn_model import *\n#from train_eval.rnn_attn_train_eval import *\n#from models.rnn_attn_model import *\nfrom utils.cnn_blue import *\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ntrain_data, test_data, val_data, QnA_vocab, Ans_Sen_vocab = loadDataset()\n\nINPUT_DIM = len(QnA_vocab)\nOUTPUT_DIM = len(Ans_Sen_vocab)\nEMB_DIM = 100\nHID_DIM = 512 # each conv. layer has 2 * hid_dim filters\nENC_LAYERS = 10 # number of conv. blocks in encoder\nDEC_LAYERS = 10 # number of conv. blocks in decoder\nENC_KERNEL_SIZE = 3 # must be odd!\nDEC_KERNEL_SIZE = 3 # can be even or odd\nENC_DROPOUT = 0.25\nDEC_DROPOUT = 0.25\nTRG_PAD_IDX = Ans_Sen_vocab.stoi[Ans_Sen.pad_token]\nBATCH_SIZE = 100\n\nprint(\"==> Building Encoder\")\n\nenc = Encoder(INPUT_DIM, EMB_DIM, HID_DIM, ENC_LAYERS, ENC_KERNEL_SIZE, ENC_DROPOUT, device, QnA_vocab.vectors)\n\nprint(\"==> Building Decoder\")\n\ndec = Decoder(OUTPUT_DIM, EMB_DIM, HID_DIM, DEC_LAYERS, DEC_KERNEL_SIZE, DEC_DROPOUT, TRG_PAD_IDX, device, Ans_Sen_vocab.vectors)\n\nprint(\"==> Building Seq2Seq Model\")\n\nmodel = Seq2Seq(enc, dec, device).to(device)\n\nmodel.load_state_dict(torch.load('checkpoints/cnn-model.pt'))\n\nbleu_score = calculate_bleu(test_data, QnA, Ans_Sen, model, device)\n\nprint('BLEU score = {:.2f}'.format(bleu_score*100))","sub_path":"Baseline_Models/evaluator/.ipynb_checkpoints/cnn_evaluator-checkpoint.py","file_name":"cnn_evaluator-checkpoint.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"404807816","text":"from django.shortcuts import render\n# Create your views here.\nfrom datetime import datetime\nimport json\nimport math\nimport jwt\nfrom django.http import HttpResponse,response,JsonResponse\nfrom django.shortcuts import render,redirect,reverse\nfrom . import models\n# Create your views here.\ndef show(request):\n with open(\"question/answer.json\",encoding='utf-8') as fp:\n data=json.load(fp)\n for i in data:\n print(i)\n models.answer.objects.create(**i)\n return HttpResponse(\"OK\")\n # return HttpResponse('show share')\n# 按条件搜索问答详细信息(还未分页)\ndef search(request):\n len = models.question.objects.count()\n l = math.ceil(len / 3)\n if not request.body:\n bb = []\n a1 = []\n ff = list(models.question.objects.filter(id__in=[1,2,3]).values('question_id'))\n for i in ff:\n # t_name=list(models.question.objects.filter(question_id=i[\"question_id\"]).values('launch_user_id'))[0]\n aa=list(models.question.objects.filter(question_id=i['question_id']).values('content'))[0]\n # print(aa,'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')\n # bb=list(models.answer.objects.filter(question_id_id=i['question_id']).values('answser_user_id'))[0]\n cc=list(models.answer.objects.filter(question_id_id=i['question_id']).values('content'))[0]\n print(cc,'ccccccccccccccccccccccccccccccccccccccc')\n # a1.append(t_name)\n aa['question_content']=aa.pop('content')\n a1.append(aa)\n # a1.append(bb)\n cc['answer_content']=cc.pop('content')\n a1.append(cc)\n ll = {'page': l}\n\n bb.append(a1)\n print(bb,'aaaaaaaaaaaaaaaaaaaaaaaaaaaa')\n bb.append(ll)\n print(bb)\n return JsonResponse({\"acount\": bb})\n else:\n bb = []\n a1 = []\n ff = list(models.question.objects.values('question_id'))\n page = int(json.loads(request.body)['page'])\n for i in range((page - 1) * 3, page * 3):\n aa = list(models.question.objects.filter(question_id=ff[i]['question_id']).values('content'))[0]\n cc = list(models.answer.objects.filter(question_id_id=ff[i]['question_id']).values('content'))[0]\n aa['question_content'] = aa.pop('content')\n a1.append(aa)\n cc['answer_content'] = cc.pop('content')\n a1.append(cc)\n ll = {'page': l}\n\n bb.append(a1)\n print(bb, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa')\n bb.append(ll)\n print(bb)\n return JsonResponse({\"acount\": bb})\n# 查看问题的详细内容\ndef questioninfo(request):\n aa=[]\n question=json.loads(request.body)\n question_content=question['content']\n\n # 查出问题的内容,提出问题的人\n qq=list(models.question.objects.filter(content=question_content).values('content','launch_user_id'))\n for i in qq:\n aa.append(i)\n print(list(qq))\n # 查出问题id\n q_id=models.question.objects.filter(content=question_content).values('id')\n print(list(q_id))\n question_id_id=list(q_id)[0]['id']\n answer_content=list(models.answer.objects.filter(question_id_id=question_id_id).values('content'))\n for i in answer_content:\n aa.append(i)\n\n\n\n return JsonResponse({'code':aa})\n\n#展示最新问题(带分页-------------------------------------------------)\ndef showQuestion(request):\n bb = []\n a1 = []\n aa=[]\n len = models.question.objects.count()\n # 拿到问题页数。一页显示三个\n l = math.ceil(len / 3)\n # 拿到前三条的问题id\n ff = list(models.question.objects.values('spare1'))\n print(ff)\n # if not request.body:\n # for i in ff:\n # a1.append(i['spare1'])\n # a1.sort()\n # ll = {'page': l}\n # a1.reverse()\n # for i in range(0,3):\n # vv=list(models.question.objects.filter(spare1=a1[i]).values('content','spare1','launch_user_id'))\n # # 此处spare1是\"2018-10-15 11:13:50.601522\"的,如何展示需商榷\n # bb.append(vv[0])\n #\n # bb.append(ll)\n # # print(bb)\n # return JsonResponse({\"acount\": bb})\n # else:\n # # 拿到前台传过来的页码\n page=int(json.loads(request.body)['page'])\n for i in ff:\n a1.append(i['spare1'])\n a1.sort()\n ll = {'page': l}\n a1.reverse()\n print(111111111111111111111111111111)\n for i in range((page-1)*3,page*3):\n # 拿到问题内容\n print(222222222222222222222222222222222222222222222222222222)\n vv=list(models.question.objects.filter(spare1=a1[i]).values('content'))\n # 此处spare1是\"2018-10-15 11:13:50.601522\"的,如何展示需商榷\n acc = list(models.question.objects.filter(spare1=a1[i]).values('question_id'))\n print(acc,33333333333333333333333333333333333333333333333333333333333333)\n abb=list(models.answer.objects.filter(question_id_id=acc[0]['question_id']).values('content'))\n bb.append({'question_content':vv[0]['content']})\n if abb:\n\n bb.append({'answer_content':abb[0]['content']})\n else:\n bb.append({'answer_content':''})\n print(33333333333333333333333333333333333333333333333333333333333333)\n\n aa.append(bb)\n aa.append(ll)\n # print(bb)\n return JsonResponse({\"acount\": aa})\n\n\n\n# 查看未解决问题(带分页------------------)\ndef waitquestion(request):\n\n a1 = []\n len = models.question.objects.filter(question_style_id=1).count()\n # 拿到未问题页数。一页显示三个\n l = math.ceil(len / 3)\n # ff是未解决问题和提问人的字典列表\n ff = list(models.question.objects.filter(question_style_id=1).values('content').order_by('-spare1'))\n # if request.body:\n # page=int(json.loads(request.body)['page'])\n # if page==1:\n # bb = []\n # for i in range(0,3):\n # a1.append(ff[i])\n # ll = {'page': l}\n # bb.append(a1)\n # # print(bb, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa')\n # bb.append(ll)\n # # print(bb)\n # return JsonResponse({\"acount\": bb})\n # else:\n # for i in range((page-1)*3,page*3):\n # bb = []\n # a1.append(ff[i])\n # ll = {'page': l}\n # bb.append(a1)\n # # print(bb, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa')\n # bb.append(ll)\n # # print(bb)\n # return JsonResponse({\"acount\": bb})\n # else:\n\n bb = []\n for i in range(0, 3):\n a1.append({'question_content':ff[i]['content']})\n a1.append({'answer_question':''})\n ll = {'page': l}\n bb.append(a1)\n # print(bb, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa')\n bb.append(ll)\n # print(bb)\n return JsonResponse({\"acount\": bb})\n\n#查看答案\ndef showAnswer(request):\n return HttpResponse('show answer')\n#问题分页\ndef queLimit(request):\n return HttpResponse('show question in limit')\n#答案分页\ndef ansLimit(request):\n return HttpResponse('show answer in limit')\n#提出问题\ndef ask(request):\n asd = request.META.get(\"HTTP_TOKEN\")\n SECRET_KEY = '123456'\n # 将headers中的token进行解密\n decoded = jwt.decode(asd, SECRET_KEY, audience='webkit', algorithms=['HS256'], options={'verify_exp': True})\n if decoded:\n ss = json.loads(request.body)\n cc=models.question.objects.count()\n ab = {\n 'spare1': datetime.now(),\n 'question_style_id':1,\n 'content': ss['content'],\n 'launch_user_id': decoded['user_id'],\n 'question_id':cc+1\n }\n models.question.objects.create(**ab)\n return JsonResponse({'code': '成功哦'})\n else:\n return JsonResponse({'code': 'token过期'})\n#回答问题\ndef answer(request):\n asd = request.META.get(\"HTTP_TOKEN\")\n SECRET_KEY = '123456'\n # 将headers中的token进行解密\n decoded = jwt.decode(asd, SECRET_KEY, audience='webkit', algorithms=['HS256'], options={'verify_exp': True})\n if decoded:\n name=decoded['user_id']\n ss=json.loads(request.body)['content']\n s2=json.loads(request.body)['answercontent']\n check=list(models.question.objects.filter(content=ss).values('question_id'))[0]['question_id']\n aa={\n 'content':s2,\n 'answser_user_id':name,\n 'question_id_id':check\n }\n models.answer.objects.create(**aa)\n return JsonResponse({'code':'成功哦'})\n else:\n return JsonResponse({'code':'token过期'})\n\n\n\n# 建表\ndef jianbiao(request):\n with open(\"question/answer.json\",encoding='utf-8') as fp:\n data=json.load(fp)\n\n for i in data:\n print(i)\n models.answer.objects.create(**i)\n return HttpResponse(\"OK\")\n","sub_path":"question/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"31981857","text":"import cv2 as cv\nimport numpy as np\n\n'''\n\n'''\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n#我们在下面自行创建了原始图片\nimg = np.zeros((400, 400), np.uint8)\ncv2.circle(img, (150, 150), 100, 255, -1)\ncv2.circle(img, (250, 250), 100, 255, -1)\n\n#进行了距离变换\ndist = cv2.distanceTransform(img, cv2.DIST_L2, cv2.DIST_MASK_3)#euclidean distance\n'''\n这里先插入一下opencv的distance type: 前面有CV_ 的都是老版本的写法,新版本无 CV_\nCV_DIST_USER =-1, /* User defined distance */\nCV_DIST_L1 =1, /* distance = |x1-x2| + |y1-y2| */\nCV_DIST_L2 =2, /* the simple euclidean distance */\nCV_DIST_C =3, /* distance = max(|x1-x2|,|y1-y2|) */\nCV_DIST_L12 =4, /* L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */\nCV_DIST_FAIR =5, /* distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */\nCV_DIST_WELSCH =6, /* distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */\nCV_DIST_HUBER =7 /* distance = |x|\n'''\n\n#单通道向三通道转换,watershed只接受三通道的图像\ndist3 = np.zeros((dist.shape[0], dist.shape[1], 3), dtype = np.uint8)\ndist3[:, :, 0] = dist\ndist3[:, :, 1] = dist\ndist3[:, :, 2] = dist\n\n#创建分类的图层,包含种子点\nmarkers = np.zeros(img.shape, np.int32)\ncv2.circle(markers, (150, 150), 100, 0, -1)\ncv2.circle(markers, (250, 250), 100, 0, -1)\nmarkers[150,150] = 1 # seed for circle one\nmarkers[250, 250] = 2 # seed for circle two\nmarkers[50, 50] = 3 # seed for background\nmarkers[350, 350] = 4 # seed for background\n\n#执行分水岭算法\ncv2.watershed(dist3, markers)\nplt.imshow(markers)\nplt.show()\n'''\n但如果我们仔细看过上面的原理分析,就会发现分水岭内部是通过判断梯度来决定下一个种子点的选择的。\n在那张距离变换的图上,背景部分的梯度永远都是0,所以背景部分会优先与山峰部分被标记,\n知道背景部分遇到了山峰的边缘部分,这个时候的梯度跟山顶部分的梯度相当,\n这时,山顶的种子才有可能后的向四临域泛洪的机会,\n所以两个种子的标签类最终会在山腰部分相遇,形成分水岭,这个山腰大概是1/2圆半径的位置。\n'''","sub_path":"opencv_轮廓检测/分水岭算法2.py","file_name":"分水岭算法2.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"77361997","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport torch as th\nimport torch.nn as nn\n\n\nclass StackLSTM(nn.Module):\n def __init__(self, context_dim, output_dim, hidden_size=512, num_layers=3, dropout=0):\n super(StackLSTM, self).__init__()\n self.stack_rnn = nn.LSTM(input_size=context_dim, hidden_size=hidden_size, \\\n num_layers=num_layers, dropout=dropout, batch_first=True)\n self.fconn = nn.Linear(hidden_size, output_dim)\n\n def forward(self, x):\n if type(x) == nn.utils.rnn.PackedSequence:\n packed, _ = self.stack_rnn(x)\n x = self.fconn(packed.data)\n else:\n t, n, _ = x.shape\n x, _ = self.stack_rnn(x)\n x = x.view(t * n, -1)\n x = self.fconn(x)\n return x\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"168023537","text":"from datetime import datetime\r\n\r\n#Global stuff \r\nnow = datetime.now()\r\n\r\ncurrent_day = now.day \r\ncurrent_year = now.year \r\n\r\ncurrent_minutes = now.strftime(\"%M\")\r\ndaytime = now.strftime(\"%p\")\r\nx = now.hour \r\n\r\n#find the right time of day ie. am or pm and the hour to use\r\nif x > 12:\r\n current_hour = x - 12\r\nelif x == 12:\r\n current_hour = x \r\nelse:\r\n current_hour = x \r\n\r\n\r\n#show todays date in month day, year format, with month as the months name and not the number\r\n\r\ndef show_date():\r\n \"\"\"\r\n Show current date in month day, year format\r\n \"\"\"\r\n date_to_show = (\"Today is {} {}, {}\").format(now.strftime(\"%B\"), current_day, current_year)\r\n print(date_to_show)\r\n\r\n#show todays time in hours:minutes am/pm format \r\ndef show_time(): \r\n \"\"\"\r\n displays the current time with hour:minutes AM/PM format\r\n \"\"\"\r\n time_to_show = (\"It is currently {}:{} {}\").format(current_hour,current_minutes,daytime)\r\n print(time_to_show)\r\n\r\n","sub_path":"displaydateandtime.py","file_name":"displaydateandtime.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"632276332","text":"import pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# This is included in TokenVis\n\n# Load the data\ncsv = 'clean_tweet.csv'\nmy_df = pd.read_csv(csv,index_col=0)\n\n# Remove NA values and sort according to sentiment\nmy_df.dropna(inplace=True)\nmy_df.reset_index(drop=True,inplace=True)\nmy_df.info()\n# my_df = my_df[(my_df['target'] == 0) | (my_df['target'] == 1)]\nmy_df = my_df.sort_values(by=['target'])\nmy_df = my_df.reset_index(drop=True)\n\n# Extract term frequency for visualization\ncvec = CountVectorizer()\ncvec.fit(my_df.text)\n#len(cvec.get_feature_names())\n\n# Separate the positive and negative terms\nneg_doc_matrix = cvec.transform(my_df[my_df.target == 0].text)\npos_doc_matrix = cvec.transform(my_df[my_df.target == 1].text)\nneg_tf = np.sum(neg_doc_matrix,axis=0)\npos_tf = np.sum(pos_doc_matrix,axis=0)\nneg = np.squeeze(np.asarray(neg_tf))\npos = np.squeeze(np.asarray(pos_tf))\nterm_freq_df = pd.DataFrame([neg,pos],columns=cvec.get_feature_names()).transpose()\n\ndocument_matrix = cvec.transform(my_df.text)\n\n# Get the beggening and end of the batches. If the data is small enough or your RAM\n# can take it, you can run the whole data, otherwise you should break it into batches.\nstart_neg = my_df[my_df['target']==0].index.values.astype(int)[0]\nend_neg = my_df[my_df['target']==0].index.values.astype(int)[-1]\nstart_pos = my_df[my_df['target']==1].index.values.astype(int)[0]\nend_pos = my_df[my_df['target']==1].index.values.astype(int)[-1]\n\n# Define the negative batch\nneg_batches = np.linspace(start_neg,end_neg +1,100).astype(int)\n# Start the counter and the term frequency vector\n\ni=0\nneg_tf = []\n# For each term in the batch, calculate the frequency of the term\nwhile i < len(neg_batches)-1:\n batch_result = np.sum(document_matrix[neg_batches[i]:neg_batches[i+1]].toarray(),axis=0)\n neg_tf.append(batch_result)\n if (i % 10 == 0) | (i == len(neg_batches)-2):\n print(neg_batches[i+1],\"entries' term freuquency calculated\")\n i += 1\n\n# Define the positive batch\npos_batches = np.linspace(start_pos,end_pos+1,100).astype(int)\n# Start the counter and the term frequency vector\ni=0\npos_tf = []\n# For each term in the batch, calculate the frequency of the term\nwhile i < len(pos_batches)-1:\n batch_result = np.sum(document_matrix[pos_batches[i]:pos_batches[i+1]].toarray(),axis=0)\n pos_tf.append(batch_result)\n if (i % 10 == 0) | (i == len(pos_batches)-2):\n print(pos_batches[i+1],\"entries' term freuquency calculated\")\n i += 1\n\n# Sum all the arrays to have total the frequency for each word\nneg = np.sum(neg_tf,axis=0)\npos = np.sum(pos_tf,axis=0)\n# Create a term frequency data frame, with the terms and their total, positive and negative\n# frequencies\nterm_freq_df = pd.DataFrame([neg,pos],columns=cvec.get_feature_names()).transpose()\n#term_freq_df.head()\n\nterm_freq_df.columns = ['negative', 'positive']\nterm_freq_df['total'] = term_freq_df['negative'] + term_freq_df['positive']\n#term_freq_df.sort_values(by='total', ascending=False).iloc[:10]\n\nlen(term_freq_df)\n\nterm_freq_df.to_csv('term_freq_df.csv',encoding='utf-8')\n","sub_path":"RickyKimsTuto/termFreq.py","file_name":"termFreq.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"193417936","text":"#!/usr/bin/env python\n\"\"\"Script for analyzing a single file in the algoComp2015.1.0 project\n\nReplaces the former segment_one_corpus.sh script. Run the file with\nthe '--help' option to get in.\n\nCopyright 2015, 2016 Alex Cristia, Mathieu Bernard\n\n\"\"\"\n\nimport argparse\nimport os\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\n\n\nCDSPATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pipeline')\n\"\"\"The algoComp/pipeline directory in CDSwordSeg\"\"\"\n\n\nclass NonAGSegmenter(object):\n \"\"\"A general wrapper to non-AG word segmentation algorithms\n\n :param str algo: the segmentation algorithm to use, in supported_algos()\n :param str tags: the tags file of phonologized utterances to segment\n :param str output_dir: the output directory where to store the results\n :param str script_dir: algoComp/pipeline directory in CDSwordSeg\n\n This class creates output_dir, copy tags in it and create the\n command to be executed.\n\n \"\"\"\n def __init__(self, algo, tags, gold, output_dir, script_dir=CDSPATH):\n # check the algo is supported\n if algo not in self.supported_algos():\n raise ValueError('unknown algo {}'.format(algo))\n self.algo = algo\n\n # get the absolute path to the algo script\n self.script = self._script(script_dir)\n if not os.path.isfile(self.script):\n raise ValueError('non-existing script {}'.format(self.script))\n\n # create the output dir and copy the tags and gold files in\n # it. Be conservative and do not overwrite any data in the\n # result directory.\n if os.path.isdir(output_dir):\n raise ValueError('result directory already exists {}'\n .format(output_dir))\n if not os.path.isfile(tags):\n raise ValueError('non-existing tags file {}'\n .format(tags))\n self.output_dir = output_dir\n os.mkdir(self.output_dir)\n shutil.copy(tags, os.path.join(output_dir, 'tags.txt'))\n shutil.copy(gold, os.path.join(output_dir, 'gold.txt'))\n\n # create the command lanuching the script\n self.command = ' '.join(\n [self.script,\n os.path.abspath(os.path.join(script_dir, '..')) + '/', # ABSPATH\n self.output_dir + '/']) # RESFOLDER\n\n self.ncores = self._ncores()\n\n def __repr__(self):\n \"\"\"Return a string representation\"\"\"\n return ' -> '.join([self.algo, self.output_dir])\n\n @staticmethod\n def supported_algos():\n \"\"\"Algorithms supported by this class\"\"\"\n return ['dibs', 'dmcmc', 'ngrams', 'puddle', 'TPs']\n\n\n def _ncores(self):\n try:\n return {'dmcmc': 5}[self.algo] # 5-fold xeval\n except KeyError:\n return 1\n\n def _script(self, script_dir):\n \"\"\"Return the absolute path to the script behind self.algo\"\"\"\n return os.path.abspath(os.path.join(script_dir, self.algo + '.sh'))\n\n\nclass AGSegmenter(NonAGSegmenter):\n def __init__(self, algo, tags, gold, output_dir,\n script_dir=CDSPATH, debug=False):\n NonAGSegmenter.__init__(self, algo, tags, gold, output_dir, script_dir)\n\n self.command += ' ' + self.algo\n if debug:\n self.command += ' debug'\n self.ncores = 8\n\n @staticmethod\n def supported_algos():\n \"\"\"Algorithms supported by the WordSegmenter class\"\"\"\n return ['AGc3sf', 'AGu']\n\n def _script(self, script_dir):\n \"\"\"Return the absolute path to the script behind self.algo\"\"\"\n return os.path.abspath(os.path.join(script_dir, 'AG_jap.sh'))\n\n\ndef supported_algos():\n return AGSegmenter.supported_algos() + NonAGSegmenter.supported_algos()\n\n\ndef create_nonag(algo, args):\n algo_dir = os.path.join(args.output_dir, algo)\n return NonAGSegmenter(algo, args.tagsfile, args.goldfile, algo_dir, args.cds_dir)\n\n\ndef create_ag(algo, args):\n # special case of AG median: run N jobs\n if args.ag_median > 1:\n jobs = []\n for i in range(1, args.ag_median+1):\n algo_dir = os.path.join(args.output_dir, algo + '_' + str(i))\n jobs.append(AGSegmenter(algo, args.tagsfile, args.goldfile,\n algo_dir, args.cds_dir, args.ag_debug))\n return jobs\n else: # only one job\n algo_dir = os.path.join(args.output_dir, algo)\n return AGSegmenter(algo, args.tagsfile, args.goldfile,\n algo_dir, args.cds_dir, args.ag_debug)\n\n\ndef create_jobs(args):\n \"\"\"Return a list of initialized WordSegmenter instances\"\"\"\n algos = args.algorithms\n if algos == ['all']:\n algos = supported_algos()\n\n jobs = []\n for algo in algos:\n j = create_ag(algo, args) if 'AG' in algo else create_nonag(algo, args)\n if isinstance(j, list):\n jobs += j\n else:\n jobs.append(j)\n return jobs\n\n\ndef clusterizable():\n \"\"\"Return True if the 'qsub' command is found in the PATH\"\"\"\n try:\n subprocess.check_output(shlex.split('which qsub'))\n return True\n except:\n return False\n\n\ndef write_command(command, bin='bash'):\n \"\"\"Write a two lines script from command and return its path\"\"\"\n tfile = tempfile.mkstemp()[1]\n with open(tfile, 'w') as f:\n f.write('#!/usr/bin/env ' + bin + '\\n')\n f.write(command + '\\n')\n return tfile\n\n\ndef run_job(job, clusterize=False, basename='', log2file=True):\n \"\"\"Call the command as a subprocess or schedule it in the cluster\n\n The log2file option can be set to False to log to stdout instead,\n this option only works when running jobs locally (i.e. with\n clusterize is False).\n\n basename is the prefix of the job name when using qsub.\n\n \"\"\"\n ofile = os.path.join(job.output_dir, 'log')\n\n if clusterize and clusterizable():\n fcommand = write_command(job.command)\n jobname = job.algo if basename == '' else basename + '_' + job.algo\n print('name = {}'.format(jobname))\n ncores = ('-pe openmpi {}'.format(job.ncores)\n if job.ncores != 1 else '')\n command = ('qsub {} -j y -V -cwd -o {} -N {} {}'\n .format(ncores, ofile, jobname, fcommand))\n res = subprocess.check_output(shlex.split(command))\n return res.split()[2] # job pid on the cluster\n else:\n ofile = (open(ofile, 'a') if log2file else sys.stdout)\n return subprocess.Popen(\n shlex.split(job.command),\n stdout=ofile,\n stderr=subprocess.STDOUT)\n\n\ndef wait_jobs(pids, clusterize):\n \"\"\"Wait all the pids in list are terminated and return\"\"\"\n if clusterize and clusterizable():\n print('waiting for jobs...')\n fcommand = write_command('echo done')\n command = ('qsub -j y -V -cwd -o /dev/null -N waiting -sync yes '\n '-hold_jid {} {}'.format(','.join(pids.values()), fcommand))\n subprocess.call(shlex.split(command), stdout=sys.stdout)\n else:\n for pid in pids.iteritems():\n print('waiting {} of pid {}'.format(pid[0].algo, pid[1].pid))\n pid[1].wait()\n\n\ndef write_gold_file(tags, gold):\n \"\"\"remove ;eword and ;esyll in tags to create gold\"\"\"\n with open(gold, 'w') as out:\n for line in open(tags, 'r').xreadlines():\n goldline = (line.replace(';esyll', '')\n .replace(' ', '')\n .replace(';eword', ' ').strip())\n # remove multiple contiguous spaces\n goldline = ' '.join(goldline.split())\n out.write(goldline + '\\n')\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\n description='This script is a segmentation pipeline binding a '\n 'phonologized input to various word segmentation algorithms.')\n\n parser.add_argument(\n '-v', '--verbose', action='store_true',\n help='display some log during execution')\n\n parser.add_argument(\n '--log-to-stdout', action='store_true', help=\n \"\"\"output log messages to stdout (by default log to OUTPUT_DIR/log)\"\"\")\n\n parser.add_argument(\n 'tagsfile', type=str, metavar='TAGSFILE',\n help='input tag file containing the utterances to segment in words. '\n 'One phonologized utterance per line, with ;esyll and ;eword '\n 'separators as outputed by the phonologizer')\n\n g1 = parser.add_argument_group('I/O optional parameters')\n\n g1.add_argument(\n '-g', '--goldfile', type=str, default=None,\n help='gold file containing the gold version of the tags file, '\n 'i.e. with ;esyll removed and ;eword replaced by a space. '\n 'If not provided, compute it')\n\n g1.add_argument(\n '--cds-dir', type=str, default=CDSPATH,\n help='algoComp/pipeline directory in CDSwordSeg. '\n 'default is {}'.format(CDSPATH))\n\n g1.add_argument(\n '-d', '--output-dir', type=str,\n default=os.path.curdir,\n metavar='OUTPUT_DIR',\n help='directory to write output files. Default is to write in `.` , '\n \"each selected algo create it's own subdirectory in OUTPUT_DIR\")\n\n g2 = parser.add_argument_group('Computation parameters')\n g2.add_argument(\n '-a', '--algorithms', type=str, nargs='+', default=['dibs'],\n choices=supported_algos() + ['all'],\n metavar='ALGO',\n help='choose algorithms in {}, or choose \"all\", '\n 'default is to compute dibs.'.format(supported_algos()))\n\n g2.add_argument(\n '-c', '--clusterize', action='store_true',\n help='schedule jobs on the cluster if the qsub command is detected, '\n 'else of if not specified, run jobs as parallel subproceses.')\n\n g2.add_argument(\n '-j', '--jobs-basename', type=str, default='',\n help='if --clusterize, basename of scheduled jobs')\n\n g2.add_argument(\n '-s', '--sync', action='store_true',\n help='wait all the jobs are terminated before exiting')\n\n g3 = parser.add_argument_group('Adaptor Grammar specific parameters')\n g3.add_argument(\n '--ag-debug', action='store_true',\n help='setup the AG algorithm in debug configuration, '\n 'this have no effect on other algorithms')\n\n g3.add_argument(\n '--ag-median', type=int, default=1, metavar='N',\n help='run the AG algorithms N times and return the median evaluation, '\n 'default is N=1, this have no effect on other algorithms')\n\n args = parser.parse_args()\n if args.verbose:\n print('parsed arguments are:\\n '\n + str(args).replace('Namespace(', '').replace(', ', '\\n ')[:-1])\n\n return args\n\n\ndef main():\n \"\"\"Entry point of the segmentation pipeline\"\"\"\n # parse input arguments\n args = parse_args()\n\n # check that tags file and CDS dir exists\n assert os.path.isfile(args.tagsfile), \\\n 'invalid tags file {}'.format(args.tagsfile)\n assert os.path.isdir(args.cds_dir), \\\n 'invalid CDS dir {}'.format(args.cds_dir)\n\n # create the output dir if needed\n args.output_dir = os.path.abspath(args.output_dir)\n # assert not os.path.isdir(args.output_dir), \\\n # 'result directory already exists: {}'.format(args.output_dir)\n if not os.path.isdir(args.output_dir):\n os.mkdir(args.output_dir)\n\n # compute the gold file if not given\n if args.goldfile is None:\n base, ext = os.path.splitext(args.tagsfile)\n args.goldfile = base + '-gold' + ext\n\n if args.verbose:\n print('writing gold file to {}'.format(args.goldfile))\n\n write_gold_file(args.tagsfile, args.goldfile)\n else:\n assert os.path.isfile(args.goldfile), \\\n 'invalid gold file {}'.format(args.goldfile)\n\n # create and run the segmentation jobs, store their pid\n jobs = create_jobs(args)\n pids = {}\n for job in jobs:\n pids[job] = run_job(job, args.clusterize, args.jobs_basename,\n log2file=not args.log_to_stdout)\n\n if args.verbose:\n print('launched jobs are')\n for k, v in pids.iteritems():\n print(' {} : {}'.format(k, v.pid))\n\n # wait all the jobs terminate\n if args.sync:\n wait_jobs(pids, args.clusterize)\n\n\nif __name__ == '__main__':\n # main()\n try:\n main()\n except Exception as err:\n print >> sys.stderr, 'fatal error in {} : {}'.format(__file__, err)\n sys.exit(1)\n","sub_path":"segment_jap.py","file_name":"segment_jap.py","file_ext":"py","file_size_in_byte":12415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583114894","text":"from pyspark.sql import SparkSession\nfrom pyspark import SparkContext\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import *\nimport datetime\n\nstart = datetime.datetime.now()\nprint(datetime.datetime.now()-start)\n\n#the input file is a csv with source & destination vertices for each edge (separator: ',')\n#I got a test graph from here : https://snap.stanford.edu/data/#socnets\n#the input file has to be copied to dse fs beforehand :\n#>dse fs\n#dsefs> put file:/home/py/data/graphs/soc-LiveJournal1_clean.txt soc-LiveJournal1_clean.txt\n\n#input_file = \"soc-sign-bitcoinalpha.csv\"\n#graph_name = \"graph_sandbox\"\n\ninput_file = \"soc-LiveJournal1_clean.txt\"\ngraph_name = \"graph_live_journal\"\n\nEdgeInputDirectory = \"/\"\nspark = SparkSession.builder.getOrCreate()\n\nprint(str(datetime.datetime.now()-start)+\":reading input file\")\nDF = spark.read.csv(EdgeInputDirectory + input_file, inferSchema =True, sep=\",\", header=False)\nprint(DF.dtypes)\nprint(DF.count())\nDF.show()\n\n#print(str(datetime.datetime.now()-start)+\":creating vertices DF\")\n#DF_vertices = DF.select(\"_c0\").union(DF.select(\"_c1\")).distinct().withColumnRenamed(\"_c0\",\"_id\").withColumn(\"~label\", lit(\"account\"))\n#DF_vertices.show()\n#print(DF_vertices.count())\n\ng = SparkContext._jvm.com.datastax.bdp.graph.spark.graphframe.DseGraphFrameBuilder.dseGraph(graph_name, spark._jsparkSession)\n\n#print(str(datetime.datetime.now()-start)+\":reading vertices from the graph\") #not useful (check)\n#vertices = spark.read.format(\"com.datastax.bdp.graph.spark.sql.vertex\").option(\"graph\", graph_name ).load()\n#vertices.show()\n#print(vertices.count())\n\n#print(str(datetime.datetime.now()-start)+\":updating vertices...\")\n#DF_vertices.write.format(\"com.datastax.bdp.graph.spark.sql.vertex\").option(\"graph\", graph_name).save(mode=\"append\")\n\n#print(str(datetime.datetime.now()-start)+\":reading vertices from the graph\") #not useful (check)\n#vertices = spark.read.format(\"com.datastax.bdp.graph.spark.sql.vertex\").option(\"graph\", graph_name ).load()\n#vertices.show()\n#print(vertices.count())\n\nprint(datetime.datetime.now()-start)\n\nprint(str(datetime.datetime.now()-start)+\":edges:\")\nDF_edges = DF.select(\"_c0\",\"_c1\").withColumnRenamed(\"_c0\",\"out_id\").withColumnRenamed(\"_c1\",\"in_id\")\nDF_edges.show()\nprint(DF_edges.dtypes)\n\n#print(str(datetime.datetime.now()-start)+\":reading edges from the graph...\") #not useful (check)\n#edges = spark.read.format(\"com.datastax.bdp.graph.spark.sql.edge\").option(\"graph\", graph_name ).load()\n#edges.show()\n#print(edges.count())\n#print(edges.dtypes)\n\nprint(str(datetime.datetime.now()-start)+\":writing edges to the graph\") \ng.updateEdges(\"account\",\"is_linked_to\", \"account\", DF_edges._jdf)\n\n#print(str(datetime.datetime.now()-start)+\":reading edges from the graph\") #not useful (check)\n#edges = spark.read.format(\"com.datastax.bdp.graph.spark.sql.edge\").option(\"graph\", graph_name ).load()\n#edges.show()\n#print(edges.count())\n\nprint(str(datetime.datetime.now()-start)+\":end\")\n\n#parking lot\n#df = spark.read.format('json').load('python/test_support/sql/people.json')\n\n","sub_path":"load_graph_cleaner.py","file_name":"load_graph_cleaner.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"529911829","text":"import os.path\nimport nltk\nimport json\nimport numpy as NP\nfrom scipy import linalg as LA\n\n#tputil = text processor utilites\n\n# the separator character in database.dat file\nDATABASE_SEPARATOR = '\\t\\t\\t'\nKNOWLEDGEBASE_FILE = 'knowledgebase.dat'\nDATABASE_FILE = 'database.dat'\n\n# method to remove the file without raisin an error\ndef remove_file(filepath):\n try:\n os.remove(filepath)\n except OSError:\n pass\n\n\n# adds a file to the database.dat file\ndef add_to_database(filename):\n if not os.path.isfile(filename):\n print(\"Error: Input file not found.\")\n return\n \n database = open(DATABASE_FILE, 'a')\n importfile = open(filename, 'r')\n \n database.write(importfile.read())\n database.write(DATABASE_SEPARATOR)\n \n importfile.close()\n database.close()\n \n\n# compiles a single text and adds it to the knowledge base\ndef compile_text(text, knowledgebase):\n fingerprint = writing_fingerprint(text)\n fingerprint_str = json.dumps(fingerprint)\n knowledgebase.write(fingerprint_str+'\\n')\n\n\n# compiles the database.dat file and adds it to the knowledge base \ndef compile_database():\n if not os.path.isfile(DATABASE_FILE):\n print(\"Error: No database found.\")\n return\n \n knowledgebase = open(KNOWLEDGEBASE_FILE, 'a')\n database = open(DATABASE_FILE, 'r')\n rawtext = database.read()\n texts = rawtext.split(DATABASE_SEPARATOR)\n \n for text in texts:\n compile_text(text, knowledgebase)\n \n knowledgebase.close()\n database.close()\n\n\n# takes all the text files in the books folder and compiles them into knowledge base\ndef compile_books():\n knowledgebase = open(KNOWLEDGEBASE_FILE, 'a')\n books_path = os.getcwd()+\"\\\\books\\\\\"\n files = [ f for f in os.listdir(books_path) if os.path.isfile(os.path.join(books_path,f)) ]\n for file_ in files:\n book = open(books_path+file_,'r')\n text = book.read()\n book.close()\n compile_text(text, knowledgebase)\n \n knowledgebase.close()\n\n \ndef purge():\n remove_file(DATABASE_FILE)\n remove_file(KNOWLEDGEBASE_FILE)\n\n \n# it takes a normal string and creates a text identifying\ndef writing_fingerprint(text):\n tokenized_text = nltk.word_tokenize(text)\n #create a 5000*50 matrix, which represents the text\n matrix = text_matrix(tokenized_text)\n result = pca(matrix)\n return result\n\n\ndef text_matrix(tokenized_text):\n WORD_CHUNKS = 5000 # the number of chunks the text should be cut up\n WORDS = 50 # the length of a single chunk\n common_words = nltk.FreqDist(tokenized_text).most_common(WORDS) # the common words\n all_words = len(tokenized_text) # the number of all words\n words_per_chunk = all_words // WORD_CHUNKS # divided by the length of a single chunk, should give us the number of words in a chunk\n remainder = all_words % WORD_CHUNKS # however we still have some extra words\n matrix = [] # the result matrix\n word_index = 0 # a helping variable\n for index in range(WORD_CHUNKS): # iterate from 0 to WORD_CHUNKS\n end_index = word_index + words_per_chunk # calculate the end index\n if index < remainder: # the first 'remainder' chunks will have 1 extra word\n end_index+=1\n \n text_chunk = tokenized_text[word_index:end_index] # get the text chunk\n word_index = end_index\n fdist = nltk.FreqDist(text_chunk) # get the word distribution\n chunk_word_count = []\n for word in common_words: # for all common words\n chunk_word_count.append(fdist[word[0]]) # get the number of times the word was used in the chunk\n \n matrix.append(chunk_word_count) # append the chunk's row to the matrix\n\n return matrix\n\n# exact copy from https://github.com/alexland/kPCA/blob/master/PCA.py\n# good for now, until we don't figure out what it does.\ndef pca(matrix, num_eigenvalues=None, EV=0, LDA=0):\n D = NP.array(matrix)\n if not (LDA & EV):\n D, EV = NP.hsplit(D, [-1])\n \n # D -= D.mean(axis=0)\n R = NP.corrcoef(D, rowvar=False)\n m, n = R.shape\n if num_eigenvalues:\n num_eigenvalues = (m - num_eigenvalues, m-1)\n eva, evc = LA.eigh(R, eigvals=num_eigenvalues)\n NP.ascontiguousarray(evc) \n NP.ascontiguousarray(eva)\n idx = NP.argsort(eva)[::-1]\n evc = evc[:,idx]\n eva = eva[idx]\n return eva.tolist()\n","sub_path":"tputil.py","file_name":"tputil.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"288638018","text":"from classes.IndexAccessor import IndexAccessor\nfrom pprint import pprint\nfrom math import log\nfrom random import randint\nfrom org.apache.lucene.index import PostingsEnum, TermsEnum, Term\nfrom org.apache.lucene.util import BytesRef, BytesRefIterator, Version\nfrom collections import defaultdict\n\nfrom org.apache.lucene.queries.mlt import MoreLikeThis\nfrom org.apache.lucene.analysis.standard import StandardAnalyzer\nfrom org.apache.lucene.analysis import CharArraySet\nfrom org.apache.lucene.search import TermQuery, BooleanQuery, BooleanClause\nfrom java.util import Arrays, HashSet\n\n\nimport settings as s\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass Article:\n def __init__(self, dbPediaName, seed='first'):\n\n self.dbPediaName = dbPediaName\n self.seed = seed\n self.SAIndexId = IndexAccessor.retrieverSA.searchDocId(dbPediaName, \"subject\")\n self.CatIndexId = IndexAccessor.retrieverCatMerged.searchDocId(dbPediaName, \"subject\")\n self.initTermVectorsCat()\n self.initTermVectorsSA()\n\n def getCathegories(self, topN=1, merged=True):\n \"\"\" return article cathogories in two form meged into one string or separate as tuple entries \"\"\"\n if merged:\n return IndexAccessor.retrieverCatMerged.search(self.dbPediaName, topN)\n else:\n return IndexAccessor.retrieverCat.search(self.dbPediaName, topN)\n\n def getAbstract(self):\n \"\"\" return article short abstract \"\"\"\n return IndexAccessor.retrieverSA.search(self.dbPediaName, 1)\n\n def getTermVectorSA(self):\n \"\"\" returns 'lucene' representation\"\"\"\n if self.SAIndexId is not None:\n return IndexAccessor.readerSA.getTermVector(self.SAIndexId, 'object')\n else:\n return None\n\n def getTermVectorCat(self):\n \"\"\" returns 'lucene' representation\"\"\"\n if self.CatIndexId is not None:\n return IndexAccessor.readerCatMerged.getTermVector(self.CatIndexId, 'object')\n else:\n return None\n\n def initTermVectorsSA(self):\n \"\"\"\n method initiates two class variables\n termsSA - all terms from short abstract\n termsFreqSA - all term from short abstract with occurance frequency\n \"\"\"\n try:\n termsEnum = self.getTermVectorSA().iterator()\n termsref = BytesRefIterator.cast_(termsEnum)\n terms = list()\n termsNum = {}\n while (termsref.next()):\n termval = TermsEnum.cast_(termsref)\n term = termval.term().utf8ToString()\n termCount = termval.totalTermFreq()\n termsNum[term] = termCount\n terms.append(term)\n self.termsSA = terms\n self.termsFreqSA = termsNum\n except AttributeError:\n logger.warning(f\"Article {self.dbPediaName} doesn't have short abstract\")\n self.termsSA = list()\n self.termsFreqSA = {}\n\n def initTermVectorsCat(self):\n \"\"\"\n method initiates two class variables\n termsCat - all terms from cathegories\n termsFreqCat - all term from cathegories with occurance frequency\n \"\"\"\n try:\n termsEnum = self.getTermVectorCat().iterator()\n termsref = BytesRefIterator.cast_(termsEnum)\n terms = list()\n termsNum = {}\n while (termsref.next()):\n termval = TermsEnum.cast_(termsref)\n term = termval.term().utf8ToString()\n termCount = termval.totalTermFreq()\n termsNum[term] = termCount\n terms.append(term)\n self.termsCat = terms\n self.termsFreqCat = termsNum\n except AttributeError:\n logger.warning(f\"Article {self.dbPediaName} doesn't have cathegories\")\n self.termsCat = list()\n self.termsFreqCat = {}\n\n # obsolete use atribute -> must be initiated first\n def getTFVectorSA(self):\n termsEnum = self.getTermVectorSA().iterator()\n termsref = BytesRefIterator.cast_(termsEnum)\n termsNum = {}\n while (termsref.next()):\n termval = TermsEnum.cast_(termsref)\n term = termval.term().utf8ToString()\n termCount = termval.totalTermFreq()\n termsNum[term] = termCount\n return termsNum\n\n # obsolete use atribute -> must be initiated first\n def getTFVectorCat(self):\n termsEnum = self.getTermVectorCat().iterator()\n termsref = BytesRefIterator.cast_(termsEnum)\n termsNum = {}\n while (termsref.next()):\n termval = TermsEnum.cast_(termsref)\n term = termval.term().utf8ToString()\n termCount = termval.totalTermFreq()\n termsNum[term] = termCount\n return termsNum\n\n def getSimilarArticles(self, targetBase, topN):\n similarArticles = ()\n if targetBase == 'sa':\n similarArticles = IndexAccessor.retrieverSA.searchSimilar(self.dbPediaName, topN)\n elif targetBase == 'cat':\n similarArticles = IndexAccessor.retrieverCatMerged.searchSimilar(self.dbPediaName, topN)\n return similarArticles\n\n def pickSimilar(self, articleName, topN, linkType, similarBase='cat'):\n if similarBase == 'sa':\n simRetriever = IndexAccessor.retrieverSA\n simReader = IndexAccessor.readerSA\n elif similarBase == 'cat':\n simRetriever = IndexAccessor.retrieverCatMerged\n simReader = IndexAccessor.readerCatMerged\n else:\n raise ValueError(f\"similarBase cannot be {similarBase} must be 'cat' or 'sa'\")\n\n if linkType == \"in\":\n a = IndexAccessor.retrieverLinks.search2(articleName, 1024, \"outlink\", \"page\")\n elif linkType == \"out\":\n a = IndexAccessor.retrieverLinks.search2(articleName, 1024, \"page\", \"outlink\")\n else:\n raise ValueError(f\"linkType cannot be {linkType} must be 'in' or 'out'\")\n\n bool = BooleanQuery.Builder()\n for i in a:\n bool.add(BooleanClause(TermQuery(Term('subject', i)), BooleanClause.Occur.SHOULD))\n mlt = MoreLikeThis(simReader)\n mlt.setBoost(True)\n mlt.setAnalyzer(StandardAnalyzer(CharArraySet(HashSet(Arrays.asList(s.stopwords)), True)))\n mlt.setFieldNames('object')\n\n docId = simRetriever.searchDocId(articleName, 'subject')\n\n if docId is None:\n return set()\n\n query = mlt.like(docId)\n # some article cathegories dont have a high engouh term frequency, lucene default is 2\n if str(query) == '':\n mlt.setMinTermFreq(1)\n query = mlt.like(docId)\n FinalQuery = BooleanQuery.Builder()\n\n FinalQuery.add(query, BooleanClause.Occur.MUST)\n # FinalQuery.add(query,BooleanClause.Occur.SHOULD)\n FinalQuery.add(bool.build(), BooleanClause.Occur.MUST)\n hits = simRetriever.searcher.search(FinalQuery.build(), topN + 1).scoreDocs\n result = []\n for hit in hits:\n doc = simRetriever.searcher.doc(hit.doc)\n if articleName not in doc.get('subject'):\n result.append(doc.get('subject'))\n if len(result) == topN:\n break\n return set(result)\n\n def getOutLinks(self, maxDepth, topN, selectStrategy='similar', similarBase='cat'):\n outLinks = defaultdict(list)\n depth = 1\n a = [self.dbPediaName]\n outLinks[0].append(self.dbPediaName)\n while depth <= maxDepth:\n for article in a:\n if selectStrategy == 'similar':\n outLinks[depth] += list(self.pickSimilar(article, topN, 'out', similarBase))\n else:\n outLinks[depth] += list(IndexAccessor.retrieverLinks.search2(article, topN, \"page\", \"outlink\"))\n a = outLinks[depth]\n depth += 1\n return outLinks\n\n def getInLinks(self, maxDepth, topN, selectStrategy='similar', similarBase='cat'):\n inLinks = defaultdict(list)\n depth = 1\n a = [self.dbPediaName]\n inLinks[0].append(self.dbPediaName)\n while depth <= maxDepth:\n for article in a:\n if selectStrategy == 'similar':\n inLinks[depth] += list(self.pickSimilar(article, topN, 'in', similarBase))\n else:\n inLinks[depth] += list(IndexAccessor.retrieverLinks.search2(article, topN, \"outlink\", \"page\"))\n a = inLinks[depth]\n depth += 1\n return inLinks\n\n def getSameCathegoryLinked(self, catTreshold, topN):\n sameCathegory = defaultdict(list)\n sameCathegory[0].append(self.dbPediaName)\n articles = list()\n cat = set(self.getCathegories(50, False))\n inLinks = self.getInLinks(1, 1000, \"random\", 'cat')\n for inLink in inLinks[1]:\n if (inLink != self.dbPediaName) and (self.dbPediaName in IndexAccessor.retrieverLinks.search2(inLink, 1000, \"page\", \"outlink\")):\n if len(cat.intersection(set(IndexAccessor.retrieverCat.search(inLink, 50)))) >= 1:\n articles.append(inLink)\n if len(articles) < topN:\n topN = len(articles)\n sameCathegory[1] = articles[:topN]\n return sameCathegory\n\n def getSameCathegoryLinked2(self, maxDepth, catTreshold, topN):\n sameCathegory = defaultdict(list)\n sameCathegory[0].append(self.dbPediaName)\n depth = 1\n articles = list()\n a = [self.dbPediaName]\n while depth <= maxDepth:\n for article in a:\n articles = list()\n pom = topN\n cat = set(IndexAccessor.retrieverCat.search(article, 50))\n inLinks = IndexAccessor.retrieverLinks.search2(article, 1000, \"outlink\", \"page\")\n for inLink in inLinks:\n if (inLink != article) and (article in IndexAccessor.retrieverLinks.search2(inLink, 1000, \"page\", \"outlink\")):\n if len(cat.intersection(set(IndexAccessor.retrieverCat.search(inLink, 50)))) >= 1:\n articles.append(inLink)\n if len(articles) < pom:\n pom = len(articles)\n sameCathegory[depth] += articles[:topN]\n a = sameCathegory[depth]\n depth += 1\n return sameCathegory\n\n def pickFromSets(self, links, similar, n):\n if len(links) < n:\n n = len(links)\n a = links.intersection(similar)\n b = list(links.difference(similar))\n diffN = len(b)\n ln = n - len(a)\n counter = 0\n while counter < ln:\n ran = randint(0, diffN - 1)\n if b[ran] not in a:\n counter += 1\n a.add(b[ran])\n return a\n\n def __repr__(self):\n return self.dbPediaName\n","sub_path":"classes/Article.py","file_name":"Article.py","file_ext":"py","file_size_in_byte":10897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"557127505","text":"# @Email: jmaggio14@gmail.com\n# @Website: https://www.imagepypelines.org/\n# @License: https://github.com/jmaggio14/imagepypelines/blob/master/LICENSE\n# @github: https://github.com/jmaggio14/imagepypelines\n#\n# Copyright (c) 2018 Jeff Maggio, Nathan Dileas, Ryan Hartzell\ndef format_dict(dictionary):\n \"\"\"\n creates a formatted string that represents a dictionary on multiple lines\n\n >>> a = \"{'d': 4, 'b': 2, 'c': 3, 'a': {'d': 4, 'b': 2, 'c': 3, 'a': {'d': 4, 'b': 2, 'c': 3, 'a': 1}}}\"\n >>> a\n {\n 'a' : {\n 'a' : {\n 'a' : 1,\n 'b' : 2,\n 'c' : 3,\n 'd' : 4,},\n 'b' : 2,\n 'c' : 3,\n 'd' : 4,},\n 'b' : 2,\n 'c' : 3,\n 'd' : 4,}\n \"\"\"\n formatted = \"\"\n for key in sorted(dictionary):\n val = dictionary[key]\n\n if isinstance(key,str):\n key = \"'{}'\".format(key)\n\n if isinstance(val,dict):\n val = format_dict(val).replace('\\n','\\n' + ' ' * (len(key)+3))\n\n formatted += \"\\n{} : {},\".format(key,val)\n\n return '{' + formatted + '}'\n\ndef main():\n import copy\n import imagepypelines as ip\n a = {'a':1,'b':2,'c':3,'d':4}\n b = copy.deepcopy(a)\n b['a'] = copy.deepcopy(a)\n b['a']['a'] = copy.deepcopy(a)\n print( ip.util.format_dict(b) )\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"imagepypelines/util/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"83472135","text":"import os\nfrom datetime import datetime, timedelta, date\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom session import LianJiaSession\nimport sys\n\n\nclass Report:\n\n def __init__(self, report_date, city=None):\n lj_session = LianJiaSession(city)\n self.city = lj_session.city\n self.city_zh = lj_session.get_city_zh()\n engine = lj_session.get_sql_engine()\n self.__yaml_data = lj_session.get_prop()\n self.root_path = lj_session.get_log_path()\n self.logging = lj_session.get_logger()\n self.log_file_path = lj_session.get_log_file_name();\n conn = engine.raw_connection()\n self.cursor = conn.cursor()\n self.query_time = report_date\n self.today = datetime.today()\n self.date_str = self.get_date_str()\n\n def report(self):\n argvs = dict()\n argvs['min_house'] = self.__yaml_data['min_house']\n argvs['query_date'] = self.query_time\n argvs['date'] = self.date_str\n argvs['city_zh'] = self.city_zh\n\n total_house = self.total_house()\n argvs['total_house'] = total_house\n\n argvs['zhang_jia'] = self.get_zd_count(zd='z')\n argvs['die_jia'] = self.get_zd_count(zd='d')\n\n total_price_change = argvs['zhang_jia'] + argvs['die_jia']\n argvs['total_price_change'] = total_price_change\n if total_price_change == 0:\n argvs['die_jia_p'] = 0\n argvs['zhang_jia_p'] = 0\n else:\n argvs['die_jia_p'] = argvs['die_jia']/total_price_change*100\n argvs['zhang_jia_p'] = argvs['zhang_jia']/total_price_change*100\n argvs['price_change_p'] = total_price_change/total_house*100\n\n argvs['fu_du'] = 5\n argvs['fu_du_z'] = self.get_zd_count(zd='z', fu_du=argvs['fu_du'])\n\n argvs['fu_du_d'] = self.get_zd_count(zd='d', fu_du=argvs['fu_du'])\n argvs['fu_du_t'] = argvs['fu_du_z'] + argvs['fu_du_d']\n\n argvs['new_house_count'] = self.get_new_house_count()\n argvs['xiao_qu_count'] = self.get_xiao_qu_count()\n argvs['total'] = self.get_house_cout()\n if argvs['fu_du_t'] == 0:\n argvs['die_jia_t_p'] = 0\n argvs['zhang_jia_t_p'] = 0\n else:\n argvs['die_jia_t_p'] = argvs['fu_du_d']/argvs['fu_du_t']*100\n argvs['zhang_jia_t_p'] = argvs['fu_du_z']/argvs['fu_du_t']*100\n\n district_arr = self.get_district()\n zt = 0\n dt = 0\n new_total = 0\n zhang_arr = []\n die_arr = []\n new_house_arr = []\n for item in district_arr:\n z = self.get_zd_count(zd='z', fu_du=argvs['fu_du'], district=item)\n d = self.get_zd_count(zd='d', fu_du=argvs['fu_du'], district=item)\n new_count = self.get_new_house_count(district=item)\n zt += z\n dt += d\n new_total += new_count\n new_house_arr.append(new_count)\n zhang_arr.append(z)\n die_arr.append(d)\n\n if argvs['new_house_count'] != new_total:\n raise Exception('总房源数计算错误!')\n # print('总计 {0} {1} {2}'.format(new_total, zt, dt))\n self.image(district_arr, zhang_arr, die_arr)\n self.get_new_house_pie(district_arr, new_house_arr)\n\n\n format_str = \"{city_zh}{query_date}({date})二手房大数据(来源于某家网):\\n\" \\\n \"数据来源于{xiao_qu_count}个小区(在售房源大于等于{min_house}套),总房源{total}套,新增房源{new_house_count}套。\\n\" \\\n \"挂牌价格变动房源共计{total_price_change}套,\" \\\n \"其中涨价{zhang_jia}套({zhang_jia_p:.2f}%),跌价{die_jia}套({die_jia_p:.2f}%)。\\n\" \\\n \"涨跌幅5%以内的共计{fu_du_t}套,其中涨价{fu_du_z}({zhang_jia_t_p:.2f}%)套,跌价{fu_du_d}({die_jia_t_p:.2f}%)套。\\n\" \\\n \"\\n以上信息仅供参考 : )\"\n report_str = format_str.format(**argvs)\n self.logging.info(report_str)\n\n # 通过status查看\n def get_house_cout(self):\n sql = 'select count(*) FROM house h where h.`status`=1'\n self.cursor.execute(sql)\n total = self.cursor.fetchone()[0]\n return total\n\n def export_xiao_qu_excel(self):\n sql_price_change = \"SELECT \th.id, \txq.`name` AS 小区, \th.title AS 标题, \tp.pre_price AS 昨日总价(万),p.price AS 今日总价(万), p.priceChange AS 价格变化(万), \tp.fudu AS 涨跌幅(百分比), h.unit_price AS 单价(元), h.area AS 面积(平方), d.district AS 区, d.area AS 板块, CONCAT('https://wh.lianjia.com/ershoufang/',h.url, '.html') AS 链接, \th.hu_xing AS 户型, \th.zhuang_xiu AS 装修, h.flood AS 楼层, h.chao_xiang AS 朝向, h.star AS 关注, p.change_time AS 时间 FROM price_change_com p, house h, xiao_qu xq, district_area d \"\n\n\n # 通过日志查看\n def get_house_cout2(self):\n start = '该页li个数['\n end = ']检测旧房源'\n sl = len(start)\n file = open(r'F:\\python\\pythonProject\\LianJia\\logs\\20200105\\1829_wuhan_log.log', 'r', encoding=\"utf-8\")\n lines = file.readlines()\n count = 0\n for line in lines:\n i = line.find(start)\n j = line.find(end)\n if i != -1 and j != -1:\n c = line[i + sl:j]\n count += int(c)\n print(count)\n\n def get_xiao_qu_count(self):\n sql = 'select count(*) from xiao_qu xq where xq.zai_shou>=' + str(self.__yaml_data['min_house'])\n self.cursor.execute(sql)\n return self.cursor.fetchone()[0]\n\n def get_new_house_pie(self, ingredients, data):\n fig, ax = plt.subplots(figsize=(10, 8), subplot_kw=dict(aspect=\"equal\"))\n\n def func(pct, allvals):\n absolute = int(pct / 100. * np.sum(allvals))\n return \"{:.1f}%\\n({:d}套)\".format(pct, absolute)\n\n wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data), textprops=dict(color=\"w\"))\n\n ax.legend(wedges, ingredients,\n title=\"区域\",\n loc=\"center left\",\n bbox_to_anchor=(1, 0, 0.5, 1)\n )\n plt.setp(autotexts, size=8, weight=\"bold\")\n ax.set_title(\"武汉二手房获取检测样本新增房源({0})\".format(self.date_str))\n path = os.path.join(self.root_path, 'newHouse_{0}_{1}.png'.format(self.city, self.date_str))\n plt.savefig(path)\n\n def image(self, labels, zhang_arr, die_arr):\n x = np.arange(len(labels)) # the label locations\n width = 0.35 # the width of the bars\n\n fig, ax = plt.subplots()\n rects1 = ax.bar(x - width / 2, zhang_arr, width, label='涨价')\n rects2 = ax.bar(x + width / 2, die_arr, width, label='跌价')\n\n # Add some text for labels, title and custom x-axis tick labels, etc.\n ax.set_ylabel('房源数')\n ax.set_title('武汉二手房获取检测样本挂牌价涨跌幅5%以内({0})'.format(self.date_str))\n ax.set_xticks(x)\n ax.set_xticklabels(labels)\n ax.legend()\n\n def autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\n autolabel(rects1)\n autolabel(rects2)\n fig.tight_layout()\n path = os.path.join(self.root_path, 'priceChange5percent_{0}_{1}.png'.format(self.city, self.date_str))\n plt.savefig(path)\n\n def get_zd_count(self, zd=None, fu_du=None, district=None):\n where_sql = self.get_where(zd=zd, fu_du=fu_du, district=district)\n select_sql = 'SELECT count(*) FROM price_change_com p, house h, xiao_qu xq, district_area d '\n sql = '{0} WHERE {1}'.format(select_sql, where_sql)\n self.cursor.execute(sql)\n return self.cursor.fetchone()[0]\n\n def get_where(self, zd, fu_du=None, district=None):\n where_sql = 'p.house_id = h.id AND xq.id = h.xiao_qu AND xq.district = d.id '\n if '今日' == self.query_time:\n where_sql += ' AND TO_DAYS(p.change_time) = TO_DAYS(NOW()) '\n elif '最近' == self.query_time:\n where_sql += ' AND TO_DAYS(p.change_time) >= DATE_SUB(NOW(),INTERVAL 3 HOUR) '\n elif '昨日' == self.query_time:\n where_sql += ' AND TO_DAYS(p.change_time) = TO_DAYS(NOW())-1 '\n elif '本周' == self.query_time:\n where_sql += ' AND TO_DAYS(p.change_time) >= TO_DAYS(NOW())-6 '\n elif '上周' == self.query_time:\n where_sql += ' AND(date_format(p.change_time, \"%Y-%m-%d\")) = YEARWEEK(now())-1 '\n elif '上月' == self.query_time:\n where_sql += ' AND PERIOD_DIFF(date_format( now(),\"%Y%m\" ) , date_format(p.change_time,\"%Y%m\")) =1 '\n\n if zd == 'z':\n where_sql += ' AND p.priceChange>0 '\n elif zd == 'd':\n where_sql += ' AND p.priceChange<0 '\n if fu_du:\n where_sql += ' AND p.fudu<{0} and p.fudu>-{0} '.format(fu_du)\n if district:\n where_sql += ' AND d.district=\"{0}\" '.format(district)\n return where_sql\n\n def get_date_str(self):\n date_str = self.today.strftime(\"%Y.%m.%d\")\n if '昨日' == self.query_time:\n date_str = (self.today + timedelta(days=-1)).strftime(\"%Y.%m.%d\")\n elif '本周' == self.query_time:\n date_str = (self.today + timedelta(days=-6)).strftime(\"%Y.%m.%d\") + ' -- ' + date_str\n elif '上周' == self.query_time:\n year, week, day = self.today.isocalendar()\n date_str = (self.today + timedelta(days=-6 - day)).strftime(\"%Y.%m.%d\") + ' -- ' + \\\n (self.today + timedelta(days=-day)).strftime(\"%Y.%m.%d\")\n elif '上月' == self.query_time:\n date_str = '{0}月份'.format(self.today.month-1)\n return date_str\n\n def total_house(self):\n sql = 'select count(*) from house'\n self.cursor.execute(sql)\n total = self.cursor.fetchone()[0]\n return total\n\n def get_status_0(self):\n sql = 'SELECT * from house h WHERE h.status=0 '\n self.cursor.execute(sql)\n total = self.cursor.fetchone()[0]\n return total\n\n def get_district(self):\n sql = 'select name from district where parent is null'\n self.cursor.execute(sql)\n district_arr = []\n arr = self.cursor.fetchall()\n for item in arr:\n district_arr.append(item[0])\n return district_arr\n\n def get_new_house_count(self, district=None):\n if '今日' == self.query_time:\n where = ' WHERE TO_DAYS(h.create_time) = TO_DAYS(NOW()) '\n elif '最近' == self.query_time:\n where = ' WHERE TO_DAYS(h.create_time) >= DATE_SUB(NOW(),INTERVAL 3 HOUR) '\n elif '昨日' == self.query_time:\n where = ' WHERE TO_DAYS(h.create_time) >= TO_DAYS(NOW())-1 '\n elif '本周' == self.query_time:\n where = ' WHERE TO_DAYS(h.create_time) >= TO_DAYS(NOW())-6 '\n elif '上周' == self.query_time:\n where = ' WHERE YEARWEEK(date_format(h.create_time, \"%Y-%m-%d\")) = YEARWEEK(now())-1'\n elif '上月' == self.query_time:\n where = ' WHERE PERIOD_DIFF(date_format( now(), \"%Y%m\") , date_format(h.create_time, \"%Y%m\")) =1'\n if district is None:\n select = 'select count(*) from house h '\n else:\n select = 'select count(*) from house h , xiao_qu xq, district_area d '\n where += ' AND h.xiao_qu=xq.id AND xq.district=d.id AND d.district=\"{0}\"'.format(district)\n self.cursor.execute(select + where)\n total = self.cursor.fetchone()[0]\n return total\n\n\nif '__main__' == __name__:\n plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体\n plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题\n # 今日 昨日 本周 上周 上月\n if len(sys.argv) == 3:\n filename, report_date, city = sys.argv\n report = Report(report_date, city)\n elif len(sys.argv) == 2:\n filename, report_date = sys.argv\n report = Report(report_date)\n elif len(sys.argv) == 1:\n report_date = '今日'\n report = Report(report_date)\n report.report()\n","sub_path":"Report.py","file_name":"Report.py","file_ext":"py","file_size_in_byte":12614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"166265448","text":"import json\nimport socket\nimport ssl\n\nimport OpenSSL\nimport requests\nimport urllib3\n\n\nfrom MTStoreDetail.date_util import get_timestamp\nfrom MTStoreDetail.oracle_util import OracleUtil\nfrom MTStoreDetail.agent_util import AgentPoolUtil\n\nagent_pool_util = AgentPoolUtil()\ng_user_agent = agent_pool_util.get_user_agent()\ng_proxy = agent_pool_util.get_proxy()\ng_cookie = agent_pool_util.get_cookie()\nsession = requests.Session()\nconnection = OracleUtil()\n\n'''\n抓取mt店铺详情页\n'''\ndef get_shop_info(url,code):\n if code == 1:\n global g_user_agent\n global g_proxy\n global g_cookie\n g_proxy = agent_pool_util.get_proxy()\n g_user_agent = agent_pool_util.get_user_agent()\n print(\"切换代理IP和User Agent成功!\")\n headers = {\n 'Host': 'm.dianping.com',\n 'User-Agent': g_user_agent,\n 'Cookie': g_cookie\n }\n\n global session\n try:\n response = session.get(url,headers=headers,proxies=g_proxy,timeout= 40)\n response.encoding='utf-8'\n status_code = response.status_code\n text = response.text\n # print(text)\n if status_code == 403:\n session = requests.Session()\n get_shop_info(url, 1)\n if '很抱歉,您要访问的页面不存在' in text:\n print(\"页面不存在!\")\n return 'not_exist'\n if '验证中心' in text:\n print(\"验证中心!\")\n return 'not_exist'\n # print(text)\n return text\n\n except socket.timeout as e:\n print('ConnectionResetError')\n get_shop_info(url, 1)\n except requests.exceptions.ReadTimeout as e:\n print('ConnectionResetError')\n return 'time_out'\n except ConnectionResetError as e:\n print('ConnectionResetError')\n get_shop_info(url, 1)\n except urllib3.exceptions.MaxRetryError as e:\n print('urllib3.exceptions.MaxRetryError')\n get_shop_info(url, 1)\n except requests.exceptions.ProxyError as e:\n print('requests.exceptions.ProxyError')\n get_shop_info(url, 1)\n except OpenSSL.SSL.SysCallError as e:\n print('OpenSSL.SSL.SysCallError')\n get_shop_info(url, 1)\n except ssl.SSLError as e:\n print('ssl.SSLError')\n get_shop_info(url, 1)\n except requests.exceptions.SSLError as e:\n print('requests.exceptions.SSLError')\n get_shop_info(url, 1)\n except OpenSSL.SSL.WantReadError as e:\n print('OpenSSL.SSL.WantReadError')\n get_shop_info(url, 1)\n except requests.exceptions.ConnectionError as e:\n print('OpenSSL.SSL.WantReadError')\n get_shop_info(url, 1)\n\n'''\n构造需要向download api提交的数据\n'''\ndef get_json_data(data):\n json_data = data\n result_total = json_data.get('result').get('total')\n result_data = json_data.get('result').get('data')\n prev_data = []\n fail_url = []\n success_url = []\n fail_counter = 0\n for sub in result_data:\n\n content = get_shop_info(sub.get('url'),0)\n if 'not_exist' == content:\n fail_url.append((get_timestamp(),sub.get('url')))\n fail_counter += 1\n print('not_exist_counter=%d' % (fail_counter))\n if fail_counter % 3 == 0:\n global g_cookie\n g_cookie = agent_pool_util.get_cookie()\n print('切换Cooki成功!')\n else:\n data = {\n \"attemptCount\": sub.get('attemptCount'),\n \"content\": content,\n \"currentDepth\": sub.get('currentDepth'),\n \"downloadTime\": get_timestamp(),\n \"downloadTool\": sub.get('downloadTool'),\n \"failureCount\": sub.get('failureCount'),\n \"httpMethodName\": sub.get('httpMethodName'),\n \"httpStatus\": 200,\n \"markId\": sub.get('markId'),\n \"maxDepth\": sub.get('maxDepth'),\n \"other\": {\n \"additionalProp1\": \"string\",\n \"additionalProp2\": \"string\",\n \"additionalProp3\": \"string\"\n },\n \"parentTraceId\": sub.get('parentTraceId'),\n \"publishTime\": sub.get('publishTime') if sub.get('publishTime') is not None else 0,\n \"publisherId\": sub.get('publisherId'),\n \"purl\": \"0000\",\n \"responseHeaders\": {\n \"X-API-TOKEN\":'aaaa',\n \"connection\":'Keep-Alive',\n \"user-agent\": \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)\",\n \"Content-Type\": \"application/json\"\n },\n \"ruleId\": sub.get('ruleId'),\n \"taskId\": sub.get('taskId'),\n \"taskInstanceId\": sub.get('taskInstanceId'),\n \"traceId\": sub.get('traceId'),\n \"url\": sub.get('url'),\n \"urlType\": sub.get('urlType')\n }\n prev_data.append(data)\n success_url.append((get_timestamp(),sub.get('url')))\n\n result_total = result_total - fail_counter\n\n if fail_counter != 0:\n print(\"爬取失败[ %d ]个页面!\" %(fail_counter))\n connection.mark_not_exit_url(fail_url)\n\n if result_total == 0:\n return (success_url,result_total)\n else:\n return_data = {\n \"data\": prev_data,\n \"total\": result_total\n }\n # print(json.dumps(return_data))\n return (success_url,return_data)\n\n\n\n","sub_path":"MTStoreDetail/crawl_util.py","file_name":"crawl_util.py","file_ext":"py","file_size_in_byte":5421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"173066480","text":"# -*- coding: utf-8 -*-\n\n# by kysdm\n\nimport re\nfrom bs4 import BeautifulSoup\n# pip3 install bs4\n# pip3 install lxml\nimport requests\n\n# **************用户变量********************\n\nuid = 'xxxxx'\ncookie = '__cfduid=xxxxx; nexusphp_u2=xxxxx; __dtsu=xxxxx'\n\n# **************用户变量********************\n\n\ndef tlist():\n headers = {\n 'Referer': f'https://u2.dmhy.org/userdetails.php?id={uid}',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',\n 'cookie': cookie\n }\n print('开始下载列表... (如果报错,代表连接U2失败)\\n')\n html = requests.get(\n f'https://u2.dmhy.org/getusertorrentlistajax.php?userid={uid}&type=leeching', headers=headers)\n soup = BeautifulSoup(html.text, 'lxml')\n tobj = soup.find_all('table', attrs={'class': 'torrentname'})\n tobj2 = soup.find_all(href=re.compile(r'^details.+#seeders', re.S))\n re1 = re.compile(r'href=\"details.php\\?id=(\\d+?)&hit=1\"', re.S)\n re2 = re.compile(r'(.+?)<\\/b>', re.S)\n re3 = re.compile(r'(.+?)<\\/b>', re.S)\n re4 = re.compile(r'details.php\\?id=(\\d+)', re.S)\n re5 = re.compile(r'>(\\d+?)', re.S)\n\n seeders = []\n for v in tobj2:\n _id = (re.findall(re4, str(v)))[0]\n _seeders = (re.findall(re5, str(v)))[0]\n seeders.append((_id, _seeders))\n\n for v in tobj:\n if 'alt=\"2X Free\"' in str(v):\n texit((re.findall(re1, str(v)))[0], '2X Free')\n elif 'alt=\"FREE\"' in str(v):\n texit((re.findall(re1, str(v)))[0], 'FREE')\n elif 'alt=\"下载比率\"' in str(v) and '0.00X' in str(v):\n texit((re.findall(re1, str(v)))[\n 0], f'{(re.findall(re2, str(v)))[0]} {(re.findall(re3, str(v)))[0]}')\n else:\n Magic((re.findall(re1, str(v)))[0], seeders)\n\n\ndef texit(t_id, mag):\n if mag == 'FREE':\n print(f'ID:{t_id} 已存在魔法:{mag}')\n elif mag == '2X Free':\n print(f'ID:{t_id} 已存在魔法:{mag}')\n else:\n print(f'ID:{t_id} 已存在魔法:{mag}')\n\n\ndef Magic(torrent_id, seeders):\n for v in seeders:\n if str(v[0]) == str(torrent_id):\n if int(v[1]) == 0:\n print(f'ID:{torrent_id} 无人做种,暂不释放魔法')\n else:\n # 下面注释掉的参数,估计是用来计算所需uc的,反正有钱,不计算了\n data = {\n 'action': 'magic',\n # 'divergence':'6.974',#全站基数\n # 'base_everyone':'1200',\n # 'base_self':'350',\n # 'base_other':'500',\n 'torrent': torrent_id, # 种子ID\n # 'tsize':'3822707742',#种子大小\n # 'ttl':'4163',#种子已存在时间\n 'user': 'SELF', # 为自己放魔法\n # 'user_other':'',\n 'start': '0', # 魔法立即生效\n 'hours': '24', # 魔法有效期24小时\n 'promotion': '8', # 魔法类型为其他\n 'ur': '1.00', # 上传比率\n 'dr': '0.00', # 下载比率\n 'comment': '' # 评论\n }\n headers = {\n 'Referer': f'https://u2.dmhy.org/promotion.php?action=magic&torrent={torrent_id}',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',\n 'cookie': cookie\n }\n\n f = requests.post(\n f'https://u2.dmhy.org/promotion.php?action=magic&torrent={torrent_id}', data=data, headers=headers)\n status_code = f.status_code\n if status_code == 200:\n print(f'ID:{torrent_id} 成功施加马猴 (')\n else:\n print(f'ID:{torrent_id} 错误,code.{status_code}')\n\n\nif __name__ == \"__main__\":\n tlist()\n","sub_path":"U2/u2_auto_free.py","file_name":"u2_auto_free.py","file_ext":"py","file_size_in_byte":4155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"404179104","text":"#!/usr/bin/env python3\nimport argparse\nfrom sys import argv, exit as sysexit, platform\nimport os\nfrom os.path import expanduser, join as pathjoin, isdir, splitext\nfrom os.path import basename, dirname, abspath\nimport log\nimport webutil\nimport bingwallpaper\nimport record\nimport setter\nimport sched\nimport time\n\nNAME = 'pybingwallpaper'\nREV = '1.3.0'\nLINK = 'https://github.com/genzj/pybingwallpaper'\nHISTORY_FILE = pathjoin(expanduser('~'), 'bing-wallpaper-history.json')\n\n_logger = log.getChild('main')\n\ndef load_setters():\n if platform == 'win32':\n return ['no', 'win']\n else:\n return ['no', 'gnome3', 'gnome2']\n\ndef parseargs(args):\n setters = load_setters()\n parser = argparse.ArgumentParser(prog=NAME,\n description='Download the wallpaper offered by Bing.com '\n +'and set it current wallpaper background.')\n parser.add_argument('-v', '--version', action='version',\n version='%(prog)s-{} ({})'.format(REV, LINK),\n help='show version information')\n parser.add_argument('-b', '--background', default=False,\n action='store_true',\n help='''work in background (daemon mode) and check\n wallpaper periodically (interval can be set by --interval).''')\n parser.add_argument('-c', '--country', default=None,\n choices=('au', 'ca', 'cn', 'de', 'fr', 'jp', 'nz', 'us', 'uk'), \n help='''select country code sent to bing.com.\n bing.com in different countries may show different\n backgrounds. Note: only China(cn), Netherland(nz) and USA(us) have\n high resolution (1920x1200) wallpapers; the rest offer 1366x768 only.''')\n parser.add_argument('-d', '--debug', default=0,\n action='count',\n help='''enable debug outputs. \n The more --debug the more detailed the log will be''')\n parser.add_argument('-f', '--force', default=False,\n action='store_true',\n help='''obsolete since 1.3.0''')\n parser.add_argument('-i', '--interval', type=int, default=2,\n help='''interval between each two wallpaper checkings \n in unit of hours. applicable only in `background` mode.\n 2 hours by default.''')\n parser.add_argument('-k', '--keep-file-name', default=False,\n action='store_true',\n help='''keep the original filename. By default\n downloaded file will be renamed as 'wallpaper.jpg'.\n Keep file name will retain all downloaded photos\n ''')\n parser.add_argument('-m', '--size-mode', default='prefer',\n choices=('prefer', 'insist', 'never'),\n help='''set selecting strategy when wallpapers in different \n size are available (normally 1920x1200 and 1366x768).\n `prefer` (default) uses high resolution if it's \n available, otherwise downloads normal resolution;\n `insist` always use high resolution and ignore \n other pictures (Note: some countries have only\n normal size wallpapers, if `insist` is adopted\n with those sites, no wallpaper can be downloaded,\n see `--country` for more);\n `never` always use normal resolution.'''\n )\n parser.add_argument('-o','--offset', type=int, default='0',\n help='''start downloading from the photo of 'N' days ago.\n specify 0 to download photo of today.''')\n parser.add_argument('--persistence', type=int, default='3',\n help='''obsolete since 1.3.0''')\n parser.add_argument('--redownload', default=False,\n action='store_true',\n help='''do not check history records. Download\n must be done. downloaded picture will still\n be recorded in history file.\n ''')\n parser.add_argument('-s', '--setter', choices=setters,\n default=setters[1],\n help='''specify interface to be called for\n setting wallpaper. 'no'\n indicates downloading-only; 'gnome2/3'\n are only for Linux with gnome; 'win' is\n for Windows only. Customized setter can\n be added as dev doc described. Default: {}\n '''.format(setters[1]))\n parser.add_argument('--setter-args', default=[], action='append',\n help='''arguments for external setters''')\n parser.add_argument('-t', '--output-folder',\n default=pathjoin(expanduser('~'), 'MyBingWallpapers'),\n help='''specify the folder to store photos.\n Use '~/MyBingWallpapers' folder in Linux, \n 'C:/Documents and Settings//MyBingWallpapers \n in Windows XP or 'C:/Users//MyBingWallpapers' \n in Windows 7 by default\n ''')\n config = parser.parse_args(args)\n config.setter_args = ','.join(config.setter_args).split(',')\n return config\n\ndef prepare_output_dir(d):\n os.makedirs(d, exist_ok=True)\n if isdir(d):\n return True\n else:\n _logger.critical('can not create output folder %s', d)\n\ndef download_wallpaper(config):\n idx = config.offset\n s = bingwallpaper.BingWallpaperPage(idx, \n country_code = config.country,\n high_resolution = bingwallpaper.HighResolutionSetting.getByName(\n config.size_mode\n )\n )\n\n _logger.debug(repr(s))\n s.load()\n _logger.log(log.PAGEDUMP, str(s))\n if not s.loaded():\n _logger.fatal('can not load url %s. aborting...', s.url)\n return None\n for wplink, info in s.image_links():\n if wplink:\n outfile = get_output_filename(config, wplink)\n rec = record.default_manager.get(wplink, None)\n\n if rec and outfile == rec['local_file']:\n if not config.redownload:\n _logger.info('file has been downloaded before, exit')\n return None\n else:\n _logger.info('file has been downloaded before, redownload it')\n\n _logger.info('download photo of \"%s\"', info)\n picture_content = webutil.loadurl(wplink)\n if picture_content:\n with open(outfile, 'wb') as of:\n of.write(picture_content)\n _logger.info('file saved %s', outfile)\n r = record.DownloadRecord(wplink, outfile)\n return r\n _logger.debug('no wallpaper, try next')\n \n if s.filtered > 0:\n _logger.info('%d picture(s) filtered, try again with -f option if you want them',\n s.filtered)\n _logger.info('bad luck, no wallpaper today:(')\n return None\n\ndef get_output_filename(config, link):\n filename = basename(link)\n if not config.keep_file_name:\n filename = 'wallpaper{}'.format(splitext(filename)[1])\n return pathjoin(config.output_folder, filename)\n\ndef load_history():\n try:\n f = open(HISTORY_FILE, 'r')\n except FileNotFoundError:\n _logger.info('{} not found, ignore download history'.format(HISTORY_FILE)) \n except Exception:\n _logger.warning('error occurs when recover downloading history', exc_info=1)\n else:\n record.default_manager.load(f)\n f.close()\n\ndef save_history(r, keepold=False):\n if not keepold:\n record.default_manager.clear()\n record.default_manager.add(r)\n try:\n f = open(HISTORY_FILE, 'w')\n f.truncate(0)\n except Exception:\n _logger.warning('error occurs when store downloading history',\n exc_info=1)\n else:\n record.default_manager.save(f)\n f.close()\n\ndef set_debug_details(level):\n if not level:\n l = log.INFO\n elif level == 1:\n l = log.DEBUG\n elif level >= 2:\n l = log.PAGEDUMP\n log.setDebugLevel(l)\n\ndef main(config, daemon=None):\n if daemon: _logger.info('daemon %s triggers an update', str(daemon))\n setter.load_ext_setters(dirname(abspath(argv[0])))\n\n prepare_output_dir(config.output_folder)\n\n load_history()\n filerecord = download_wallpaper(config)\n\n if filerecord:\n save_history(filerecord)\n if not filerecord or config.setter == 'no':\n _logger.info('nothing to set')\n else:\n s = setter.get(config.setter)()\n _logger.info('setting wallpaper %s', filerecord['local_file'])\n s.set(filerecord['local_file'], config.setter_args)\n _logger.info('all done. enjoy your new wallpaper')\n\n if daemon: schedule_next_poll(config, daemon)\n\ndef schedule_next_poll(config, daemon):\n if config.background and daemon:\n _logger.debug('schedule next running in %d seconds', config.interval*3600)\n daemon.enter(config.interval*3600, 1, main, (config, daemon))\n elif not config.background:\n _logger.error('not in daemon mode')\n elif not daemon:\n _logger.error('no scheduler')\n\ndef start_daemon(config):\n daemon = sched.scheduler()\n \n main(config, daemon)\n _logger.info('daemon %s is running', str(daemon))\n daemon.run()\n _logger.info('daemon %s exited', str(daemon))\n\nif __name__ == '__main__':\n config = parseargs(argv[1:])\n set_debug_details(config.debug)\n _logger.debug(config)\n if config.background:\n start_daemon(config)\n else:\n main(config, None)\n sysexit(0)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"650866797","text":"from flask import request\n\nfrom app.settings import ROUTE_PREFIX\n\n# Definition of the allowed domains for CORS implementation in ../app/__init.py__\nALLOWED_DOMAINS = [\n r'.*\\.geo\\.admin\\.ch',\n r'.*bgdi\\.ch',\n r'.*\\.swisstopo\\.cloud',\n]\n\nALLOWED_DOMAINS_PATTERN = '({})'.format('|'.join(ALLOWED_DOMAINS))\n\n\ndef get_base_url():\n \"\"\"\n Generate the base URL for this service (the root endpoint at which this service is currently\n served). Useful if you want to generate URLs that points to any possible endpoint of this\n service without having to decipher where the service is hosted etc...\n\n Returns:\n The base endpoint for this service, where it is currently being served (or accessed)\n \"\"\"\n # we need to remove either the trailing slash of request.host_url\n # or the prefix slash of ROUTE_PREFIX (otherwise there are two slashes in between)\n return f\"{request.host_url}{ROUTE_PREFIX[1:]}\"\n","sub_path":"app/helpers/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"180297314","text":"#!/usr/bin/python3.7\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2021 桜火, Inc. All Rights Reserved \n#\n# @Time : 2021/4/26 21:35\n# @Author : 桜火\n# @Email : xie@loli.fit\n# @File : aba.py\n# @Software: PyCharm\nimport json\nfrom vika import Vika\nimport os\njson_file = open(\"/home/runner/work/_temp/_github_workflow/event.json\",mode=\"r\")\njson_file = json_file.read()\nvika_token = os.environ[\"VKTOKEN\"]\nvika_url = os.environ[\"VKURL\"]\nenv = json.loads(json_file)\nvika = Vika(vika_token)\n# 通过 datasheetId 来指定要从哪张维格表操作数据。\ndatasheet = vika.datasheet(vika_url, field_key=\"id\")\nrow = datasheet.records.create({\n \"fldp3Jyag9dcT\": str(env[\"commits\"][0][\"id\"]),\n \"fldIilczY4AtL\": env[\"repository\"][\"name\"],\n \"fld4CxF56Aiqg\": env[\"repository\"][\"description\"],\n \"fldcNKW9tOQob\": env[\"commits\"][0][\"author\"][\"name\"],\n \"fldGoBim2N4ru\": env[\"commits\"][0][\"author\"][\"username\"],\n \"fldoDfcbS2FZT\": env[\"commits\"][0][\"author\"][\"email\"],\n \"fldSMyuxmszuo\": env[\"repository\"][\"language\"],\n \"fldUJsyEaYrET\": env[\"commits\"][0][\"message\"],\n \"fldDPC0Cjm6W3\": env[\"commits\"][0][\"timestamp\"],\n \"fldhpQbZKKfaW\": env[\"repository\"][\"master_branch\"],\n \"fld3fYMdpSROJ\": env[\"repository\"][\"html_url\"],\n})\nprint(row)\nprint(\"运行成功\")\n","sub_path":"autoRun/weige.py","file_name":"weige.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"3733614","text":"# trivia data for the red-green game, to be imported by rg.cgi\n# each question has a key that is the question number\n# and value that is a list with the question and answer data\n# that is: tdata[qnum][0] = question text\n# tdata[qnum][1] = green answer\n# tdata[qnum][2] = red answer\n# tdata[qnum][3] = both answer\n# tdata[qnum][4] = answer code\n# tdata[qnum][5] = answer text\n\n# the question text and answer text may include format\n# strings to reference images, like so: %(image_url)s\n\ntdata = {\n1: [\n \"\"\"\n What company launched the rocket shown here?\n

\n \n \"\"\",\n \"SpaceX\",\n \"Blue Origin\",\n \"\",\n \"green\",\n \"\"\"\n There's a logo on the side of the rocket.\n \"\"\"\n ],\n2: [\n \"\"\"\n What is the the airspeed velocity of an unladen swallow?\n \"\"\",\n \"26 mph\",\n \"I don't know that!\",\n \"\",\n \"red|green\",\n \"\"\"\n Either answer is OK.\n \"\"\"\n ],\n3: [\n \"\"\"\n What is the name of the organization that Linus Torvalds works for?\n \"\"\",\n \"The Linus Foundation\",\n \"Linaro\",\n \"something else\",\n \"both\",\n \"\"\"\n Linus is employed by the Linux Foundation
\n Not the Linus Foundation!\n \"\"\"\n ],\n}\n","sub_path":"rgdata/trivia.py","file_name":"trivia.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"585141668","text":"# -*- coding: utf-8 -*-\r\nimport ast\r\nimport sys\r\nimport select\r\nfrom threading import Thread\r\nfrom math import sqrt\r\n\r\nKEYWORDS = {\"z\":\"UP\", \"q\":\"LEFT\", \"s\":\"DOWN\", \"d\":\"RIGHT\", \"e\":\"EXE\", \"\\x1b\":\"ESC\", \"i\":\"i\"}\r\n\r\ndef interact(dest, c, *arg_func, **func):\r\n global KEYWORDS\r\n # arg_func est la liste des fonctions qui sont appellees par plusieurs touches et/ou qui ont besoin\r\n # de la touche appuyée en argument;\r\n # Exemple: [((\"z\", \"s\"), move_vertically), ((\"q\", \"d\"), move_horizontally)]\r\n # NB: on peut executer plusieurs fonctions pour les mêmes touches en donnant\r\n # une liste ou un tuple de focntions à la place d'une simple fonction. Dans\r\n # ce cas, les fonctions sont éxecutées dans l'ordre donné.\r\n\r\n # func est un dictionnaire crée à partir des paramètres, il prend le nom du paramètre comme touche à appuyer\r\n # et comme valeur la fonction associée\r\n # Exemple: interact(dest, m=move) executera la fonction \"move\" si on appuie sur \"m\"\r\n\r\n if c in KEYWORDS.keys():\r\n c = KEYWORDS[c]\r\n else:\r\n # La touche n'est pas définie dans le jeu\r\n return None # quitte interact rapidement, pour éviter de faire la suite inutile\r\n for keys, f in arg_func:\r\n if c in keys:\r\n if type(f) in (tuple, list):\r\n return [function(dest, c) for function in f]\r\n else:\r\n return f(dest, c)\r\n if c in func.keys():\r\n return func[c](dest)\r\n\r\ndef w(string, file=sys.stdout):\r\n file.write(string)\r\n\ndef xpath(element, path):\n assert isinstance(path, (str, list))\n #assert type(element) == type(ET.Element)\n if isinstance(path, str):\n lst_path = path.split(\"/\")\n else:\n lst_path = path\n\n if lst_path:\n if lst_path[0]:\n return xpath(element.find(lst_path.pop(0)), lst_path)\n else:\n lst_path.pop(0)\n return xpath(element, lst_path)\n else:\n return element\n\ndef str_to_tuple(string, max_len_str=None):\n if not string:\n return None\n\n lst = []\n for elt in string.split(','):\n try:\n lst.append(ast.literal_eval(elt.strip()))\n except:\n if not max_len_str:\n lst.append(elt)\n else:\n lst.append(elt[len(elt)-max_len_str:len(elt)])\n if len(lst) == 1:\n return lst[0]\n else:\n return tuple(lst)\n\ndef reformat(string):\n format_lst = [(\"\", \"\\033[1m\"), (\"\", \"\\033[3m\"), \\\n (\"\", \"\\033[7m\"), (\"\", \"\\033[4m\"), \\\n (\"\", \"\\033[9m\"), (\"\", \"\\033[0m\"), (\"\", \"⇲\") ]\n for old, new in format_lst:\n string = string.replace(old, new)\n return string\n\n# def isNormalString(string):\n# for c in string:\n# if not (c.isalnum() or c in \"\"\".:;\"'?!-_() éèàùçêôî\"\"\"):\n# return False\n# return True\n\nclass Read(Thread):\n \"\"\" Méthode permettant de récupérer les entrées clavier en parallèle du jeu.\r\nCette mathode évite le remplissage de la pile dans le cas d'un appui long sur\r\nune touche. Aussi, lors d'une demande de lecture est faite, seule la dernière\r\ntouche est renvoyée. De ce fait, les ordres sont instantanés.\"\"\"\r\n\r\n def __init__(self):\r\n Thread.__init__(self)\r\n self.val = None\r\n self.RUN = True\r\n\r\n def run(self):\r\n while self.RUN:\r\n c = sys.stdin.read(1)\r\n if c:\r\n self.val = c\r\n\r\n def stop(self):\r\n self.RUN = False\r\n\r\n def read(self):\r\n if self.val:\r\n result = self.val\r\n self.val = None\r\n else:\r\n result = \"\"\r\n return result\r\n\r\nr = None\r\n\r\ndef startReadingData():\r\n global r\r\n r = Read()\r\n r.start()\r\n\r\ndef stopReadingData():\r\n global r\r\n r.stop()\r\n\r\ndef readData():\r\n global r\r\n return r.read()\r\n\r\ndef norm(u):\r\n return sqrt(sum([c**2 for c in u]))\r\n\r\ndef scal(u, v):\r\n return sum([u[i]*v[i] for i in range(len(u))])\r\n\r\ndef clear():\r\n \"\"\"Clears the whole screen with the preset color\"\"\"\r\n w(\"\\033[H\\033[2J\")\r\n\r\ndef clear_line():\r\n \"\"\"Clears the current line with the preset color\"\"\"\r\n w(\"\\033[2K\")\r\n\r\ndef hide_cursor():\r\n \"\"\"Hides the cursor\"\"\"\r\n w(\"\\033[?25l\")\r\n\r\ndef show_cursor():\r\n \"\"\"Shows the hidden cursor\"\"\"\r\n w(\"\\033[?25h\")\r\n\r\ndef reset_attributes():\r\n \"\"\"All attributes off\"\"\"\r\n w(\"\\033[0m\")\r\n\r\ndef bold():\r\n \"\"\"Writes next texts in bold\"\"\"\r\n w(\"\\033[1m\")\r\n\r\ndef italic():\r\n \"\"\"Writes next texts in italics\"\"\"\r\n w(\"\\033[3m\")\r\n\r\ndef underline():\r\n \"\"\"Writes next texts, underlined\"\"\"\r\n w(\"\\033[4m\")\r\n\r\ndef highlight():\r\n \"\"\"Writes next texts, highlighted\"\"\"\r\n w(\"\\033[7m\")\r\n\r\ndef darker_font():\r\n \"\"\"Writes next texts with a darker font\"\"\"\r\n w(\"\\033[2m\")\r\n\r\ndef invisible_font():\r\n \"\"\"Writes next texts with an invisible font\"\"\"\r\n w(\"\\033[8m\")\r\n\r\ndef crossed():\r\n \"\"\"Writes next texts, crossed\"\"\"\r\n w(\"\\033[9m\")\r\n\r\ndef home():\r\n \"\"\"Sets the cursor at his \"home\" position.\r\nthe default home position is the upper left corner\"\"\"\r\n w(\"\\033[H\")\r\n\r\ndef goto(line, column=None):\r\n \"\"\"Sets the cursor to the coordinates (column, line).\r\nThe default column value is the current column.\r\nWarning: The origin is (1, 1), not (0, 0).\"\"\"\r\n\r\n assert column is None or isinstance(column, int)\r\n assert isinstance(line, int)\r\n if not column:\r\n w(\"\\033[{y}H\".format(y=line))\r\n else:\r\n w(\"\\033[{y};{x}H\".format(x=column, y=line))\r\n\r\ndef save():\r\n \"\"\"Saves the current cursor position.\r\nYou can move the cursor to the saved cursor position by using the Restore Cursor\r\nPosition sequence.\"\"\"\r\n w(\"\\033[s\")\r\n\r\ndef restore():\r\n \"\"\"Sets the cursor to the position stored by the Save Cursor Position\r\nsequence.\"\"\"\r\n w(\"\\033[u\")\r\n\r\ndef up(n=1):\r\n \"\"\"Moves the cursor up by the specified number of lines n without changing\r\ncolumns.\r\nIf the cursor is already on the top line, ANSI.SYS ignores this sequence.\"\"\"\r\n w(\"\\033[{0}A\".format(n))\r\n\r\ndef down(n=1):\r\n \"\"\"Moves the cursor down by the specified number of lines n without changing\r\ncolumns.\r\nIf the cursor is already on the bottom line, ANSI.SYS ignores this sequence.\"\"\"\r\n w(\"\\033[{0}B\".format(n))\r\n\r\ndef right(n=1):\r\n \"\"\"Moves the cursor forward by the specified number of columns n without\r\nchanging lines.\r\nIf the cursor is already in the rightmost column, ANSI.SYS ignores this\r\nsequence.\"\"\"\r\n w(\"\\033[{0}C\".format(n))\r\n\r\ndef left(n=1):\r\n \"\"\"Moves the cursor back by the specified number of columns without\r\nchanging lines.\r\nIf the cursor is already in the leftmost column, ANSI.SYS ignores this sequence.\"\"\"\r\n w(\"\\033[{0}D\".format(n))\r\n\r\ndef color_seq(fontcolor=None, bgcolor=None):\r\n \"\"\"Return the str-sequence which sets the cursor to the specified colors.\r\nThe color can be a number between 0 and 255, a (r, g, b) tuple or a str as\r\n\"black\", \"red\", \"green\", \"yellow\", \"blue\", \"cyan\", or \"white\".\"\"\"\r\n if not (fontcolor is None or isinstance(fontcolor, (str, int, tuple))):\r\n raise TypeError(\"type {0} for {1} is not allowed\".format(type(fontcolor), fontcolor))\r\n if not (bgcolor is None or isinstance(bgcolor, (str, int, tuple))):\r\n raise TypeError(\"type {0} for {1} is not allowed\".format(type(bgcolor), bgcolor))\r\n transcolor = {\"black\":0,\r\n \"red\":1,\r\n \"green\":2,\r\n \"yellow\":3,\r\n \"blue\":4,\r\n \"purple\":5,\r\n \"cyan\":6,\r\n \"white\":7}\r\n result = \"\"\r\n for color in (fontcolor, bgcolor):\r\n if color is not None:\r\n if isinstance(color, str):\r\n if color not in transcolor.keys():\r\n if color[0] == \"\\\\\":\r\n color = \"\\\\\" + color\r\n raise ValueError(\"The str-sequence '{0}' doesn't match to any color\".format(color))\r\n else:\r\n color = transcolor[color]\r\n if isinstance(color, int):\r\n if color not in range(256):\r\n raise ValueError(\"The int {0} doesn't match to any color\".format(color))\r\n result += \"\\033[{mode}8;5;{c}m\".format(c=color, mode=(3+int(color==bgcolor)))\r\n elif isinstance(color, tuple):\r\n if len(color) != 3:\r\n raise ValueError(\"The tuple {0} doesn't have the good length. Expected 3.\".format(color))\r\n else:\r\n for c in color:\r\n if not c in range(256):\r\n raise ValueError(\"The int {0} doesn't match to any color\".format(c))\r\n result += \"\\033[{mode}8;2;{r};{g};{b}m\".format(mode=(3+int(color==bgcolor)), r=color[0], g=color[1], b=color[2])\r\n\r\n return result\r\n\r\ndef color(fontcolor=None, bgcolor=None):\r\n \"\"\"sets the cursor to the specified colors.\r\nThe color can be a number between 0 and 255 or a str as \"black\", \"red\", \"green\",\r\n\"yellow\", \"blue\", \"cyan\", or \"white\".\"\"\"\r\n w(color_seq(fontcolor, bgcolor))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n ctype = int(str(input(\"255 colors -> 1, 16M colors -> 2: \")))\r\n assert ctype in (1, 2)\r\n\r\n if ctype == 1:\r\n mode = int(str(input(\"fontcolor -> 1, background -> 2: \")))\r\n assert mode in (1, 2)\r\n mode += 2\r\n\r\n reset_attributes(); home(); clear()\r\n bold(); underline()\r\n w(\"Standart colors :\")\r\n reset_attributes()\r\n goto(1, 25)\r\n for r in range(0, 8):\r\n if mode == 3:\r\n color(fontcolor=r)\r\n else:\r\n color(bgcolor=r)\r\n w(\" {r}\".format(r=r) + \" \"*(4-len(str(r))))\r\n\r\n goto(3, 1)\r\n reset_attributes(); bold(); underline()\r\n w(\"high_intensity colors :\")\r\n reset_attributes()\r\n goto(3, 25)\r\n for r in range(8, 16):\r\n if mode == 3:\r\n color(fontcolor=r)\r\n else:\r\n color(bgcolor=r)\r\n w(\" {r}\".format(r=r) + \" \"*(4-len(str(r))))\r\n\r\n goto(5, 1)\r\n reset_attributes(); bold(); underline()\r\n w(\"216 colors :\")\r\n reset_attributes()\r\n goto(7, 1)\r\n for r in range(16, 232):\r\n if mode == 3:\r\n color(fontcolor=r)\r\n else:\r\n color(fontcolor=238, bgcolor=r)\r\n w(\" {r}\".format(r=r) + \" \"*(4-len(str(r))))\r\n cols = 36\r\n j = (r-15)//cols+7\r\n if (r-15)%cols == 0:\r\n w(u\"\\u001b[{j};1H\".format(j=j))\r\n\r\n\r\n goto(j+1, 1)\r\n reset_attributes(); bold(); underline()\r\n w(\"Grayscale colors:\")\r\n reset_attributes()\r\n goto(j+1, 25)\r\n if mode == 4:\r\n w(u\"\\033[31;5m\")\r\n for r in range(232, 256):\r\n if mode == 3:\r\n color(fontcolor=r)\r\n else:\r\n color(bgcolor=r)\r\n w(\" {r}\".format(r=r) + \" \"*(4-len(str(r))))\r\n\r\n reset_attributes()\r\n goto(j+3, 1)\r\n else:\r\n r = int(str(input(\"red: \")))\r\n assert r in range(256)\r\n g = int(str(input(\"green: \")))\r\n assert r in range(256)\r\n b = int(str(input(\"blue: \")))\r\n assert r in range(256)\r\n color(None, (r, g, b))\r\n home(); clear(); reset_attributes()\r\n","sub_path":"Knil Dungeon (prototype 1)/Tools.py","file_name":"Tools.py","file_ext":"py","file_size_in_byte":11347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"496843174","text":"import ipaddress\nimport re\n\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import RegexValidator, URLValidator\nfrom django.utils.translation import gettext as _\n\nfrom .utils.regex import Regex\n\nregex = Regex()\n\n# ------- Messages -------\nINVALID_ASN = _('Enter a valid AS number.')\nINVALID_CNPJ = _('Enter a valid CNPJ number.')\nINVALID_IPV4_NETWORK = _('Enter a valid IPv4 network.')\nINVALID_IPV6_NETWORK = _('Enter a valid IPv6 network.')\nINVALID_IPV46_NETWORK = _('Enter a valid IPv4 or IPv6 network.')\nINVALID_SWITCH_MODEL = _(\n 'SwitchModel.model format not compatible with SwitchModel.vendor.')\nONLY_LOWERCASE = _('Allowed only ASCII lowercase characters.')\nUSUAL_IX_CODE = _('Allowed only two-four alphabetic lowercase characters')\nUSUAL_IX_FULLNAME = _(\n 'Allowed only Name of city followed by the state '\n 'abbreviation separated by -')\nUSUAL_IX_SHORTNAME = (\n 'Allowed only two groups of 3-13 and 2-2 alphabetic lowercase characters '\n 'separated by dot')\nUSUAL_MAC_ADDRESS = _(\n 'Allowed only one of these: '\n '1) Six groups of two hexadecimal digits. '\n '2) Three groups of four hexadecimal digits. '\n '3) Twelve hexadecimal digits. '\n '(1) left zeros could be omitted. '\n '(1) and (2) could be separated by colons, dots or hyphens.')\nUSUAL_PIX_CODE = _('Allowed only three-max_field_length characters '\n 'with first uppercase')\nINVALID_DOWNLINK_NAME = _(\n 'DownlinkChannel name doesn\\'t match with switch model.')\nINVALID_UPLINK_NAME = _(\n 'UplinkChannel name doesn\\'t match with switch model.')\nINVALID_CORE_NAME = _(\n 'CoreChannel name doesn\\'t match with switch model.')\nINVALID_CUSTOMER_NAME = _(\n 'CustomerChannel name doesn\\'t match with switch model.')\nUNRECOGNIZED_CHANNEL_TYPE_VENDOR = _('Unrecognized channel_type/vendor values')\nINVALID_CHANNEL_TYPE_OR_VENDOR = _('Invalid value of channel_type or vendor')\nRESERVED_IP = _('The IP {} is reserved')\n# ------- Regex -------\nCNPJ = re.compile(r'^{0}$'.format(regex.cnpj))\nIX_CODE = re.compile(r'^{0}$'.format(regex.ix_code))\nIX_FULLNAME = re.compile(regex.ix_fullname)\nIX_SHORTNAME = re.compile(regex.ix_shortname)\nLOWERCASE = re.compile(r'^[a-z]+$')\nPIX_CODE = re.compile(regex.pix_code)\nEXTREME_MODELS = re.compile(r'^{0}$'.format(regex.extreme))\nCISCO_MODELS = re.compile(r'^{0}$'.format(regex.cisco))\nBROCADE_MODELS = re.compile(r'^{0}$'.format(regex.brocade))\nJUNIPER_MODELS = re.compile(r'^{0}$'.format(regex.juniper))\nDOWNLINK_BROCADE = re.compile(r'^dl-{0}$'.format(regex.channel_name_brocade))\nDOWNLINK_CISCO = re.compile(r'^dl-{0}$'.format(regex.channel_name_cisco))\nDOWNLINK_EXTREME = re.compile(r'^dl-{0}$'.format(regex.channel_name_extreme))\nDOWNLINK_JUNIPER = re.compile(r'^dl-{0}$'.format(regex.channel_name_juniper))\nMAC_ADDRESS = re.compile(\n '{}{}{}'.format(r'^(', '|'.join(regex._MAC_PATTERN_JOIN), r')$'))\nUPLINK_BROCADE = re.compile(r'^ul-{0}$'.format(regex.channel_name_brocade))\nUPLINK_CISCO = re.compile(r'^ul-{0}$'.format(regex.channel_name_cisco))\nUPLINK_EXTREME = re.compile(r'^ul-{0}$'.format(regex.channel_name_extreme))\nUPLINK_JUNIPER = re.compile(r'^ul-{0}$'.format(regex.channel_name_juniper))\nCORE_BROCADE = re.compile(r'^cc-{0}$'.format(regex.channel_name_brocade))\nCORE_CISCO = re.compile(r'^cc-{0}$'.format(regex.channel_name_cisco))\nCORE_EXTREME = re.compile(r'^cc-{0}$'.format(regex.channel_name_extreme))\nCORE_JUNIPER = re.compile(r'^cc-{0}$'.format(regex.channel_name_juniper))\nCUSTOMER_BROCADE = re.compile(r'^ct-{0}$'.format(regex.channel_name_brocade))\nCUSTOMER_CISCO = re.compile(r'^ct-{0}$'.format(regex.channel_name_cisco))\nCUSTOMER_EXTREME = re.compile(r'^ct-{0}$'.format(regex.channel_name_extreme))\nCUSTOMER_JUNIPER = re.compile(r'^ct-{0}$'.format(regex.channel_name_juniper))\n\n# ------- Validation Dicts -------\nCHANNEL_DICT = {\n 'CustomerChannel': {\n 'BROCADE': RegexValidator(CUSTOMER_BROCADE, INVALID_CUSTOMER_NAME),\n 'CISCO': RegexValidator(CUSTOMER_CISCO, INVALID_CUSTOMER_NAME),\n 'EXTREME': RegexValidator(CUSTOMER_EXTREME, INVALID_CUSTOMER_NAME),\n 'JUNIPER': RegexValidator(CUSTOMER_JUNIPER, INVALID_CUSTOMER_NAME)\n },\n 'CoreChannel': {\n 'BROCADE': RegexValidator(CORE_BROCADE, INVALID_CORE_NAME),\n 'CISCO': RegexValidator(CORE_CISCO, INVALID_CORE_NAME),\n 'EXTREME': RegexValidator(CORE_EXTREME, INVALID_CORE_NAME),\n 'JUNIPER': RegexValidator(CORE_JUNIPER, INVALID_CORE_NAME)\n },\n 'DownlinkChannel': {\n 'BROCADE': RegexValidator(DOWNLINK_BROCADE, INVALID_DOWNLINK_NAME),\n 'CISCO': RegexValidator(DOWNLINK_CISCO, INVALID_DOWNLINK_NAME),\n 'EXTREME': RegexValidator(DOWNLINK_EXTREME, INVALID_DOWNLINK_NAME),\n 'JUNIPER': RegexValidator(DOWNLINK_JUNIPER, INVALID_DOWNLINK_NAME)\n },\n 'UplinkChannel': {\n 'BROCADE': RegexValidator(UPLINK_BROCADE, INVALID_UPLINK_NAME),\n 'CISCO': RegexValidator(UPLINK_CISCO, INVALID_UPLINK_NAME),\n 'EXTREME': RegexValidator(UPLINK_EXTREME, INVALID_UPLINK_NAME),\n 'JUNIPER': RegexValidator(UPLINK_JUNIPER, INVALID_UPLINK_NAME)\n },\n 'TranslationChannel': {\n 'BROCADE': NotImplemented,\n 'CISCO': NotImplemented,\n 'EXTREME': NotImplemented,\n 'JUNIPER': NotImplemented\n }\n}\n\n\n# ------- Validation Functions -------\ndef validate_as_number(number):\n \"\"\"ASN validator.\"\"\"\n\n # 16-bit range list\n s_bit_reserved_range = list(range(64496, 64512))\n s_bit_reserved_range.extend(list(range(64513, 65536)))\n\n # 32-bit range list\n t_bit_reserved_range = list(range(65536, 65551))\n\n if number < 1 or \\\n number in s_bit_reserved_range or \\\n number in t_bit_reserved_range or \\\n number >= 4200000000:\n raise ValidationError(INVALID_ASN)\n\n\ndef validate_cnpj(value):\n validator = RegexValidator(\n regex=CNPJ,\n message=INVALID_CNPJ,\n code='invalid')\n\n validator(value)\n\n\ndef validate_ipv4_network(value):\n try:\n ipaddress.IPv4Network(value, False)\n except (ipaddress.AddressValueError,\n ipaddress.NetmaskValueError,\n ValueError):\n raise ValidationError(INVALID_IPV4_NETWORK, code='invalid')\n\n\ndef validate_ipv46_network(value):\n try:\n ipaddress.ip_network(value, False)\n except (ipaddress.AddressValueError,\n ipaddress.NetmaskValueError,\n ValueError):\n raise ValidationError(INVALID_IPV46_NETWORK, code='invalid')\n\n\ndef validate_ipv6_network(value):\n try:\n ipaddress.IPv6Network(value, False)\n except (ipaddress.AddressValueError,\n ipaddress.NetmaskValueError,\n ValueError):\n raise ValidationError(INVALID_IPV6_NETWORK, code='invalid')\n\n\ndef validate_ix_code(value):\n validator = RegexValidator(IX_CODE, USUAL_IX_CODE)\n validator(value)\n\n\ndef validate_ix_fullname(value):\n validator = RegexValidator(IX_FULLNAME, USUAL_IX_FULLNAME)\n validator(value)\n\n\ndef validate_ix_shortname(value):\n validator = RegexValidator(IX_SHORTNAME, USUAL_IX_SHORTNAME)\n validator(value)\n\n\ndef validate_mac_address(value):\n \"\"\"Usual lowercase MAC address validator.\"\"\"\n validator = RegexValidator(MAC_ADDRESS, USUAL_MAC_ADDRESS)\n validator(value)\n\n\ndef validate_name_format(value):\n if value.count('{') > 1 or value.count('}') > 1:\n raise ValidationError(\n ('there is more than one { or } on name_format'))\n if value.count('{0}') == 0:\n raise ValidationError(_('name_format must contain \\{0\\}'))\n if value.format(12) != value.replace('{0}', '12'):\n raise ValidationError(_('name_format must contain \\{0\\}'))\n\n\ndef validate_only_lowercase(value):\n \"\"\"Only lowercase validator.\"\"\"\n validator = RegexValidator(LOWERCASE, ONLY_LOWERCASE)\n validator(value)\n\n\ndef validate_pix_code(value):\n valitador = RegexValidator(PIX_CODE, USUAL_PIX_CODE)\n valitador(value)\n\n\ndef validate_url_format(value):\n validator = URLValidator()\n validator(value)\n\n\ndef validate_switch_model(switch):\n if switch.vendor == 'EXTREME':\n validator = RegexValidator(EXTREME_MODELS, INVALID_SWITCH_MODEL)\n validator(switch.model)\n elif switch.vendor == 'CISCO':\n validator = RegexValidator(CISCO_MODELS, INVALID_SWITCH_MODEL)\n validator(switch.model)\n elif switch.vendor == 'JUNIPER':\n validator = RegexValidator(JUNIPER_MODELS, INVALID_SWITCH_MODEL)\n validator(switch.model)\n elif switch.vendor == 'BROCADE':\n validator = RegexValidator(BROCADE_MODELS, INVALID_SWITCH_MODEL)\n validator(switch.model)\n else:\n raise ValidationError(_('unrecognized switch model'))\n\n\ndef validate_channel_name(channel):\n channel_type = channel.__class__.__name__\n vendor = channel.channel_port.port_set.first().switch.model.vendor\n if (vendor and channel_type and\n channel_type in CHANNEL_DICT and\n vendor in CHANNEL_DICT[channel_type]):\n validator = CHANNEL_DICT[channel_type][vendor]\n if validator:\n validator(channel.name)\n else:\n raise ValidationError(UNRECOGNIZED_CHANNEL_TYPE_VENDOR)\n else:\n raise ValidationError(INVALID_CHANNEL_TYPE_OR_VENDOR)\n","sub_path":"ipaxi/ixbr_api/core/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":9242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63314166","text":"import os\nimport requests\nimport emailBase\nfrom bs4 import BeautifulSoup as BF\n\ndef checkGradeValidation(mGrade):\n templocation = mGrade.lower().find(\"<\")\n if templocation != -1:\n return mGrade[:templocation]\n\n return mGrade\n \ndef createInfoMsgToSend(elementList):\n\n # Create (If doesn't exist) message.txt or clean it to create a new message\n msgFile = open(\"message.txt\", \"w\")\n msgFile.write(\"New movies : \\n\")\n\n # Loop that add data on message.txt\n for anElementListM in elementList:\n\n # A attribute that contains name of movie\n nameOfMovie = anElementListM.findAll(\"a\", {\"class\": \"headinglink\"})[0]\n\n # IMG attribute that contains image of movie\n imageOfMovie = anElementListM.findAll(\"img\", {\"class\": \"lozad\"})[0].get('data-src')\n\n # DIV attribute that contains imdb grade (if doesn't show only subs4free grade)\n movieGradeAsHtml = str(anElementListM.findAll(\"div\", {\"class\": \"panel-heading-info\"}))\n # To check if grade exist \n locationOfGrade = movieGradeAsHtml.lower().find(\"imdb\")\n \n if locationOfGrade != -1:\n # Get only the grade\n gradeOfMovie = movieGradeAsHtml[locationOfGrade : locationOfGrade+9]\n \n msgFile.write(\"* Name: \" + nameOfMovie.text + \" || \" + checkGradeValidation(gradeOfMovie) + \" || \" + imageOfMovie + \"\\n\" )\n else: \n msgFile.write(\"* Name: \" + nameOfMovie.text + \" || \" + imageOfMovie)\n\n\n\ndef main():\n # main function\n\n # Set the url link\n urlMovies = 'https://www.subs4free.info/'\n\n # Set my-user-aget. If you dont know who is your 'User-aget', just google \"my user agent\" and it will show it first on result\n headers = {\n \"User-Agent\": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'}\n\n # Get the whole page content\n pageMovies = requests.get(urlMovies, headers=headers)\n\n # Convert page to lxml\n soupMovies = BF(pageMovies.content, 'lxml')\n \n # DIV attribute that contains info for every movie\n elementListMovies = soupMovies.findAll(\"div\", {\"class\": \"movies-info\"})\n\n createInfoMsgToSend(elementListMovies)\n\n emailBase.main()\n\nif __name__ == \"__main__\":\n main()\n print(\"ok\")\n \n","sub_path":"movieWatchDog.py","file_name":"movieWatchDog.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"445051386","text":"#!/usr/bin/python3\nimport time\n# import threading\nimport math\n\nimport gym\nimport numpy as np\nfrom gym.spaces import Discrete\nfrom gym.utils import seeding\nimport rospy\nfrom gazebo_msgs.msg import ModelState\nfrom gazebo_msgs.srv import SetModelState\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Twist\nfrom gazebo_msgs.srv import GetModelState\nfrom std_srvs.srv import Empty\n# from gazebo_msgs.srv import GetModelStateResponse\n# from rosgraph_msgs.msg import Clock\n\nenable_correction = True\nac_num = 0\n\n\ndef set_gpw_num(num):\n global ac_num\n ac_num = num\n\n# 2.将reward进行分段设置\n# 3.修改action作用方式,(1)不能speed为持久状态,(2)使用某种移动作为action\n\n\n# 由于先前的写法,这里暂时只能单独写,而不能统一处理\ndef reset_node_init():\n pub = rospy.Publisher('/gazebo/set_model_state', ModelState, queue_size=1)\n\n new_obstacle_state = ModelState()\n new_obstacle_state.model_name = \"robot\"+str(ac_num)\n # cc_x = 0.0 # coordinate correction\n # cc_y = 0.0 # 使用其它的坐标方案\n\n if ac_num == 1:\n new_obstacle_state.pose.position.x = -1.0 # 1.0\n new_obstacle_state.pose.position.y = -4.0\n elif ac_num == 2:\n new_obstacle_state.pose.position.x = -5.0 # 1.0\n new_obstacle_state.pose.position.y = 5.0\n elif ac_num == 3:\n new_obstacle_state.pose.position.x = 2.0 # 1.0\n new_obstacle_state.pose.position.y = -3.0\n elif ac_num == 4:\n new_obstacle_state.pose.position.x = 5.0 # 1.0\n new_obstacle_state.pose.position.y = 5.0\n else:\n gym.logger.warn(\"Error ac_num !\")\n\n new_obstacle_state.pose.position.z = 0\n # 注意4元数的概念\n new_obstacle_state.pose.orientation.x = 0 # z与w 控制了水平朝向?\n new_obstacle_state.pose.orientation.y = 0\n new_obstacle_state.pose.orientation.z = 0\n new_obstacle_state.pose.orientation.w = 0\n\n new_obstacle_state.twist.linear.x = 0\n new_obstacle_state.twist.linear.y = 0\n new_obstacle_state.twist.linear.z = 0\n\n new_obstacle_state.twist.angular.x = 0\n new_obstacle_state.twist.angular.y = 0\n new_obstacle_state.twist.angular.z = 0\n\n new_obstacle_state.reference_frame = \"world\"\n\n return pub, new_obstacle_state\n\n\n# def correct_coordinate_func():\n# if enable_correction:\n# def this_func(input_value):\n# return abs(input_value)\n# else:\n# def this_func(input_value):\n# return input_value\n# return this_func\n\n\n# 没有0号robot\n# 有障碍物的空间\n# goal_sequence = [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)],\n# [(5.0, 5.0), (9.0, 5.0), (9.0, 1.0)]]\n\n# goal_sequence = [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)],\n# [(5.0, 5.0), (8.0, 7.0), (9.0, 1.0), (1.0, 8.9)]]\n#\n# initial_sequence = [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0, 0)],\n# [(2.1, 1.2), (7.0, 3.0), (5.0, 8.2), (1.0, 6.2)]\n# ]\n\n# # 由于计算距离与角度,所以状态中正负不重要\n# initial_sequence = [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)],\n# [(1.5, 5.0), (9.0, 1.0), (5.0, 6.0), (2.0, 8.5)],\n# [(2.0, -5.0), (8.5, -1.5), (5.0, -6.0), (2.0, -8.5)],\n# [(-1.5, -5.0), (-9.0, -1.0), (-5.0, -6.0), (-2.0, -8.5)],\n# [(-1.5, 5.0), (-9.0, 1.0), (-5.0, 6.0), (-2.0, 8.5)]]\n#\n# goal_sequence = [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)],\n# [(8.0, 8.0), (2.0, 1.0), (6.0, 3.0), (9.0, 9.0)],\n# [(8.0, -8.0), (2.0, -1.0), (6.0, -3.0), (9.0, -9.0)],\n# [(-8.0, -8.0), (-2.0, -1.0), (-6.0, -3.0), (-9.0, -9.0)],\n# [(-8.0, 8.0), (-2.0, 1.0), (-6.0, 3.0), (-9.0, 9.0)]]\n\n# 由于计算距离与角度,所以状态中正负不重要\n# for obstacle place, 多机器人障碍物 initial 并没有用到\ninitial_sequence = [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0), (0.0, 0.0)],\n [(1.5, 5.0), (9.0, 1.0), (5.0, 6.0), (2.0, 8.5)],\n [(2.0, -5.0), (8.5, -1.5), (5.0, -6.0), (2.0, -8.5)],\n [(-1.5, -5.0), (-9.0, -1.0), (-5.0, -6.0), (-2.0, -8.5)],\n [(-1.5, 5.0), (-9.0, 1.0), (-5.0, 6.0), (-2.0, 8.5)]]\n\ngoal_sequence = [[(0.0, 0.0), (0.0, 0.0), (0.0, 0.0)],\n [(-1.0, -8.0), (-9.0, -2.0), (-8.0, -8.0)],\n [(-1.0, 5.0), (-9.0, 9.0), (-8.0, 2.0)],\n [(5.0, -5.0), (9.0, -5.0), (2.0, -9.0)],\n [(9.0, 3.0), (1.0, 7.0), (9.0, 9.0)]]\n\n\nclass FourthRobGpw2(gym.Env):\n def __init__(self):\n rospy.init_node(\"rl_robot_node\"+str(ac_num))\n self.pub, self.reset_robot_state = reset_node_init()\n self.act_pub = rospy.Publisher('/robot'+str(ac_num)+'/pioneer/cmd_vel', Twist, queue_size=1)\n self.sub_name = '/robot' + str(ac_num) + '/laser/scan'\n self.laser_sub = rospy.Subscriber(self.sub_name, LaserScan, self.laser_callback, queue_size=1)\n # self.cc_func = correct_coordinate_func()\n # 数据已经离散化(不需要归一化吧?),进一步转换成整数, 线速度为第15个状态\n # self.observation_space = gym.spaces.Box(-10.0, 10.0, (15, ), dtype=np.dtype(np.float32))\n # if enable_correction:\n # self.observation_space = gym.spaces.Box(0, 100, (14,), dtype=np.dtype(np.int32)) # 整数版\n # else:\n # self.observation_space = gym.spaces.Box(-100, 100, (14, ), dtype=np.dtype(np.int32)) # 整数版\n # self.observation_space = gym.spaces.Box(0, 1, (14,), dtype=np.dtype(np.float32)) # normalization\n # self.observation_space = gym.spaces.Box(-10.0, 10.0, (4, ), dtype=np.dtype(np.float32))\n self.observation_space = gym.spaces.Box(0, 100, (12, ), dtype=np.dtype(np.int32))\n self.action_space = Discrete(5) # 取值0,1,2,3,4,5 , 动作是否应该加上组合?\n self.state = None\n # self.laser_data = [0 for i in range(0, 10)]\n self.num_laser = 10 # 别乱改,有些相关数据没用这个参数\n self.laser_data = None\n self.sample_laser_data = [0 for _ in range(0, self.num_laser)] # 特定抽取的data, 位置从右向左\n self.int_sample_laser_data = [0 for _ in range(0, self.num_laser)] # 特定抽取的data, 位置从右向左,整数版\n # self.state_sample_laser_data = [0 for x in range(0, self.num_laser)] # 特定抽取的data, 位置从右向左,归一化\n # 用于修正激光数据\n self.last_laser_data = [0 for x in range(0, self.num_laser)]\n # self.current_sate = None\n # self.speed = 0.0 # 运行一段时间之后,记录的speed、angle就会与实际(gazebo)有较大差距\n self.state_speed = 0.0 # 作为状态用的speed 离散整数化\n self.state_angle = 0.0 # angular speed\n self.min_speed = 0.0 # -0.75 # 线速度 m/s ;角速度 rad/s(6弧度相当于一个整圆),要想倒车必须在车身后部安装测距手段\n self.max_speed = 0.5 # 速度不能高于0.75,已经开始出现误差 0.5m/s因为环境障碍物比较密集\n # self.angle = 0.0\n self.min_angle = - 0.5\n self.max_angle = 0.5\n self.cmd_twist = Twist()\n self.done = False\n # self.thread1 = LaserNodeThread()\n # self.thread1.setDaemon(True)\n # self.thread1.start()\n # 获取状态服务\n rospy.wait_for_service('gazebo/get_model_state')\n self.get_state_srv = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState)\n # 重置位置服务\n rospy.wait_for_service('gazebo/set_model_state')\n self.set_obstacle_srv = rospy.ServiceProxy('/gazebo/set_model_state', SetModelState)\n # 重置simulation\n rospy.wait_for_service('/gazebo/reset_simulation')\n self.reset_sim_srv = rospy.ServiceProxy('/gazebo/reset_simulation', Empty)\n # self.obstacle_pose = [[0 for x in range(0, 2)] for x in range(0, 20)] # 20个障碍物的位置[x, y]\n # gazebo返回的robot数据\n self.gazebo_robot_pose_x = 0.0 # 可以考虑为其注入噪声,这里在初始化时为0,导致下面一开始角度计算有一个错误\n self.gazebo_robot_pose_y = 0.0\n self.gazebo_robot_speed = 0.0\n self.gazebo_robot_angle = 0.0\n self.robot_orientation_z = 0\n self.robot_orientation_w = 0\n self.true_state_distance = 0.0 # self.state_distance 经过处理,不再是真实距离,用于检查是否到达目标\n self.state_distance = 0.0 # 用于作为状态输入,对比每步的reward\n self.state_angle = 0.0\n self.state_polar_angle = 0.0 # 这个是robot相对x轴朝向\n self.last_robot_pose_x = 0.0\n self.last_robot_pose_y = 0.0\n # reward 相关\n self.arrive_reward = 100.0\n self.collision_reward = -100.0\n self.road_reward_times = 1 # 0.1\n self.time_cost_reward = -0.1\n self.last_distance_to_goal = 0.0 # 上一次动作时距离目标的距离\n self.distance_to_goal_threshold = 0.10 # 0.20\n self.collision_threshold = 0.35 # 至少比车身宽 0.5 , 0.43, 0.35是比较好的数值,再小就不行了\n # self.action_0 = False\n # self.distance_r_sate = 0\n # 设置最终robot位姿\n self.goal_x = 9.0 # 8\n self.goal_y = 6.0 # 8\n # self.desire_final_speed = None\n # self.desire_final_angle = None\n self.eps = 0 # 记录当前迭代轮数\n # self.get_obstacle_pose()\n self.seed()\n self.steps = 0 # for debug\n self.total_steps = 0\n self.trace_need = 1\n # self.reset() # 先初始化一下 , 在dqn中会先调用一下的\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def laser_callback(self, msg):\n self.laser_data = msg.ranges\n\n # 使用随机目标应该可以加快学习速度,和泛化能力\n # def random_goal(self):\n # # print(\"random_goal\")\n # # RandomState(ac_num)\n # # 搞不懂random被openAI怎么动了,运行结果诡异,使用baselines中的uniform分布\n # self.goal_x = self.np_random.uniform(low=-9.0, high=9.0)\n # self.goal_y = self.np_random.uniform(low=-9.0, high=9.0)\n # # self.goal_x = (18 * (np.random.ranf() - 0.5)) # x~(-9,9)\n # # self.goal_y = (18 * (np.random.ranf() - 0.5)) # y~(-9,9)\n # # print(str(self.goal_x) +\" \" +str(self.goal_y))\n # # 注意这里的设计, 每当goal 不满足条件时,就需要重新random一下,然后与出生点、“所有”障碍物点重新对比一下\n # i = -1\n # while i < 19:\n # i += 1\n # while self.compute_distance(self.goal_x, self.reset_robot_state.pose.position.x, self.goal_y,\n # self.reset_robot_state.pose.position.y) < 1.0 \\\n # or (self.compute_distance(self.goal_x, self.obstacle_pose[i][0],\n # self.goal_y, self.obstacle_pose[i][1])) < 1.2:\n # # self.goal_x = (18 * (np.random.ranf() - 0.5)) # 距离初始位置或任意障碍物过近\n # # self.goal_y = (18 * (np.random.ranf() - 0.5))\n # self.goal_x = self.np_random.uniform(low=-9.0, high=9.0)\n # self.goal_y = self.np_random.uniform(low=-9.0, high=9.0)\n # i = -1\n #\n # self.goal_x = round(self.goal_x, 1) # 离散化\n # self.goal_y = round(self.goal_y, 1)\n # # print(\"end random_goal\")\n\n # fixed version\n def reset_goal(self):\n goal_num = self.np_random.randint(0, 3)\n # self.goal_x = self.cc_func(round(goal_sequence[ac_num][goal_num][0], 1))\n # self.goal_y = self.cc_func(round(goal_sequence[ac_num][goal_num][1], 1))\n self.goal_x = round(goal_sequence[ac_num][goal_num][0], 1)\n self.goal_y = round(goal_sequence[ac_num][goal_num][1], 1)\n\n def initial_pose(self):\n pose_num = self.np_random.randint(0, 4)\n # self.reset_robot_state.pose.position.x = self.cc_func(round(initial_sequence[ac_num][goal_num][0], 1))\n # self.reset_robot_state.pose.position.y = self.cc_func(round(initial_sequence[ac_num][goal_num][1], 1))\n self.reset_robot_state.pose.position.x = round(initial_sequence[ac_num][pose_num][0], 1)\n self.reset_robot_state.pose.position.y = round(initial_sequence[ac_num][pose_num][1], 1)\n # print('init_actor' + str(ac_num) + ' --> x: ' + str(self.reset_robot_state.pose.position.x)\n # + ' y: ' + str(self.reset_robot_state.pose.position.y))\n\n @staticmethod\n def compute_distance(lhx, lhy, rhx, rhy):\n return math.sqrt((lhx - rhx) ** 2 + (lhy - rhy) ** 2)\n\n # goal 在robot当前位置为基准的角度\n def cpose_goal_angle(self):\n return math.atan2(self.goal_y - self.gazebo_robot_pose_y, self.goal_x - self.gazebo_robot_pose_x) # (-pi,pi]\n\n # # 使用相邻两次移动计算robot朝向,移动距离很小的话(特别有噪声的情况下,怎么可能计算的准确?需要借助IMU?)\n # def compute_polar_coordinates(self):\n # edge_a = self.compute_distance(self.last_robot_pose_x, self.last_robot_pose_y,\n # self.gazebo_robot_pose_x, self.gazebo_robot_pose_y)\n # edge_b = self.compute_distance(self.last_robot_pose_x, self.last_robot_pose_y, self.goal_x, self.goal_y)\n # edge_c = self.compute_distance(self.gazebo_robot_pose_x, self.gazebo_robot_pose_y, self.goal_x, self.goal_y)\n # cos_angle_beta = (edge_a**2 + edge_c**2 - edge_b**2)/(2*edge_a*edge_c)\n # self.state_distance = edge_c # 数值需进行处理\n # self.state_angle = math.pi - math.acos(cos_angle_beta) # 数值需进行处理\n\n # def distance_to_obstacle(self, num_x, num_y, count):\n # return math.sqrt((self.obstacle_pose[count][0] - num_x) ** 2 + (self.obstacle_pose[count][1] - num_y) ** 2)\n\n # 如果使用normalization_state_input(),则不要使用这个\n def state_speed_wrapper(self):\n # print(self.gazebo_robot_speed)\n # print(self.gazebo_robot_angle)\n self.state_speed = round(self.gazebo_robot_speed, 4) * 200\n self.state_speed = int(self.state_speed) # (0~100)\n self.state_speed = np.clip(self.state_speed, 0, 100)\n self.state_angle = round(self.gazebo_robot_angle, 4) * 100\n self.state_angle = int(self.state_angle) + 50 # (0~100)\n self.state_angle = np.clip(self.state_angle, 0, 100)\n\n def reset(self):\n self.total_steps += self.steps\n self.steps = 0 # for debug\n self.eps += 1\n # print('call_reset')\n self.done = False\n # 每10轮random一次\n if self.eps % 10 == 0 or self.eps == 1:\n self.reset_goal()\n # self.initial_pose()\n # robot 的初始朝向也随机化\n self.reset_robot_state.pose.orientation.z = self.np_random.uniform(low=-0.9, high=0.9)\n self.reset_robot_state.pose.orientation.w = self.np_random.uniform(low=-0.9, high=0.9)\n print('actor'+str(ac_num)+' --> x: ' + str(self.goal_x) + ' y: ' + str(self.goal_y))\n # 重置robot的 speed angle 注意各步骤执行顺序\n self.cmd_twist.linear.x = 0.0\n self.cmd_twist.angular.z = 0.0\n # 将robot重置回原位置\n start_time = time.time()\n while (time.time() - start_time) < 0.25: # 这里不使用srv直接重置,\n self.act_pub.publish(self.cmd_twist) # 先重置速度\n self.pub.publish(self.reset_robot_state)\n time.sleep(0.05)\n # time.sleep(0.5) # 重置后需要一定时间等待激光等数据更新...\n # 重置state中的pose speed angle\n # 每过大约10万步reset simulation\n if self.total_steps >= (self.trace_need*10000):\n # self.reset_sim_srv()\n self.trace_need += 1\n\n self.gazebo_robot_pose_x, self.gazebo_robot_pose_y, self.gazebo_robot_speed, self.gazebo_robot_angle,\\\n self.state_polar_angle = self.get_gazebo_state()\n self.gazebo_robot_speed = 0.0\n self.gazebo_robot_angle = 0.0\n # self.laser_data = self.thread1.laser_data\n self.laser_sub = rospy.Subscriber(self.sub_name, LaserScan, self.laser_callback, queue_size=1)\n self.last_robot_pose_x = self.gazebo_robot_pose_x\n self.last_robot_pose_y = self.gazebo_robot_pose_y\n self.sample_fuc()\n self.get_rid_of_bad_data()\n self.int_sample_fuc()\n # reset 函数需要提供初始状态\n # self.state = np.array([]) # 用来只有目标点作为状态时\n self.state_speed_wrapper()\n self.true_state_distance = self.distance_to_goal()\n if self.true_state_distance >= 10:\n self.true_state_distance = 10\n # self.normalization_state_input()\n # self.discretization_state_input()\n # print(self.sample_laser_data)\n # print(self.rew_sample_laser_data)\n self.state = np.array(self.int_sample_laser_data[:])\n # self.state = np.array(self.state_sample_laser_data[:])\n # self.state = np.append(self.state, [self.state_distance, self.state_polar_angle,\n # self.state_speed, self.state_angle])\n # self.state = np.append(self.state, [int(self.true_state_distance*6), int(self.state_polar_angle),\n # self.state_speed, self.state_angle])\n self.state_distance = int(round(self.true_state_distance*6))\n self.state = np.append(self.state, [self.state_distance, int(self.state_polar_angle)])\n self.last_distance_to_goal = self.state_distance\n self.last_laser_data = self.sample_laser_data[:]\n # self.state = self.state.reshape((14,))\n self.state = self.state.reshape((12,))\n return self.state\n\n def step(self, action):\n self.steps += 1\n assert self.action_space.contains(action), \"%r (%s) invalid\" % (action, type(action))\n # robot 的加速度是有限制的,这里的选取一定要慎重,有两种方案,要么把变化数值都设成很小(不宜,难以快速响应环境)\n # 要么将publish的频率设限,20hz(+0.1情况下)以下\n # print(\"action:\"+str(action))\n # print(\"gazebo: speed\" + str(self.gazebo_robot_speed))\n # action = 0 # testing\n # if action == 0:\n # self.gazebo_robot_speed += 0.05\n # elif action == 1:\n # self.gazebo_robot_speed -= 0.05\n # # elif action == 2:\n # # self.gazebo_robot_speed = 0.0\n # elif action == 2:\n # self.gazebo_robot_angle += 0.05\n # elif action == 3:\n # self.gazebo_robot_angle -= 0.05\n # # elif action == 5:\n # # self.gazebo_robot_angle = 0.0\n # elif action == 4:\n # pass # 保持当前状态\n # else:\n # gym.logger.warn(\"Unknown situation !\")\n if action == 0:\n self.gazebo_robot_speed = 0.10 # 速度不能突然设置为特别大的数,否则会失控,不能超过0.1了\n # self.action_0 = True\n elif action == 1:\n self.gazebo_robot_speed = 0.0\n # self.action_0 = False\n # elif action == 2:\n # self.gazebo_robot_speed = 0.0\n elif action == 2:\n self.gazebo_robot_angle = +0.10\n # self.action_0 = False\n elif action == 3:\n self.gazebo_robot_angle = -0.10\n # self.action_0 = False\n # elif action == 5:\n # self.gazebo_robot_angle = 0.0\n elif action == 4:\n self.gazebo_robot_angle = 0\n # self.action_0 = False\n else:\n gym.logger.warn(\"Unknown situation !\")\n\n self.gazebo_robot_speed = np.clip(self.gazebo_robot_speed, self.min_speed, self.max_speed)\n self.gazebo_robot_angle = np.clip(self.gazebo_robot_angle, self.min_angle, self.max_angle)\n\n # 与许多其它os不同之处,p2os设置好cmd_vel后,robot会一直保持该速度,\n # self.cmd_twist.linear.x = 0\n # gazebo中robot就算什么指令都没有,还是会有非常小的cmd_twist.linear.x与cmd_twist.angular.z,如果直接publish这些数据,只会造成误差越来越大\n if abs(self.gazebo_robot_speed) < 0.025:\n self.gazebo_robot_speed = 0.0\n if abs(self.gazebo_robot_angle) < 0.025:\n self.gazebo_robot_angle = 0.0\n self.cmd_twist.linear.x = self.gazebo_robot_speed\n self.cmd_twist.angular.z = self.gazebo_robot_angle\n # attention! testing!\n # self.cmd_twist.linear.x = 0.5\n # self.cmd_twist.angular.z = 0.0\n # print(\"gazebo: speed\" + str(self.gazebo_robot_speed) + \", angle: \" + str(self.gazebo_robot_angle))\n # 应该新建一个服务,将最新的动作信息同步给该服务,在该服务中负责发布cmd_twist,或者使用线程\n time.sleep(0.085) # 0.075\n self.act_pub.publish(self.cmd_twist)\n\n # 记录部分上一轮数据\n # self.laser_data = self.thread1.laser_data\n self.laser_sub = rospy.Subscriber(self.sub_name, LaserScan, self.laser_callback, queue_size=1)\n self.last_robot_pose_x = self.gazebo_robot_pose_x\n self.last_robot_pose_y = self.gazebo_robot_pose_y\n # 执行完动作,检查一下状态值(这里的严谨性有待考察,因为这里并不是严格的action一下,返回一个状态)\n self.gazebo_robot_pose_x, self.gazebo_robot_pose_y, self.gazebo_robot_speed, self.gazebo_robot_angle,\\\n self.state_polar_angle = self.get_gazebo_state()\n self.sample_fuc()\n self.get_rid_of_bad_data()\n self.true_state_distance = self.distance_to_goal()\n if self.true_state_distance >= 10:\n self.true_state_distance = 10\n # print(self.state_speed)\n # print(self.state_angle)\n # self.normalization_state_input()\n # self.discretization_state_input()\n self.int_sample_fuc()\n # print(self.sample_laser_data)\n # print(self.rew_sample_laser_data)\n self.state = np.array(self.int_sample_laser_data[:])\n # self.state = np.array(self.state_sample_laser_data[:])\n # self.state = np.array([])\n self.state_speed_wrapper()\n self.state_distance = int(round(self.true_state_distance * 6))\n self.state = np.append(self.state, [self.state_distance, int(self.state_polar_angle)])\n # self.state_speed, self.state_angle])\n # self.state = np.append(self.state, [self.state_distance, self.state_polar_angle,\n # self.state_speed, self.state_angle])\n # self.state = np.append(self.state, [int(self.goal_x*10), int(self.goal_y*10),\n # int(self.gazebo_robot_pose_x*10), int(self.gazebo_robot_pose_y*10),\n # int(self.last_robot_pose_x*10), int(self.last_robot_pose_y*10),\n # self.state_speed, self.state_angle])\n # print(self.sample_laser_data)\n # 应该把最后的位姿信息也作为限制, min(distance) 选择0.25,有待考察,因为将测距仪放在车头前部\n if self.true_state_distance < self.distance_to_goal_threshold \\\n or min(self.sample_laser_data) < self.collision_threshold: # and (self.gazebo_robot_speed < 0.1):\n self.done = True\n # print(\"SPACE\")\n # print(self.sample_laser_data)\n # print(self.last_laser_data)\n # print(\"x: \" + str(self.gazebo_robot_pose_x) + \"y: \" + str(self.gazebo_robot_pose_y))\n # print(self.true_state_distance)\n if self.steps <= 10: # for debug\n print(\"robot: \"+str(ac_num)+\" : \")\n print(self.sample_laser_data)\n # print(self.last_laser_data)\n print(\"goal_x: \"+str(self.goal_x)+\"goal_y: \"+str(self.goal_y))\n print(\"init_x: \"+str(self.gazebo_robot_pose_x)+\"init_y: \"+str(self.gazebo_robot_pose_y))\n # print(self.int_sample_laser_data)\n # self.state = self.state.reshape((14, ))\n self.state = self.state.reshape((12, ))\n reward_num = self.reward() # reward值必须在更新last_distance_to_goal之前计算\n self.last_distance_to_goal = self.state_distance # 更新距离,为下次计算reward准备\n self.last_laser_data = self.sample_laser_data[:] # 注意这里,坑.... copy!!!\n\n # print(\"actor\"+str(ac_num)+\": \")\n # print(self.state)\n return self.state, reward_num, self.done, {}\n\n def distance_to_goal(self):\n return math.sqrt((self.goal_x - self.gazebo_robot_pose_x)**2 + (self.goal_y - self.gazebo_robot_pose_y)**2)\n\n def reward(self):\n # 应该把最后的位姿信息也作为reward的限制,与done保持一致,目标距离与障碍物距离之间应该有交叉reward?\n if self.true_state_distance < self.distance_to_goal_threshold:\n return self.arrive_reward\n elif min(self.sample_laser_data) < self.collision_threshold: # 有关障碍物距离部分,原始激光数据有噪声(或其它原因,不能直接做判定,甚至达到0.2 ???)\n # print(self.sample_laser_data)\n # print(\"error\")\n return self.collision_reward\n # 谨慎选择有关距离的reward_fuc, 避免robot有可能出现的刷分行为(与arrive_reward的比例,正负等等)\n # 有关距离目标距离的部分,应该可以加快学习速度,但是比较难处理,超过目标点之后,跑远了就给它负的reward\n # 方案一\n # else:\n # return self.road_reward_times * (self.last_distance_ro_goal-self.distance_to_goal())\n # 方案二\n else: # 应该设置成总选action_1给负分\n # if self.action_0 is True:\n # plus_reward = 0.1\n # else:\n # plus_reward = 0\n # if self.last_distance_to_goal - self.state_distance > 0: # 越来越近\n # return 1.0 * self.road_reward_times + plus_reward\n # elif self.last_distance_to_goal - self.state_distance < 0: # 远离惩罚\n # return -0.5 * self.road_reward_times + plus_reward # 可以加大远离的惩罚\n # else:\n # return 0 + plus_reward\n if self.last_distance_to_goal - self.state_distance > 0: # 越来越近\n return 1.0*self.road_reward_times + self.time_cost_reward\n elif self.last_distance_to_goal - self.state_distance < 0: # 远离惩罚,不动惩罚\n return -0.5*self.road_reward_times + self.time_cost_reward # 可以加大远离的惩罚\n else:\n return 0 + self.time_cost_reward\n # else:\n # return 0.0\n\n def render(self, mode='human'):\n pass\n\n # @staticmethod\n # def normalization_func(max_num, min_num, x):\n # return (x - min_num)/(max_num - min_num)\n #\n # def normalization_state_input(self):\n # for i in range(0, 10):\n # self.state_sample_laser_data[i] = self.normalization_func(10, 0, self.sample_laser_data[i])\n # self.state_polar_angle = self.normalization_func(2*math.pi, 0, self.state_polar_angle)\n # self.state_distance = self.normalization_func(14.14, 0, self.true_state_distance) # sqrt(200)\n # self.state_speed = self.normalization_func(0.5, 0, self.gazebo_robot_speed)\n # if self.state_speed < 0: # why?\n # self.state_speed = 0.0\n # self.state_angle = self.normalization_func(0.5, -0.5, self.gazebo_robot_angle)\n #\n # # round()取值方式精度不高,具体查看 http://www.runoob.com/w3cnote/python-round-func-note.html\n # def discretization_state_input(self):\n # for i in range(0, 10):\n # self.state_sample_laser_data[i] = round(self.state_sample_laser_data[i], 2)\n # self.state_polar_angle = round(self.state_polar_angle, 2)\n # self.state_distance = round(self.state_distance, 2)\n # self.state_speed = round(self.state_speed, 2)\n # self.state_angle = round(self.state_angle, 2)\n\n # 是否应该换成机器人本身的数据,毕竟真实机器人没有这些\n # @staticmethod\n def get_gazebo_state(self):\n # 第一个参数model_name,第二个参数为relative_entity_name\n model_state = self.get_state_srv('robot'+str(ac_num), '') # 注意model_state 的类型为GetModelStateResponse\n robot_pose_x = round(model_state.pose.position.x, 1) # 注意pose为(x,y,z) , 离散,\n robot_pose_y = round(model_state.pose.position.y, 1)\n robot_twist_linear_x = round(model_state.twist.linear.x, 4) # 离散化\n robot_twist_angular_z = round(model_state.twist.angular.z, 4) # angular.z代表平面机器人的角速度,因为此时z轴为旋转轴\n if model_state.pose.orientation.z < 0: # robot_polar_angle位于[-2pi,2pi],what the hell?\n robot_polar_angle = -2 * math.acos(model_state.pose.orientation.w)\n else:\n robot_polar_angle = 2 * math.acos(model_state.pose.orientation.w)\n # print(robot_polar_angle)\n # print(model_state.pose.orientation.w)\n # if robot_polar_angle < 0: # 整合为[0,2pi]\n # robot_polar_angle += 2*math.pi # robot_polar_angle是robot相对默认坐标系的转向角\n if robot_polar_angle > math.pi: # 整合为(-pi,pi]\n robot_polar_angle -= 2*math.pi # robot_polar_angle是robot相对默认坐标系的转向角\n elif robot_polar_angle <= -math.pi:\n robot_polar_angle += 2*math.pi\n # print(robot_polar_angle/math.pi * 180)\n robot_to_goal_angle = self.cpose_goal_angle() - robot_polar_angle # 这里会被计算成(-2pi,2pi]\n if robot_to_goal_angle > math.pi: # 整合为(-pi,pi]\n robot_to_goal_angle -= 2*math.pi # robot_polar_angle是robot相对默认坐标系的转向角\n elif robot_to_goal_angle <= -math.pi:\n robot_to_goal_angle += 2*math.pi\n # print(\"robot 当前与坐标轴的角度\")\n # print(robot_polar_angle / math.pi * 180)\n # print(\"goal 与当前robot坐标轴的角度\")\n # print(self.cpose_goal_angle() / math.pi * 180)\n # print(\"goal 与当前robot的角度\")\n # print(robot_to_goal_angle/math.pi * 180)\n # robot_polar_angle = round(robot_polar_angle*10, 1) # normalization 注释掉这句话\n robot_to_goal_angle += math.pi # 变为(0,2pi]\n # robot_to_goal_angle = round(robot_to_goal_angle*10, 1) # normalization 注释掉这句话\n robot_to_goal_angle = round(robot_to_goal_angle*10) # normalization 注释掉这句话\n # robot_orientation_z = round(50*(model_state.pose.orientation.z+1), 1) # z与w 在[-1,1]之间\n # robot_orientation_w = round(50*(model_state.pose.orientation.w+1), 1)\n # return self.cc_func(robot_pose_x), self.cc_func(robot_pose_y), robot_twist_linear_x, robot_twist_angular_z\n return robot_pose_x, robot_pose_y, robot_twist_linear_x, robot_twist_angular_z, robot_to_goal_angle\n\n # 当前实现使用其它方法\n # 获取障碍物的位置\n # def get_obstacle_pose(self):\n # # print('call get_obstacle_pose')\n # for i in range(0, 15): # 15个方块\n # obstacle_pose = self.get_state_srv('unit_box_' + str(i), '')\n # self.obstacle_pose[i][0] = obstacle_pose.pose.position.x\n # self.obstacle_pose[i][1] = obstacle_pose.pose.position.y\n #\n # for i in range(0, 5): # 5个圆柱体,不使用球体,容易到处乱滚\n # obstacle_pose = self.get_state_srv('unit_cylinder_' + str(i), '')\n # self.obstacle_pose[i + 15][0] = obstacle_pose.pose.position.x\n # self.obstacle_pose[i + 15][1] = obstacle_pose.pose.position.y\n # # print('end call get_obstacle_pose')\n #\n # # 用来随机重置障碍物的位置坐标\n # def reset_obstacle_pose(self):\n # for i in range(0, 20):\n # self.obstacle_pose[i][0] = (20 * (np.random.ranf() - 0.5)) # x~(-10,10)\n # while abs(self.obstacle_pose[i][0]) < 1.0:\n # self.obstacle_pose[i][0] = (20 * (np.random.ranf() - 0.5)) # 距离初始位置过近\n # self.obstacle_pose[i][0] = round(self.obstacle_pose[i][0], 1) # 离散化\n # self.obstacle_pose[i][1] = (20 * (np.random.ranf() - 0.5)) # y~(-10,10)\n # while abs(self.obstacle_pose[i][1]) < 1.0:\n # self.obstacle_pose[i][1] = (20 * (np.random.ranf() - 0.5)) # 距离初始位置过近\n # self.obstacle_pose[i][1] = round(self.obstacle_pose[i][1], 1)\n #\n # # 使用服务,重置障碍物\n # def reset_obstacle_pose_srv(self):\n # new_obstacle_state = ModelState()\n #\n # new_obstacle_state.pose.orientation.x = 0\n # new_obstacle_state.pose.orientation.y = 0\n # new_obstacle_state.pose.orientation.z = 0\n # new_obstacle_state.pose.orientation.w = 0\n #\n # new_obstacle_state.twist.linear.x = 0\n # new_obstacle_state.twist.linear.y = 0\n # new_obstacle_state.twist.linear.z = 0\n #\n # new_obstacle_state.twist.angular.x = 0\n # new_obstacle_state.twist.angular.y = 0\n # new_obstacle_state.twist.angular.z = 0\n #\n # new_obstacle_state.reference_frame = \"world\"\n # for i in range(0, 15): # 10个方块\n # new_obstacle_state.model_name = \"unit_box_\"+str(i)\n # new_obstacle_state.pose.position.x = self.obstacle_pose[i][0]\n # new_obstacle_state.pose.position.y = self.obstacle_pose[i][1]\n # new_obstacle_state.pose.position.z = 0\n #\n # self.set_obstacle_srv(new_obstacle_state)\n #\n # for i in range(0, 5): # 5个圆柱体,不使用球体,容易到处乱滚\n # new_obstacle_state.model_name = \"unit_cylinder_\"+str(i)\n # new_obstacle_state.pose.position.x = self.obstacle_pose[i+15][0]\n # new_obstacle_state.pose.position.y = self.obstacle_pose[i+15][1]\n # new_obstacle_state.pose.position.z = 0\n #\n # self.set_obstacle_srv(new_obstacle_state)\n\n # 从原激光数据中抽取10组0.0型的激光数据,相当于每20°取一个;\n # 为了各robot可以互相探测,激光安装在车身前部,但更合理的做法应当是车身中央,所以要将测量到的laser数据进行一下变换0.15\n def sample_fuc(self):\n self.sample_laser_data[0] = self.laser_data[0]\n self.sample_laser_data[-1] = self.laser_data[-1]\n for i in range(1, 9):\n self.sample_laser_data[i] = self.laser_data[i * 72]\n for j in range(0, 10):\n # temp_angle = (math.pi / 9) * j # 弧度制\n # self.sample_laser_data[j] += math.sin(temp_angle) * 0.15 # 修正中心位置,这个应该用于安装于车头的情况\n self.sample_laser_data[j] = round(self.sample_laser_data[j], 1) # 离散化,保留1位小数,注意round()既非截断,也非四舍五入,也许2位更好?\n # if self.sample_laser_data[i] == float('inf'):\n if self.sample_laser_data[j] > 10.0:\n self.sample_laser_data[j] = 10.0\n\n # # 该函数应该在sample_fuc()之后调用,用于记录一个数组中的几组激光数据,self.rew_sample_laser_data为3×10(暂时)\n # def add_check_laser_data(self):\n # data = self.sample_laser_data\n # print(data)\n # if self.next_nrsld_index >= len(self.rew_sample_laser_data):\n # self.rew_sample_laser_data.append(data)\n # else:\n # self.rew_sample_laser_data[self.next_nrsld_index] = data\n # self.next_nrsld_index = (self.next_nrsld_index + 1) % self.num_rew_sample_laser_data\n # print(self.next_nrsld_index)\n # def add_check_laser_data(self):\n # data = self.sample_laser_data\n # self.rew_sample_laser_data[self.next_nrsld_index] = data\n # self.next_nrsld_index = (self.next_nrsld_index + 1) % self.num_rew_sample_laser_data\n # print(\"what the hell?\")\n # print(self.rew_sample_laser_data)\n # print(self.next_nrsld_index)\n #\n # # 用于恢复<0.3的激光数据\n # def get_rid_of_bad_data(self):\n # for i in range(self.num_laser):\n # if self.sample_laser_data[i] < 0.3:\n # for j in range(self.num_rew_sample_laser_data):\n # if self.rew_sample_laser_data[j][i] > 0.3:\n # self.sample_laser_data[i] = self.rew_sample_laser_data[j][i]\n # else:\n # pass\n # else:\n # pass\n\n # 用于恢复<0.3的激光数据,或许应该检查的是相同位置激光读数差距(应该不只保存一组,而是多组,方便对比)\n def get_rid_of_bad_data(self):\n for i in range(self.num_laser):\n if self.sample_laser_data[i] < 0.3:\n # print(\"check\")\n # print(self.sample_laser_data)\n # print(self.last_laser_data)\n self.sample_laser_data[i] = self.last_laser_data[i]\n else:\n pass\n\n # 如果使用normalization_state_input(),则不要使用这个\n def int_sample_fuc(self):\n for j in range(0, 10):\n self.int_sample_laser_data[j] = int(self.sample_laser_data[j]*10) # 变成整数\n\n # 找到其它原因,放弃该部分代码\n # # 给出一个避免噪声影响的最小值, 还要加上限制条件(inf情况下),如安然变小(噪声),为false\n # def check_min_laser_data(self):\n # mean = 0.0\n # sigle_bool_check_data = [0 for x in range(0, self.num_rew_sample_laser_data)]\n # sigle_bool_bool = [0 for x in range(0, self.num_rew_sample_laser_data)]\n # for i in range(self.num_laser):\n # for j in range(self.num_rew_sample_laser_data):\n # sigle_bool_check_data[j] = self.rew_sample_laser_data[j][i]\n # mean = sum(sigle_bool_check_data)/len(sigle_bool_check_data)\n # for k in range(self.num_rew_sample_laser_data):\n # if (sigle_bool_check_data[k] - mean) > 0.1: # (当前状态下不太可能单次变化超过0.1)\n # sigle_bool_bool[k] = False # 判定为噪声数据\n # else:\n # sigle_bool_bool[k] = True\n # if False in sigle_bool_bool:\n # self.bool_check_laser_data[i] = False # 判定该位置为噪声数据\n # # 迭代寻找最小数据,未完成\n\n # def __del__(self):\n # # 等待至线程中止。这阻塞调用线程直至线程的join()方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。\n # self.thread1.join() # 还是不对\n #\n def close(self):\n pass\n # self.thread1.join() # 还是不对\n","sub_path":"p2os_test/src/fourth_edition2_gpw.py","file_name":"fourth_edition2_gpw.py","file_ext":"py","file_size_in_byte":39245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"106753524","text":"#龙武帝尊爬取\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport lxml\nimport os\nheader={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6788.400 QQBrowser/10.3.2727.400'\n }\nr = requests.get('https://xs.sogou.com/list/7727651310',headers=header)\npattern = re.compile('(.*?)',re.S)\nsus= re.findall(pattern,r.text)\nfor su in sus:\n url = 'https://xs.sogou.com/%s'%su[0]\n rr =requests.get(url).text\n soup = BeautifulSoup(rr,\"lxml\")\n ps= soup.select('#contentWp p')\n with open('F://'+'龙武帝尊.txt','a') as fil:\n fil.write(str(su[1])+'\\n')\n for p in ps:\n with open('F://'+'龙武帝尊.txt','a') as file:\n file.write(p.string+'\\n')\n print('第%s章下载完成'%su[1])\nprint('下载完成')\n \n","sub_path":"很久很久以前写的爬虫代码/龙武帝尊爬取.py","file_name":"龙武帝尊爬取.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"556022246","text":"from typing import List\n\nfrom bson.objectid import ObjectId\n\nfrom app.models import Question\nfrom app.mongo.util import modify_id_response\n\n\ndef model(db):\n return db.iqdb.questions\n\n\nasync def find(db):\n rows = model(db).find().sort(\"_id\", -1)\n return [modify_id_response(row) async for row in rows]\n\n\nasync def insert_one(db, question: Question):\n created = await model(db).insert_one(question.dict())\n return modify_id_response(await model(db).find_one({\"_id\": created.inserted_id}))\n\n\nasync def update_one(db, _id: str, query):\n await model(db).update_one(\n {\"_id\": ObjectId(_id)}, {\"$set\": query},\n )\n\n\nasync def delete_one(db, _id: str):\n await model(db).delete_one({\"_id\": ObjectId(_id)})\n\n\nasync def update_tag(db, _id: str, tags: List[str]):\n await model(db).update_one({\"_id\": ObjectId(_id)}, {\"$set\": {\"tags\": tags}})\n","sub_path":"iq-api/app/mongo/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"520389430","text":"#!/usr/bin/env python3\n\n\"\"\"\nAuthor: Victoria McDonald\nemail: vmcd@atmos.washington.edu\nwebsite: http://torimcd.github.com\nlicense: BSD\n\nThis script creates maps and anomaly maps of the model cloud climatology in CAM5.\n\n\"\"\"\nimport matplotlib\nmatplotlib.use(\"Agg\")\n\nimport os\nimport sys\nimport numpy as np\nimport netCDF4\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nfrom matplotlib import ticker\nfrom mpl_toolkits.basemap import Basemap\nimport processing_functions as pf\n\n\n# ------------------------------------------------------------------------\n# change this section to match where you downloaded the model output files \n# ------------------------------------------------------------------------\n\ndownload_path = '' # enter the path to the directory where you downloaded the archived data, eg '/home/user/Downloads'\n\nfilebase = download_path + 'FYSP_clouds_archive/CAM5/'\noutfileloc = download_path + 'temp_data/' # this is the location to save the processed netcdf files to\n\n# the fields we want to average for our plots - these must not depend on pressure level\nfields = 'CLDHGH,CLDLOW,LHFLX,LWCF,PRECT,SHFLX,SWCF,TS'\n\n# process the fields we're plotting\npf.map_annual_average(filebase, outfileloc, 'cam5', fields) # averages fields over years 31-60, retaining location so can be plotted in map view\n\n\n# cloud climatology\ncloudfields= ['CLDHGH', 'LWCF', 'CLDLOW', 'SWCF']\n\ncloudcmaps=['bone', 'BrBG', 'PuRd', 'RdBu_r', 'bone', 'BrBG', 'OrRd_r', 'RdBu_r']\n\ncloudfilenames = ['c5_map_annual_average', 'c5_map_annual_average', 'c5_map_annual_average', 'c5_map_annual_average']\n\ncloudletters = ['a', 'b', 'c', 'd']\ncloudheadings = ['High Cloud Fraction',\t'Longwave Cloud Forcing', 'Low Cloud Fraction', 'Shortwave Cloud Forcing']\n\ncloudaxislabels = [r'$\\mathrm{Fraction}$', r'$\\mathrm{W/m^2}$', r'$\\mathrm{Fraction}$', r'$\\mathrm{W/m^2}$']\n\ncloudvmins = [0,-0.5, 0, -60, 0, -0.5, -110, -60]\ncloudvmaxs = [1, 0.5, 100, 60, 1, 0.5, 0, 60]\n\n\n#create figure - use figsize=(8.5, 9.5) to make bigger\n#fig = plt.figure(figsize=(3.46457, 4.48356))\nfig = plt.figure(figsize=(7.08661, 5.2107))\n\n\n# container with 2 rows of 2 columns, first column is grid of absolute value plots, second column is diff plots. First row is cloud climatology, second row is model climatology\nouter_grid = gridspec.GridSpec(1, 2, wspace=0.2, hspace=0.1, width_ratios=(2,1))\n\n# first two columns, absolute value plots\ncldabsgrid = gridspec.GridSpecFromSubplotSpec(4, 3, subplot_spec=outer_grid[0], wspace=0.0, hspace=0.45, width_ratios=(15,15,1))\n\n# third colum, anomaly plots\nclddiffgrid = gridspec.GridSpecFromSubplotSpec(4, 2, subplot_spec=outer_grid[1], wspace=0.0, hspace=0.45, width_ratios=(25,1))\t\n\n\n\n# -------------------------CLOUD CLIMATOLOGY -------------------------\n\n\n# keep track of which field/row we're on\nn=0\n# keep track of which gridspace/column we're plotting in for abs val\na = 0\n# keep track of which gridspace/column we're plotting in for diff\t\t\nd = 0\n# keep track of which vmin/max we're on\nv = 0\n\npresent = '_10'\neight = '_09'\n\nfor p in cloudfields:\n\tf = cloudfilenames[n]\n\tcloudfield = cloudfields[n]\n\n\tpresentcase = outfileloc + f + present +'.nc'\n\teightcase = outfileloc + f + eight +'.nc'\n\t\n\t# plot the data - PRESENT\n\tax = fig.add_subplot(cldabsgrid[a])\n\ta=a+1\n\n\tds = netCDF4.Dataset(presentcase)\n\tlons = ds.variables['lon'][:]\n\tlats = ds.variables['lat'][:]\n\tpresfld = ds.variables[cloudfield][:]\n\tunits = ds.variables[cloudfield].units\n\t\n\tds.close() #close the file\n\n\t# setup the map\n\tm = Basemap(lat_0=0,lon_0=0, ax=ax)\n\tm.drawcoastlines()\n\tm.drawcountries()\n\tparallels = [-45, 0, 45]\n\tmeridians = [-90., 0., 90.]\n\tm.drawparallels(parallels, labels=[True ,False,False, False], fontsize=6)\n\tm.drawmeridians(meridians,labels=[False,False,False,True], fontsize=6)\n\t\t\n\t\t\n\t# Create 2D lat/lon arrays for Basemap\n\tlon2d, lat2d = np.meshgrid(lons, lats)\n\t\n\t# Plot the data\n\tcs = m.pcolormesh(lon2d,lat2d,np.squeeze(presfld), cmap=cloudcmaps[v], latlon='True', vmin=cloudvmins[v], vmax=cloudvmaxs[v], rasterized=True)\n\t\n\t# This is the fix for the white lines between contour levels\n\tcs.set_edgecolor(\"face\")\n\t\t\n\t# add letter annotation\n\tplt.text(-0.10, 1.0, cloudletters[n], fontsize=6, fontweight=\"bold\", transform=ax.transAxes)\n\n\t# add heading\n\tplt.text(0.65, 1.05, cloudheadings[n], fontsize=7, transform=ax.transAxes)\n\n\n\t#plot the data - EIGHT\n\tax = fig.add_subplot(cldabsgrid[a])\n\ta=a+1\n\n\tds = netCDF4.Dataset(eightcase)\n\tlons = ds.variables['lon'][:]\n\tlats = ds.variables['lat'][:]\n\tefld = ds.variables[cloudfield][:]\n\tunits = ds.variables[cloudfield].units\n\t\n\tds.close() #close the file\n\t\n\t# setup the map\n\tm = Basemap(lat_0=0,lon_0=0, ax=ax)\n\tm.drawcoastlines()\n\tm.drawcountries()\n\tparallels = [-45, 0, 45]\n\tmeridians = [-90., 0., 90.]\n\tm.drawparallels(parallels, labels=[False ,False,False, False], fontsize=6)\n\tm.drawmeridians(meridians,labels=[False,False,False,True], fontsize=6)\n\t\t\n\t\t\n\t# Create 2D lat/lon arrays for Basemap\n\tlon2d, lat2d = np.meshgrid(lons, lats)\n\n\t# Plot \n\tcs = m.pcolormesh(lon2d,lat2d,np.squeeze(efld), cmap=cloudcmaps[v], latlon='True', vmin=cloudvmins[v], vmax=cloudvmaxs[v], rasterized=True)\n\tv = v+1\n\t\n\t# This is the fix for the white lines between contour levels\n\tcs.set_edgecolor(\"face\")\n\n\t# plot the colorbar - ABS value\n\tax = fig.add_subplot(cldabsgrid[a])\n\ta=a+1\n\tcb = plt.colorbar(cs, cax=ax)\n\n\tcb.ax.tick_params(labelsize=6) \n\ttick_locator = ticker.MaxNLocator(nbins=5)\n\tcb.locator = tick_locator\n\tcb.update_ticks()\n\n\t#plot the data - DIFF\n\tax = fig.add_subplot(clddiffgrid[d])\n\td=d+1\n\tif os.path.isfile(eightcase):\n\t\n\t\t# setup the map\n\t\tm = Basemap(lat_0=0,lon_0=0, ax=ax)\n\t\tm.drawcoastlines()\n\t\tm.drawcountries()\n\t\tparallels = [-45, 0, 45]\n\t\tmeridians = [-90., 0., 90.]\n\t\tm.drawparallels(parallels, labels=[True ,False,False, False], fontsize=6)\n\t\tm.drawmeridians(meridians,labels=[False,False,False,True], fontsize=6)\n\t\t\n\t\t\n\t\t# Create 2D lat/lon arrays for Basemap\n\t\tlon2d, lat2d = np.meshgrid(lons, lats)\n\t\n\t\t# Plot \n\t\tcs = m.pcolormesh(lon2d,lat2d,np.squeeze(efld)-np.squeeze(presfld), cmap=cloudcmaps[v], latlon='True', vmin=cloudvmins[v], vmax=cloudvmaxs[v], rasterized=True)\n\t\tv = v+1\n\t\n\t\t# This is the fix for the white lines between contour levels\n\t\tcs.set_edgecolor(\"face\")\n\n\t\t# plot the colorbar - DIFF value\n\t\tax = fig.add_subplot(clddiffgrid[d])\n\t\td=d+1\n\t\tcb = plt.colorbar(cs, cax=ax)\n\n\t\tcb.set_label(label=cloudaxislabels[n], fontsize=6)\n\t\tcb.ax.tick_params(labelsize=6) \n\t\ttick_locator = ticker.MaxNLocator(nbins=5)\n\t\tcb.locator = tick_locator\n\t\tcb.update_ticks()\n\n\t# go to next field/row\n\tn=n+1\n\n\n# -----------------------------\n\nplt.show()\n\nfig.savefig(\"figures_ED/ED_figure3.pdf\", format='pdf', bbox_inches='tight')\n\n","sub_path":"ED_figure3.py","file_name":"ED_figure3.py","file_ext":"py","file_size_in_byte":6702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306314662","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright 2018-2022 Accenture Technology\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\nimport logging\nfrom mercury.system.singleton import Singleton\n\n\ndef get_level(level: str):\n # DEBUG | INFO | WARN | ERROR | FATAL\n result = logging.INFO\n if level is not None:\n if level.upper() == 'DEBUG':\n result = logging.DEBUG\n elif level.upper() == 'ERROR':\n result = logging.ERROR\n elif level.upper() == 'WARN' or level.upper() == 'WARNING':\n result = logging.WARNING\n elif level.upper() == 'FATAL':\n result = logging.CRITICAL\n return result\n\n\n@Singleton\nclass LoggingService:\n\n def __init__(self, log_level='INFO'):\n self.logger = logging.getLogger()\n env_log_level = os.getenv('LOG_LEVEL')\n level = get_level(env_log_level) if env_log_level is not None else get_level(log_level)\n self.logger.setLevel(level)\n formatter = logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s [%(filename)s:%(lineno)s]')\n formatter.default_msec_format = '%s.%03d'\n ch = logging.StreamHandler()\n ch.setFormatter(formatter)\n ch.setLevel(level)\n self.logger.addHandler(ch)\n\n def get_logger(self):\n return self.logger\n","sub_path":"mercury/system/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"245248262","text":"#!/usr/bin/env python\n\nimport unittest\n\nimport dlint\n\n\nclass TestBadTempfileUse(dlint.test.base.BaseTest):\n\n def test_bad_tempfile_usage(self):\n python_node = self.get_ast_node(\n \"\"\"\n import tempfile\n\n tempfile.mktemp()\n \"\"\"\n )\n\n linter = dlint.linters.BadTempfileUseLinter()\n linter.visit(python_node)\n\n result = linter.get_results()\n expected = [\n dlint.linters.base.Flake8Result(\n lineno=4,\n col_offset=0,\n message=dlint.linters.BadTempfileUseLinter._error_tmpl\n ),\n ]\n\n assert result == expected\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_bad_tempfile_use.py","file_name":"test_bad_tempfile_use.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"464279401","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\n\nclass Crawler:\n \"\"\"Use this class to get data from certain url\n \"\"\"\n\n def __init__(self, url):\n\n self.chromedriver = \"/home/alex/code/hackathon/chromedriver\"\n self.options = Options()\n self.options.add_argument(\"--start-maximized\")\n self.driver = webdriver.Chrome(executable_path=self.chromedriver,\n chrome_options=self.options)\n self.url = url\n\n self.driver.get(url)\n\n def getDriver(self):\n\n return self.driver\n","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202308423","text":"\n########### Part 1 ################\n\n# answers should go to hw7.txt file \n\n\n########### Part 2 ###############\n\ndef workaround(x):\n \"\"\"this function exists to let okpy accept submissions.\n >>> workaround(5)\n 10\n \"\"\"\n return x*2\n\nimport numpy as np\nimport pandas as pd\nfrom datetime import *\n\n#YOUR CODE GOES HERE#\ndef Month_num_converter(Month):\n \"\"\" Returns numerical value given a full name Month\n >>> Month_num_converter('January')\n 1\n >>> Month_num_converter('July')\n 7\n >>> Month_num_converter('Jan')\n 'Month input is not valid'\n \"\"\"\n try:\n return{\n 'January' : 1,\n 'February' : 2,\n 'March' : 3,\n 'April' : 4,\n 'May' : 5,\n 'June' : 6,\n 'July' : 7,\n 'August' : 8,\n 'September' : 9, \n 'October' : 10,\n 'November' : 11,\n 'December' : 12\n }[Month] \n except:\n return \"Month input is not valid\"\ndef date_converter(df):\n \"\"\" Convert date in the table to the day-month-year form.\n >>> data_1.apply(date_converter,axis=1)\n 0 02-Jun-13\n 1 23-Jul-13\n 2 30-Sep-17\n 3 12-Dec-17\n dtype: object\n >>> data_2.apply(date_converter,axis=1)\n 0 02-Jan-15\n 1 21-Mar-16\n 2 30-May-17\n 3 15-Jul-18\n dtype: object\n >>> date_converter(1)\n 'invalid input'\n \"\"\"\n try:\n return df['Date'].strftime(\"%d-%b-%y\")\n except:\n return \"invalid input\"\ndef data_formatter(df):\n ''' \n Format the Month, Year, Day in the table to datatime form.\n >>> data_2 = pd.read_csv('data2.csv')\n >>> data_2['Month'] = data_2['Month'].apply(Month_num_converter)\n >>> data_2.apply(data_formatter,axis=1)\n 0 2015-01-02\n 1 2016-03-21\n 2 2017-05-30\n 3 2018-07-15\n dtype: datetime64[ns]\n >>> data_1 = pd.read_csv('data1.csv')\n >>> data_1.apply(data_formatter,axis=1)\n 0 2013-06-02\n 1 2013-07-23\n 2 2017-09-30\n 3 2017-12-12\n dtype: datetime64[ns]\n >>> date_converter(1)\n 'invalid input'\n '''\n try:\n return datetime(df['Year'],df['Month'],df['Day'])\n except:\n return \"invalid input\"\ndata_1 = pd.read_csv('data1.csv')\ndata_2 = pd.read_csv('data2.csv')\ndata_2['Month'] = data_2['Month'].apply(Month_num_converter)\ndata_2['Date'] = data_2.apply(data_formatter,axis=1)\ndata_1['Date']= data_1.apply(data_formatter,axis=1)\ncombine_csv = data_1[['Date','Tweet']].merge(data_2[['Date','Tweet']], on=['Tweet','Date'],how='outer')\ncombine_csv['Date']=pd.to_datetime(combine_csv.Date)\ncombine_csv = combine_csv.sort_values('Date',ascending=False)\ncombine_csv['Date']=combine_csv.apply(date_converter,axis=1)\ncombine_csv.to_csv('combined.csv', index=False)\n\n\n","sub_path":"hw7.py","file_name":"hw7.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430975633","text":"import glob\r\nimport os\r\nimport sys\r\nimport argparse\r\n\r\nclass FStatisticCalculator():\r\n def __init__(self):\r\n \"\"\"\r\n Initiates the class with the created variables\r\n \"\"\"\r\n self.gf = \"\" # group file\r\n self.btc = \"\" # BGC to compound file\r\n self.output_dir = \"\"\r\n self.ap_files = list() # affinity propagation files\r\n self.bgc_to_compound = dict()\r\n self.compound_to_group = dict()\r\n self.group_size = dict()\r\n self.dominant_group_counts = dict()\r\n self.complete_network_score = 0\r\n \r\n def getCmdArguments(self):\r\n \"\"\"\r\n Retrieves the command line arguments\r\n \"\"\"\r\n parser = argparse.ArgumentParser(prog='F_statistic_calculator.py')\r\n parser.add_argument(\"-a\", \"--affinity_propagation_dir\", help=\"The directory with the to be used affinity propagation files in it\", required=True)\r\n parser.add_argument(\"-b\", \"--compound_file\", help=\"The bgc to compound file, with complete path to the file\",required=False, default=\"/home/roete009/Thesis/python/temp/bgcs_to_compounds_ALL.tsv\")\r\n parser.add_argument(\"-g\", \"--group_file\", help=\"The compound to class file, with complete path to the file\",required=False, default=\"/home/roete009/Thesis/python/temp/training_set_rev03_classes.tsv\")\r\n parser.add_argument(\"-o\", \"--output_dir\", help=\"The directory to output the final results in\", required=False, default=\"./\")\r\n args = parser.parse_args()\r\n \r\n if os.path.isfile(args.group_file):\r\n self.gf = args.group_file\r\n else:\r\n sys.exit(\"The given group file is not found\")\r\n \r\n if os.path.isfile(args.compound_file):\r\n self.btc = args.compound_file\r\n else:\r\n sys.exit(\"The given compound file is not found\")\r\n \r\n if os.path.isdir(args.output_dir):\r\n self.output_dir = args.output_dir\r\n else:\r\n sys.exit(\"The given output directory is not valid\")\r\n \r\n if os.path.isdir(args.affinity_propagation_dir):\r\n files = glob.glob(args.affinity_propagation_dir + \"/*affinity_propagation*\")\r\n if len(files) != 0:\r\n self.ap_files = files\r\n else:\r\n sys.exit(\"No affinity propagation files found in the given directory\")\r\n else:\r\n sys.exit(\"The given AP directory is not valid\")\r\n print(\"Command line arguments retrieved...\")\r\n \r\n def get_compound_to_group(self):\r\n '''\r\n Parses the group file that has the groups corresponding to the compounds.\r\n '''\r\n with open(self.gf) as f:\r\n next(f)\r\n for line in f:\r\n compound_group, compound = [line.strip().split(\"\\t\")[i] for i in [2,3]]\r\n self.compound_to_group.update({compound:compound_group})\r\n if compound_group not in self.group_size.keys():\r\n self.group_size.update({compound_group:0})\r\n self.group_size[compound_group] += 1\r\n print(\"Compound to group processed...\")\r\n \r\n def get_bgc_to_compounds(self):\r\n '''\r\n Parses the bgc to compounds file to create a dict that translates the BGC to the corresponding compound\r\n '''\r\n for line in open(self.btc):\r\n bgc, compound = line.strip().split(\"\\t\")\r\n if compound in self.compound_to_group.keys():\r\n if bgc in self.bgc_to_compound:\r\n # To check if the same bgc does not have two classifications\r\n if self.compound_to_group[compound] != self.compound_to_group[self.bgc_to_compound[bgc]]:\r\n print(\"Double bgc entry with different classification for:\\n\" + bgc + \":\" + compound + \":\" + self.compound_to_group[compound]+\"\\nWith: \" + self.bgc_to_compound[bgc] + \":\" + self.compound_to_group[self.bgc_to_compound[bgc]]+\"\\n\")\r\n else:\r\n self.bgc_to_compound.update({bgc:compound})\r\n print(\"BGC to compound processed...\")\r\n \r\n def convert_to_groups(self, gcf_bgcs):\r\n \"\"\"\r\n Converts the BGCS to groups keeping the unknown groups out\r\n \"\"\"\r\n gcf_groups = list()\r\n for bgc in gcf_bgcs:\r\n try:\r\n gcf_groups.append(self.compound_to_group[self.bgc_to_compound[bgc]])\r\n except: # if not found in either of the lists\r\n continue # do nothing when the bgc group is unknown \r\n return gcf_groups \r\n \r\n def parse_ap_files(self):\r\n \"\"\"\r\n parses the affinity propagation files\r\n \"\"\"\r\n print(\"Processing all affinity propagation files\")\r\n for ap_file in self.ap_files:\r\n # create a dictionary with all group names as keys and an empty list as the value\r\n self.dominant_group_counts = {group:[0, 0] for group in self.compound_to_group.values()}\r\n self.complete_network_score = 0\r\n for line in open(ap_file):\r\n splitline = line.split(\",\")\r\n gcf_nr = splitline[0]\r\n gcf_bgcs = splitline[1:]\r\n gcf_groups = self.convert_to_groups(gcf_bgcs) # Also removes the unknown groups\r\n self.process_group_dominance(self.get_group_counts(gcf_groups))\r\n self.calculate_network_score()\r\n self.write_result_to_file(ap_file)\r\n \r\n def process_group_dominance(self, group_counts):\r\n \"\"\"\r\n Retrieves the gcf of all GCFs\r\n \"\"\"\r\n total = sum(group_counts.values())\r\n for group in group_counts.keys():\r\n if self.dominant_group_counts[group][0] < group_counts[group]:\r\n self.dominant_group_counts[group] = [group_counts[group], total]\r\n elif self.dominant_group_counts[group][0] == group_counts[group]:\r\n # This is done to penalize for groups being equally divided over multiple GCFs\r\n if total > self.dominant_group_counts[group][1]:\r\n self.dominant_group_counts[group][1] = total\r\n \r\n def get_group_counts(self, gcf_groups):\r\n \"\"\"\r\n For every compound group the number of occurences in the gcf is counted\r\n \"\"\"\r\n group_counts = dict()\r\n # count all occurences for each individual group that is found within the gcf\r\n for group in set(gcf_groups):\r\n group_counts.update({group:gcf_groups.count(group)})\r\n return group_counts \r\n \r\n def calculate_network_score(self):\r\n \"\"\"\r\n Calculates the F-statistic based on the clusters in the GCF based on the dominant group in the GCF\r\n \"\"\"\r\n total_cluster = 0\r\n for group in self.dominant_group_counts:\r\n total_cluster += 1\r\n group_count, total = self.dominant_group_counts[group]\r\n\r\n if total != 0:\r\n # The ratio of the total number of nodes in the curated group vs the number of nodes\r\n # in the GCF with the largest number of members in that group\r\n completeness = float(group_count) / float(self.group_size[group])\r\n # The purity determines how many other BGCs that do not belong to the dominant group are in the GCF\r\n purity = float(group_count) / float(total)\r\n # *0.5 to get a score between 0.0 and 1.0\r\n self.complete_network_score += (completeness * 0.50) + (purity * 0.50)\r\n self.complete_network_score = self.complete_network_score / total_cluster\r\n \r\n def open_output_file(self):\r\n \"\"\"\r\n Creates the output file\r\n \"\"\"\r\n self.file_out = open(self.output_dir + \"/f_statistic_scores.tsv\", 'w')\r\n \r\n def write_result_to_file(self, ap_file):\r\n \"\"\"\r\n Writes the results for all the AP files to a final results file in a tsv format\r\n \"\"\"\r\n ap_file = ap_file.split(\"affinity_propagation_\")[1]\r\n cutoff = ap_file.split(\"_c\")[1].split(\"_\")[0]\r\n jaccard = ap_file.split(\"_Jw\")[1].split(\"_\")[0]\r\n adjacency = ap_file.split(\"_AIw\")[1].split(\"_\")[0]\r\n DSS = ap_file.split(\"_DSSw\")[1].split(\"_\")[0]\r\n AB = ap_file.split(\"_AB\")[1].split(\".csv\")[0]\r\n self.file_out.write(ap_file + \"\\t\" + str(self.complete_network_score) + \"\\t\" + cutoff + \"\\t\" + jaccard + \"\\t\" + adjacency + \"\\t\" + DSS + \"\\t\" + AB + \"\\n\")\r\n \r\ndef main():\r\n F = FStatisticCalculator()\r\n F.getCmdArguments()\r\n F.get_compound_to_group()\r\n F.get_bgc_to_compounds()\r\n F.open_output_file()\r\n F.parse_ap_files()\r\n \r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"F_statistic_calculator.py","file_name":"F_statistic_calculator.py","file_ext":"py","file_size_in_byte":8718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645963159","text":"import socket\r\n\r\nhost = '127.0.0.1' #end do servidor\r\nport = 5005 #porta q o server esta\r\n\r\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # var s - invoca meto socket(ipv4,tcp)\r\norig = (host, port)\r\ns.bind(orig) #vinculou rost e porta com o socket\r\n\r\nwhile True:\r\n #rece msg do cliente\r\n msgClient = s.recvfrom(1024)\r\n client = msgClient[1]\r\n msg = msgClient[0].decode()\r\n\r\n #separa dados da string enviada\r\n dados = msg.split()\r\n nome = dados[0]\r\n cargo = dados[1]\r\n salario = float(dados[2])\r\n \r\n\r\n #altera valores de salario\r\n if cargo == 'operador':\r\n salario += salario * 0.2\r\n\r\n elif cargo == 'programador':\r\n salario += salario * 0.18\r\n\r\n #formata a string de resosta\r\n texto = '%s %f' % (nome, salario)\r\n \r\n print(client)\r\n print(nome, salario)\r\n \r\n #envia a resposta ao cliente\r\n s.sendto(texto.encode(), client)\r\n\r\n\r\ns.close()\r\n\r\n ","sub_path":"server1.py","file_name":"server1.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"212701059","text":"import time\nimport requests\nfrom datetime import datetime\nfrom pprint import pprint\nfrom functools import wraps\nfrom copyheaders import headers_raw_to_dict\n\n\n\n\nr_b = b'''\n\tContent-Type: application/json; charset=utf-8\n\tHost: wapsc.189.cn\n\tConnection: Keep-Alive\n\tAccept-Encoding: gzip\n\tUser-Agent: okhttp/3.6.0\n\t'''\npublic_headers = headers_raw_to_dict(r_b)\n\n\ndef login(func):\n\t@wraps(func)\n\tdef wrapper():\n\t\turl = 'http://wapsc.189.cn/lls-user-center/user/doUserLogin'\n\t\t\n\t\tres = requests.Session()\n\t\tres = requests.post(url, json=json, headers=public_headers, timeout=10)\n\t\tres_json = res.json()\n\t\t# pprint(res_json)\n\t\tsign_dict = {}\n\t\tsign_dict['session'] = res_json['body']['cloudSessionID']\n\t\tsign_dict['登录状态'] = res_json['head']['respMsg']\n\t\tprint(sign_dict)\n\t\tsession = sign_dict['session']\n\t\treturn func(session)\n\treturn wrapper\n\n\n\n@login\ndef pickFriut(session):\n\t\"\"\"\n\tPOST 摘苹果\n\t\"\"\"\n\tfruit_url = 'http://wapsc.189.cn/lls-gold-garden/gardenIndex/goldGardenIndex'\n\tfruit_json = {\"head\":{\"cloudSessionID\":session},\"body\":{}}\n\tfruit_res = requests.post(fruit_url, headers=public_headers, json=fruit_json, timeout=10)\n\tfruit_id_json = fruit_res.json()\n\t# pprint(fruit_id_json)\n\tfor i in range(len(fruit_id_json['body']['resourceFruit'])):\n\t\tfruitId = fruit_id_json['body']['resourceFruit'][i]['userFruitId']\n\t\tpick_url = 'http://wapsc.189.cn/lls-gold-garden/gardenFruit/pickFruit'\n\t\tpick_json = {\"head\":{\"cloudSessionID\":session},\"body\":{\"fruitId\":fruitId}}\n\t\tprint(pick_json)\n\t\ttime.sleep(5)\n\t\tpick_res = requests.post(pick_url, headers=public_headers, json=pick_json, timeout=10)\n\t\tpprint(pick_res.json()['head']['respMsg'])\n\nif __name__ == '__main__':\n\twhile True:\n\t\tprint(datetime.now())\n\t\tpickFriut()\n\t\ttime.sleep(86700)","sub_path":"pick_fruit.py","file_name":"pick_fruit.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"494548586","text":"class PyFSM():\n inputAbc = 'abcdefghijklmnopqrstuvwxyz{'\n statesMatrix = []\n\n def __init__(self):\n self.initStatesMatrix('matrix.txt')\n\n def initStatesMatrix(self, filename):\n try:\n f = open(filename)\n for line in f:\n self.statesMatrix.append(line[:-2].split('\\t'))\n f.close()\n except Exception as e:\n print(str(e))\n\n def checkWord(self, word):\n state = 999\n word += \"{\"\n for sym in word:\n try:\n if state == 0:\n break\n if state == 999:\n state = 0\n state = int(self.statesMatrix[state][ord(sym) - 97])\n except KeyError as e:\n print(e)\n state = 0\n except Exception as e:\n print(e)\n return state\n\n\nif __name__ == \"__main__\":\n print(\"Конечный автомат для распознавания слов Python\")\n a = PyFSM()\n word = input(\"Введите слово для проверки (или 0 для выхода):\\n\")\n while word != \"0\":\n isWord = a.checkWord(word)\n if isWord == -1:\n print(\"Это слово является ключевым словом Python!\")\n else:\n print(\"Это слово не является ключевым словом Python!\")\n word = input(\"Введите слово для проверки (или 0 для выхода):\\n\")\n","sub_path":"finite_state_machine.py","file_name":"finite_state_machine.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"280705867","text":"#!/usr/bin/env python\n#SBATCH --mem=5G\n#SBATCH --mail-type=END\n#SBATCH --mail-user=brando90@mit.edu\n#SBATCH --ntask=1\n#SBATCH --time=7-00:00\n#SBATCH --array=1-200\n\n#from __future__ import #print_function\n#tensorboard --logdir=/tmp/mdl_logs\n#\n\n''' useful commands for slurm:\n#SBATCH --array=1-200\n#SBATCH --gres=gpu:1\n'''\n\nprint('#!/usr/bin/env python')\nprint('#!/usr/bin/python')\n\nimport os\nimport sys\nimport platform\n\n#import pickle\nimport maps\nimport argparse\nimport pdb\nimport functools\n\nimport numpy as np\nimport tensorflow as tf\n\nimport my_tf_pkg as mtf\nfrom my_tf_pkg import main_hp\nfrom my_tf_pkg import main_large_hp_checkpointer as large_main_hp\n\n\nprint( '===> os.listdir(.): ', os.listdir('.') )\nprint( 'os.getcwd(): ', os.getcwd())\nprint('os.path.dirname(os.path.abspath(__file__)): ', os.path.dirname(os.path.abspath(__file__)))\n\n\nprint_func_flush_true = functools.partial(print, flush=True) # TODO fix hack\n\n## create args\narg = maps.NamedDict()\n\n## test or train error\narg.get_errors_from = mtf.get_errors_based_on_train_error\n#arg.get_errors_from = mtf.get_errors_based_on_validation_error\n\n## use TensorBoard\n#arg.use_tb = True\narg.use_tb = False\n\n#arg.type_job, arg.nb_array_jobs = 'serial', 1 #careful when this is on and GPU is NOT on\narg.type_job, arg.nb_array_jobs = 'slurm_array_parallel', 1\n#arg.type_job, arg.nb_array_jobs = 'main_large_hp_ckpt', 200\n#arg.save_checkpoints = True\narg.save_checkpoints = False\n#arg.save_last_mdl = True\narg.save_last_mdl = False\n\nhostname = platform.node()\nprint('hostname: ', hostname)\nprint('in docker? ','IN_DOCKER_CONT' in os.environ)\nif hostname == 'dhcp-18-189-23-174.dyn.mit.edu' or hostname == 'Yasmins-MacBook-Pro.local':\n ## debug mode\n #arg.data_dirpath = './data/' # path to datasets\n #prefix_path_sim_results = './tmp_simulation_results_scripts/%s/%s/' # folder where the results from script is saved\n #prefix_path_ckpts = './tmp_all_ckpts/%s/%s/' # folder where the results from script is saved\n #arg.tb_data_dump = './tb_dump' # folder where /train,/cv,/test tb stats are stored\n ## to run locally: python batch_main.py -sj sj\n # arg.data_dirpath = './data/' # path to datasets\n # prefix_path_sim_results = '../../simulation_results_scripts/%s/%s/' # folder where the results from script is saved\n # prefix_path_ckpts = '../../all_ckpts/%s/%s/' # folder where the results from script is saved\n # arg.tb_data_dump = '../../tb_dump' # folder where /train,/cv,/test tb stats are stored\n arg.data_dirpath = '/Users/brandomiranda/home_simulation_research/hbf_tensorflow_code/tf_experiments_scripts/data/' # path to datasets\n prefix_path_sim_results = '/Users/brandomiranda/home_simulation_research/simulation_results_scripts/%s/%s/' # folder where the results from script is saved\n prefix_path_ckpts = '/Users/brandomiranda/home_simulation_research/all_ckpts/%s/%s/' # folder where the results from script is saved\n arg.tb_data_dump = '/Users/brandomiranda/home_simulation_research/tb_dump' # folder where /train,/cv,/test tb stats are stored\nelse:\n # to run in OM\n arg.data_dirpath = '/om/user/brando90/home_simulation_research/hbf_tensorflow_code/tf_experiments_scripts/data/' # path to datasets\n prefix_path_sim_results = '/om/user/brando90/home_simulation_research/simulation_results_scripts/%s/%s/' # folder where the results from script is saved\n prefix_path_ckpts = '/om/user/brando90/home_simulation_research/all_ckpts/%s/%s/' # folder where the results from script is saved\n arg.tb_data_dump = '/om/user/brando90/home_simulation_research/tb_dump' # folder where /train,/cv,/test tb stats are stored\nif 'IN_DOCKER_CONT' in os.environ:\n ## to run in docker\n arg.data_dirpath = '/home_simulation_research/hbf_tensorflow_code/tf_experiments_scripts/data/' # path to datasets\n prefix_path_sim_results = '/home_simulation_research/simulation_results_scripts/%s/%s/' # folder where the results from script is saved\n prefix_path_ckpts = '/home_simulation_research/all_ckpts/%s/%s/' # folder where the results from script is saved\n arg.tb_data_dump = '/home_simulation_research/tb_dump' # folder where /train,/cv,/test tb stats are stored\n\n# prefix_path_sim_results = '../../simulation_results_scripts/%s/%s'\n# prefix_path_ckpts = '../../all_ckpts/%s/%s' # folder where the results from script is saved\narg.get_path_root = lambda arg: prefix_path_sim_results%(arg.experiment_root_dir,arg.experiment_name)\narg.get_path_root_ckpts = lambda arg: prefix_path_ckpts%(arg.experiment_root_dir,arg.experiment_name)\n\narg.prefix_ckpt = 'mdl_ckpt'\n####\narg.data_filename = 'f_32D_binary_parity_N80000'\narg.task_folder_name = mtf.get_experiment_folder(arg.data_filename) #om_f_4d_conv\narg.type_preprocess_data = None\n#\narg.N_frac = int(8*10**4)\n#print('arg.N_frac: ', arg.N_frac)\n\n## Classification Task related flags\narg.classification = mtf.classification_task_or_not(arg)\narg.classification = True\n#arg.classification = False\narg.softmax, arg.one_hot = True, True\n#arg.softmax, arg.one_hot = False, False\n\narg.experiment_name = 'task_May10_NN_32D_parity_prod_80K_softmax' # experiment_name e.g. task_Oct_10_NN_MGD_xavier_relu_N2000\n#arg.experiment_name = 'TMP3'\narg.job_name = 'NN_32D_units31x2_Adam'\n\narg.experiment_root_dir = mtf.get_experiment_folder(arg.data_filename)\n#\narg.mdl = 'standard_nn'\n#arg.mdl = 'binary_tree_16D_conv_hidden_layer'\n#\nif arg.mdl == 'debug_mdl':\n arg.act = tf.nn.relu\n arg.dims = None\n arg.get_dims = lambda arg: arg.dims\n arg.get_x_shape = lambda arg: [None,arg.D]\n arg.get_y_shape = lambda arg: [None,arg.D_out]\nelif arg.mdl == 'standard_nn':\n arg.init_type = 'truncated_normal'\n arg.init_type = 'data_xavier_kern'\n arg.init_type = 'xavier'\n\n K = 31*2\n arg.units = [K]\n #arg.mu = 0.0\n #arg.std = 0.5\n\n arg.get_W_mu_init = lambda arg: [None, None, 0]\n #arg.get_W_mu_init = lambda arg: [None, None, None, None, None, 0]\n #arg.get_W_std_init = lambda arg: [None, None, 0.1]\n arg.std_low, arg.std_high = 0.001, 3.0\n arg.get_W_std_init = lambda arg: [None, None, float(np.random.uniform(low=arg.std_low, high=arg.std_high, size=1)) ]\n #arg.get_W_std_init = lambda arg: [None, None, None, None, None, float(np.random.uniform(low=arg.std_low, high=arg.std_high, size=1)) ]\n\n #arg.get_W_mu_init = lambda arg: len(arg.dims)*[arg.mu]\n #arg.get_W_std_init = lambda arg: len(arg.dims)*[arg.std]\n\n arg.b = 0.1\n arg.get_b_init = lambda arg: len(arg.get_dims(arg))*[arg.b]\n\n arg.act = tf.nn.relu\n #arg.act = tf.nn.elu\n #arg.act = tf.nn.softplus\n #\n arg.get_x_shape = lambda arg: [None,arg.D]\n arg.get_dims = lambda arg: [arg.D]+arg.units+[arg.D_out]\nelse:\n raise ValueError('Need to use a valid model, incorrect or unknown model %s give.'%arg.mdl)\n\narg.get_y_shape = lambda arg: [None, arg.D_out]\n# float type\narg.float_type = tf.float32\n#steps\narg.steps_low = int(2.5*80000)\n#arg.steps_low = int(1*4001)\narg.steps_high = arg.steps_low+1\narg.get_steps = lambda arg: int( np.random.randint(low=arg.steps_low ,high=arg.steps_high) )\n\narg.M_low = 32\narg.M_high = 15000\narg.get_batch_size = lambda arg: int(np.random.randint(low=arg.M_low , high=arg.M_high))\n#arg.potential_batch_sizes = [16,32,64,128,256,512,1024]\n#arg.potential_batch_sizes = [128]\ndef get_power2_batch_size(arg):\n i = np.random.randint( low=0, high=len(arg.potential_batch_sizes) )\n batch_size = arg.potential_batch_sizes[i]\n return batch_size\n#arg.get_batch_size = get_power2_batch_size\n## report freqs\narg.report_error_freq = 50\narg.get_save_ckpt_freq = lambda arg: int(0.25*arg.nb_steps)\n\n## learning step/rate\narg.low_log_const_learning_rate, arg.high_log_const_learning_rate = -0.5, -6\narg.get_log_learning_rate = lambda arg: np.random.uniform(low=arg.low_log_const_learning_rate, high=arg.high_log_const_learning_rate)\narg.get_start_learning_rate = lambda arg: 10**arg.log_learning_rate\n#arg.get_log_learning_rate = lambda arg: None\n#arg.get_start_learning_rate = lambda arg: 0.01\n\n## decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps)\narg.decay_rate_low, arg.decay_rate_high = 0.1, 1.0\narg.get_decay_rate = lambda arg: np.random.uniform(low=arg.decay_rate_low, high=arg.decay_rate_high)\n#arg.get_decay_rate = lambda arg: 0.1\ndef get_decay_steps(arg):\n #arg.decay_steps_low, arg.decay_steps_high = arg.report_error_freq, arg.M\n arg.decay_steps_low, arg.decay_steps_high = 5000, 30000\n decay_steos = np.random.randint(low=arg.decay_steps_low, high=arg.decay_steps_high)\n return decay_steos\n#get_decay_steps = lambda arg: 10000\narg.get_decay_steps = get_decay_steps # when stair case, how often to shrink\n\n#arg.staircase = False\narg.staircase = True\n\n# optimization_alg = 'GD'\n# optimization_alg = 'Momentum'\n# optimization_alg = 'Adadelta'\n# optimization_alg = 'Adagrad'\noptimization_alg = 'Adam'\n# optimization_alg = 'RMSProp'\narg.optimization_alg = optimization_alg\n\nif optimization_alg == 'GD':\n pass\nelif optimization_alg=='Momentum':\n #arg.get_use_nesterov = lambda: False\n arg.get_use_nesterov = lambda: True\n arg.momentum_low, arg.momontum_high = 0.01, 0.99\n arg.get_momentum = lambda arg: np.random.uniform(low=arg.momentum_low,high=arg.momontum_high)\nelif optimization_alg == 'Adadelta':\n arg.rho_low, arg.rho_high = 0.1, 0.99\n arg.get_rho = lambda arg: np.random.uniform(low=arg.rho_low,high=arg.rho_high)\nelif optimization_alg == 'Adagrad':\n #only has learning rate\n pass\nelif optimization_alg == 'Adam':\n arg.beta1 = 0.99\n arg.beta2 = 0.999\n arg.get_beta1 = lambda arg: arg.beta1 # m = b1m + (1 - b1)m\n arg.get_beta2 = lambda arg: arg.beta2 # v = b2 v + (1 - b2)v\n #arg.beta1_low, arg.beta1_high = beta1_low=0.7, beta1_high=0.99 # m = b1m + (1 - b1)m\n #arg.beta2_low, arg.beta2_high = beta2_low=0.8, beta2_high=0.999 # v = b2 v + (1 - b2)v\nelif optimization_alg == 'RMSProp':\n arg.decay_loc, arg.decay_high = 0.75, 0.99\n arg.get_decay = lambda arg: np.random.uniform(low=arg.decay_loc,high=arg.decay_high)\n arg.momentum_low, arg.momontum_high = 0.0, 0.99\n arg.get_momentum = lambda arg: np.random.uniform(low=arg.momentum_low,high=arg.momontum_high)\nelse:\n pass\n\n#arg.bn = True\n#arg.trainable_bn = True #scale, shift BN\narg.bn = False\narg.trainable_bn = False #scale, shift BN\n\n# NORMALIZE UNIT CIRCLE\narg.data_normalize='normalize_input'\narg.data_normalize='dont_normalize'\n\nre_train = None\narg.re_train = re_train\n#\n# arg.slurm_jobid = os.environ['SLURM_JOBID']\n# arg.slurm_array_task_id = os.environ['SLURM_ARRAY_TASK_ID']\n\n####\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-d\", \"--debug\", help=\"debug mode: loads the old (pickle) config file to run in debug mode\", action='store_true')\nparser.add_argument(\"-tj\", \"--type_job\", help=\"type_job for run\")\nparser.add_argument(\"-sj\", \"--SLURM_JOBID\", help=\"SLURM_JOBID for run\")\nparser.add_argument(\"-stid\", \"--SLURM_ARRAY_TASK_ID\", help=\"SLURM_ARRAY_TASK_ID for run.\")\nparser.add_argument(\"-sca\", \"--save_config_args\", help=\"save_config_args saves the current config file to a picke file \")\n\nparser.add_argument(\"-tb\", \"--tensorboard\", dest='tensorboard', help=\"tensorboard mode: save tensorboard data\", action='store_true')\nparser.add_argument('-notb', \"--no-tensorboard\", dest='tensorboard', help=\"tensorboard mode: save tensorboard data\", action='store_false')\nparser.set_defaults(tensorboard=False)\n\nparser.add_argument(\"-pr\", \"--path_root\", help=\"path_root: specifies the path root to save hyper params\")\n#parser.add_argument(\"-hp\", \"--hyper_parameter\", help=\"hyper_parameter: when searching for hp on needs to specify were to store the results of experiment or it will default.\")\n\ncmd_args = parser.parse_args()\n# (do if first if statment is true) if (return true when cmd_args is initialized to None) else (do this)\ncmd_args.type_job = cmd_args.type_job if cmd_args.type_job else arg.type_job\n# if the flag is initialized (not None) then use it, otherwise use the flag from environment veriable\narg.slurm_jobid = cmd_args.SLURM_JOBID if cmd_args.SLURM_JOBID else os.environ['SLURM_JOBID']\nif arg.type_job == 'slurm_array_parallel':\n arg.slurm_array_task_id = cmd_args.SLURM_ARRAY_TASK_ID if cmd_args.SLURM_ARRAY_TASK_ID else os.environ['SLURM_ARRAY_TASK_ID']\nelse:\n arg.slurm_array_task_id = arg.type_job\n\nif cmd_args.save_config_args:\n # flag to save current config files to pickle file\n arg.save_config_args = cmd_args.save_config_args\nif cmd_args.debug:\n #arg.debug = cmd_args.debug\n # load old pickle config\n # pickled_arg_dict = pickle.load( open( \"pickle-slurm-%s_%s.p\"%(int(arg.slurm_jobid)+int(arg.slurm_array_task_id),arg.slurm_array_task_id), \"rb\" ) )\n # #print( pickled_arg_dict )\n # # values merged with the second dict's values overwriting those from the first.\n # arg_dict = {**dict(arg), **pickled_arg_dict}\n # arg = ns.Namespace(arg_dict)\n print('EMPTY IF STATEMENT') #TODO fix line above that gives syntax error\narg.use_tensorboard = cmd_args.tensorboard\narg.get_dataset = lambda arg: (arg.X_train, arg.Y_train, arg.X_cv, arg.Y_cv, arg.X_test, arg.Y_test)\n\narg.act_name = arg.act.__name__\n##\narg.cmd_args = cmd_args\n##\narg.print_func = print_func_flush_true # functools.partial(print, flush=True)\narg.flush = True\n#arg.flush = False\n# makes things serial or not (ie. not spin serial processes or not)\n#arg.debug = True\narg.debug = False\n#\narg.display_training = True\n#arg.display_training = False\n#\n#arg.collect_generalization = True\narg.collect_generalization = False\n##\narg.start_stid = 1\narg.end_stid = arg.nb_array_jobs\narg.restore = False\n#pdb.set_trace()\narg.rand_x = None\nif __name__ == '__main__':\n cmd_args = arg.cmd_args\n #print('In __name__ == __main__')\n if cmd_args.type_job == 'serial':\n # jobs one job. No slurm array\n arg.start_stid = 1\n arg.end_stid = arg.nb_array_jobs\n large_main_hp.run_hyperparam_search2(arg)\n elif cmd_args.type_job == 'slurm_array_parallel':\n # run one single job according to slurm array command\n main_hp.main_hp(arg)\n elif cmd_args.type_job == 'main_large_hp_ckpt':\n large_main_hp.main_large_hp_ckpt(arg)\n #elif cmd_args.type_job = 'dgx1_multiprocess':\n","sub_path":"dgx1/parity_func/dgx1_expt_32D_parity_func_80000_80K_SOFTMAX/shallow31x2.py","file_name":"shallow31x2.py","file_ext":"py","file_size_in_byte":14212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"641271168","text":"from django.utils.encoding import python_2_unicode_compatible\nfrom django.db import models\n\nfrom mapping.common.mixins import TimestampsMixin\n\n\n@python_2_unicode_compatible\nclass OperationType(TimestampsMixin):\n \"\"\"\n Operation Types\n\n Global to all companies, these are used to determine the operation type\n\n Examples:\n - Processing, Piece\n - Processing, Batch\n - Inspection, Batch\n - Setup\n - Outside Processing\n - Wait For Resource\n\n\n Value Types\n -----------\n Global to all companies, these are used to categorize the value\n type of the specified operation.\n\n Examples:\n - Value Add (VA)\n - Non-Value Add (NVA)\n - Required Non-Value Add (RNVA)\n \"\"\"\n\n VALUE_ADD = 'VA'\n NON_VALUE_ADD = 'NVA'\n REQ_NON_VALUE_ADD = 'RNVA'\n\n VALUE_TYPE_CHOICES = (\n (VALUE_ADD, 'Value Add'),\n (NON_VALUE_ADD, 'Non Value Add'),\n (REQ_NON_VALUE_ADD, 'Required, Non Value Add'),)\n\n name = models.CharField(\n 'operation type',\n help_text='The type of operation',\n max_length=50,\n unique=True,)\n\n description = models.TextField(\n 'description',\n help_text='Optional description for the operation type',\n blank=True,\n null=True,)\n\n value_type = models.CharField(\n 'value type',\n help_text='Value type classification (Value Add, Non Value Add, '\n 'Required, Non Value Add)',\n max_length=4,\n choices=VALUE_TYPE_CHOICES,\n default=VALUE_ADD,)\n\n chart_style = models.ForeignKey(\n 'ChartStyle',\n related_name='operation_type',\n null=True,)\n\n class Meta:\n db_table = 'tagging_operation_type'\n\n def __str__(self):\n return self.name\n","sub_path":"mapping/tagging/models/operation_type.py","file_name":"operation_type.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"456638166","text":"#!/usr/bin/env python\n\nimport argparse\nimport json\nimport os\nimport urllib.parse\nfrom datetime import datetime\n\nimport requests\n\n\nGITLAB_API_URL = \"https://gitlab.spack.io/api/v4/projects/2\"\nTIME_FORMAT = \"%Y-%m-%dT%H:%M:%S.%fZ\"\nAUTH_HEADER = {\n \"PRIVATE-TOKEN\": os.environ.get(\"GITLAB_TOKEN\", None)\n}\n\n\ndef paginate(query_url):\n \"\"\"Helper method to get all pages of paginated query results\"\"\"\n results = []\n\n while query_url:\n resp = requests.get(query_url, headers=AUTH_HEADER)\n\n if resp.status_code == 401:\n print(\" !!! Unauthorized to make request, check GITLAB_TOKEN !!!\")\n return []\n\n next_batch = json.loads(resp.content)\n\n for result in next_batch:\n results.append(result)\n\n if \"next\" in resp.links:\n query_url = resp.links[\"next\"][\"url\"]\n else:\n query_url = None\n\n return results\n\n\ndef print_response(resp, padding=''):\n \"\"\"Helper method to print response status code and content\"\"\"\n print(f\"{padding}response code: {resp.status_code}\")\n print(f\"{padding}response value: {resp.text}\")\n\n\ndef run_new_pipeline(pipeline_ref):\n \"\"\"Given a ref (branch name), run a new pipeline for that ref. If\n the branch has already been deleted from gitlab, this will generate\n an error and a 400 response, but we probably don't care.\"\"\"\n enc_ref = urllib.parse.quote_plus(pipeline_ref)\n run_url = f\"{GITLAB_API_URL}/pipeline?ref={enc_ref}\"\n print(f\" running new pipeline for {pipeline_ref}\")\n print_response(requests.post(run_url, headers=AUTH_HEADER), \" \")\n\n\ndef cancel_downstream_pipelines(pipeline_id):\n \"\"\"Given a pipeline id, query gitlab for its downstream pipelines\n and cancel them one at a time. Once all the child pipelines are\n canceled, also cancel the parent pipeline.\"\"\"\n bridges_url = f\"{GITLAB_API_URL}/pipelines/{pipeline_id}/bridges\"\n bridge_jobs = paginate(bridges_url)\n\n for bridge in bridge_jobs:\n if \"downstream_pipeline\" in bridge and bridge[\"downstream_pipeline\"]:\n child_pipeline = bridge[\"downstream_pipeline\"]\n child_pid = child_pipeline[\"id\"]\n print(f\" canceling child pipeline {child_pid}\")\n cancel_url = f\"{GITLAB_API_URL}/pipelines/{child_pid}/cancel\"\n print_response(requests.post(cancel_url, headers=AUTH_HEADER), \" \")\n\n print(f\" canceling parent pipeline {pipeline_id}\")\n cancel_url = f\"{GITLAB_API_URL}/pipelines/{pipeline_id}/cancel\"\n print_response(requests.post(cancel_url, headers=AUTH_HEADER), \" \")\n\n\ndef cancel_and_restart_stuck_pipelines(num_days=0):\n \"\"\"Query gitlab for all running pipelines. For any pipeline that is\n more than 1 day old, run a new pipeline on the assocatied ref/branch,\n and then cancel the pipeline as well as its downstream child\n pipelines. Any pipeolines created fewer than num_days ago will\n be ignored.\"\"\"\n print(f\"Attempting to cancel and retry pipelines older than {num_days} days\")\n\n time_now = datetime.utcnow()\n\n pipelines_url = f\"{GITLAB_API_URL}/pipelines?status=running\"\n running_pipelines = paginate(pipelines_url)\n\n print(f\"Retrieved {len(running_pipelines)} pipelines:\")\n for pipeline in running_pipelines:\n p_id = pipeline[\"id\"]\n p_ref = pipeline[\"ref\"]\n p_created = pipeline[\"created_at\"]\n\n time_pipeline = datetime.strptime(p_created, TIME_FORMAT)\n elapsed_days = (time_now - time_pipeline).days\n\n if elapsed_days > num_days:\n print(f\" Cleaning up stuck pipeline {p_id} created at {p_created}\")\n run_new_pipeline(p_ref)\n cancel_downstream_pipelines(p_id)\n else:\n print(f\" Ignoring pipeline {p_id} created at {p_created}\")\n\n\nif __name__ == \"__main__\":\n if \"GITLAB_TOKEN\" not in os.environ:\n raise Exception(\"GITLAB_TOKEN environment is not set\")\n\n parser = argparse.ArgumentParser(description=\"Find stuck pipelines to cancel and restart\")\n parser.add_argument(\"--num-days\", default=0, type=int,\n help=\"Ignore pipelines created fewer than this many days ago\")\n args = parser.parse_args()\n\n try:\n cancel_and_restart_stuck_pipelines(args.num_days)\n except Exception as inst:\n print(\"Caught unhandled exception:\")\n print(inst)\n","sub_path":"images/gitlab-clear-pipelines/cancel_and_restart_stuck_pipelines.py","file_name":"cancel_and_restart_stuck_pipelines.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"578618780","text":"from collections import Counter\nimport pandas as pd\nimport numpy as np\nfrom math import log\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom scipy.spatial.distance import cdist\nfrom scipy.cluster.hierarchy import dendrogram, linkage\nfrom sklearn.model_selection import train_test_split\n\n\"\"\"Q6 Extension\nExamine the dataset coursework2.csv. It contains similar data but has a few more\nIP addresses. Using the same clusters of IP addresses (plus sets of previously unseen\nsource and destinations), are the patterns observed in Q4 still valid? How about\nthe decision tree in Q5?\n\"\"\"\n\n###############################################################################\n\"Read the file: \"\ndata = pd.read_csv('coursework2.csv')\n\n\n\"Data Pre-processing: \"\nsourceip = data['sourceIP'].tolist()\ndestip = data['destIP'].tolist()\nclassification = data['classification'].tolist()\ndataframe = pd.DataFrame(data=data) \n\n\"Convert the csv into list and re-order the sequence\"\nd = pd.Series(destip).value_counts().reset_index().values.tolist()\ns = pd.Series(sourceip).value_counts().reset_index().values.tolist()\nc = pd.Series(classification).value_counts().reset_index().values.tolist()\n\n###############################################################################\n\n\"Calculate the numbers of occurrence of each element\"\ns1, s2, s3, s4 = 0, 0, 0, 0\nd1, d2, d3, d4 = 0, 0, 0, 0\nsf, ss, st, sh = [], [], [], []\ndf, ds, dt, dh = [], [], [], []\n\n###############################################################################\n\n\"Clustering the SourceIP addresses\"\nKs = range(0, len(s))\n\nfor k in Ks:\n if s[k][1] <= 20:\n s1 += 1\n sf.append(s[k][0])\n elif s[k][1] <= 200:\n s2 += 1\n ss.append(s[k][0])\n elif s[k][1] <= 400:\n s3 += 1\n st.append(s[k][0])\n # elif s[k][1] > 400:\n else:\n s4 += 1\n sh.append(s[k][0])\n \nssum = s1 + s2 + s3 + s4\n\n\"Replace the SourceIP addresses with their cluster names\"\nK = range(0, len(data))\n\nfor k in K: \n if dataframe.iat[k,0] in sf:\n dataframe.iat[k,0] = 'SourceIP Cluster 1'\n elif dataframe.iat[k,0] in ss:\n dataframe.iat[k,0] = 'SourceIP Cluster 2'\n elif dataframe.iat[k,0] in st:\n dataframe.iat[k,0] = 'SourceIP Cluster 3'\n else:\n dataframe.iat[k,0] = 'SourceIP Cluster 4'\n\n\n###############################################################################\n\n\"Clustering the DestIP addresses\"\nKd = range(0, len(d))\n\nfor k in Kd:\n if d[k][1] <= 40:\n d1 += 1\n df.append(d[k][0])\n elif d[k][1] <= 100:\n d2 += 1\n ds.append(d[k][0])\n elif d[k][1] <= 400:\n d3 += 1\n dt.append(d[k][0])\n # elif d[k][1] > 400:\n else:\n d4 += 1\n dh.append(d[k][0])\n \ndsum = d1 + d2 + d3 + d4\n\n\"Replace the DestIP addresses with their cluster names\"\nfor k in K: \n if dataframe.iat[k,1] in df:\n dataframe.iat[k,1] = 'DestIP Cluster 1'\n elif dataframe.iat[k,1] in ds:\n dataframe.iat[k,1] = 'DestIP Cluster 2'\n elif dataframe.iat[k,1] in dt:\n dataframe.iat[k,1] = 'DestIP Cluster 3'\n else:\n dataframe.iat[k,1] = 'DestIP Cluster 4'\n###############################################################################\n \n\"Prepare the dataset for making decision tree.\"\n\nsourceIP_cluster = dataframe['sourceIP'].tolist()\ndestIP_cluster = dataframe['destIP'].tolist()\nclassification_name = dataframe['classification'].tolist()\n\nDataSet = [ [] for _ in range(len(sourceIP_cluster)) ]\nK = range(0, len(sourceIP_cluster))\n\nfor k in K:\n DataSet[k].append(sourceIP_cluster[k])\n DataSet[k].append(destIP_cluster[k])\n DataSet[k].append(classification_name[k])\n\n\n\"\"\"Dataset is now prepared,\n in the form of [\"SourceIP Cluster name, DestIP Cluster name, Label\"]\n\"\"\"\n# print(DataSet)\n\n###############################################################################\n\n\"Create training and testing dataset.\"\n\n\"Split the data randomly: \"\ntrain, test = train_test_split(DataSet, test_size=0.1, random_state=0)\n\n\"Set the training data and labels: \"\ntraining_data = train\nheader = ['sourceIP', 'destIP', 'classification']\n\n\n###############################################################################\n\"\"\"\n Decision Tree (CART)\n\"\"\"\n\n###############################################################################\n\n\ndef class_counts(dataset):\n \"Counting the number of each type of labels\"\n counts = {} # a dictionary of label -> count.\n for data in dataset:\n label = data[-1]\n if label not in counts:\n counts[label] = 0\n counts[label] += 1\n \n return counts\n\ndef class_counts_prob(counts):\n\n total = sum(counts.values()) * 1.0\n for classification in counts.keys():\n counts[classification] = round((counts[classification] / total), 3)\n return counts\n\n###############################################################################\n\ndef numeric(value):\n \"Check if a value is numeric\"\n return isinstance(value, int) or isinstance(value, float)\n\n\n###############################################################################\n\nclass Question:\n \"Ask A Question to partition the dataset\"\n \n def __init__(self, column, value):\n self.column = column\n self.value = value\n\n def match(self, example):\n # Compare the feature value in an example to the\n # feature value in this question.\n val = example[self.column]\n if numeric(val):\n return val >= self.value\n else:\n return val == self.value\n\n def __repr__(self):\n # This is just a helper method to print the question in a readable format.\n condition = \"==\"\n if numeric(self.value):\n condition = \">=\"\n return \"Is %s %s %s?\" % (\n header[self.column], condition, str(self.value))\n\n\ndef partition(dataset, question):\n # input question = Question\n \"Partition the dataset: if match the question, then be true.\"\n \n true_data, false_data = [], []\n for data in dataset:\n if question.match(data):\n true_data.append(data)\n else:\n false_data.append(data)\n return true_data, false_data\n\n###############################################################################\n\n\"Opt 1: gini index for impurity. (Used in this version)\"\ndef gini(dataset):\n counts = class_counts(dataset) # def class_counts\n impurity = 1\n for label in counts:\n prob_of_lbl = counts[label] / float(len(dataset))\n impurity -= prob_of_lbl ** 2\n return impurity\n\n\"Opt 2: Shannon Entropy. (Not used in this version)\"\ndef calcShannonEnt(dataset): # this replaces the original gini.\n countDataSet = len(dataset)\n labelCounts={}\n for featVec in dataset:\n currentLabel=featVec[-1]\n if currentLabel not in labelCounts.keys():\n labelCounts[currentLabel] = 0\n labelCounts[currentLabel] += 1\n\n shannonEnt = 0.0\n for key in labelCounts:\n prob = float(labelCounts[key])/countDataSet\n shannonEnt -= prob * log(prob, 2)\n\n return shannonEnt\n\n###############################################################################\n\ndef info_gain(left, right, current_uncertainty):\n \"Information Gain\"\n p = float(len(left)) / (len(left) + len(right))\n ### current_uncertainty = gini(dataset)\n # return current_uncertainty - p * calcShannonEnt(left) - (1 - p) * calcShannonEnt(right)\n return current_uncertainty - p * gini(left) - (1 - p) * gini(right)\n\n\ndef find_best_split(dataset):\n \"Find the best question to ask then split.\"\n best_gain = 0 # keep track of the best information gain\n best_question = None # keep train of the feature / value that produced it\n # current_uncertainty = calcShannonEnt(dataSet)\n current_uncertainty = gini(dataset)\n n_features = len(dataset[0]) - 1 # number of columns\n\n for feature in range(n_features): # for each feature\n values = set([data[feature] for data in dataset]) # unique values in the column\n for val in values: # for each value\n question = Question(feature, val)\n true_data, false_data = partition(dataset, question)\n if len(true_data) == 0 or len(false_data) == 0:\n continue\n gain = info_gain(true_data, false_data, current_uncertainty)\n if gain >= best_gain:\n best_gain, best_question = gain, question\n\n return best_gain, best_question\n\n###############################################################################\n\nclass Leaf:\n\n def __init__(self, dataset):\n self.predictions = class_counts_prob(class_counts(dataset))\n\n\nclass Decision_Node:\n\n def __init__(self, question, true_branch, false_branch):\n self.question = question\n self.true_branch = true_branch\n self.false_branch = false_branch\n\n\ndef build_tree(dataset):\n gain, question = find_best_split(dataset)\n if gain == 0:\n return Leaf(dataset)\n\n true_data, false_data = partition(dataset, question) # partition()\n true_branch = build_tree(true_data)\n false_branch = build_tree(false_data)\n\n return Decision_Node(question, true_branch, false_branch)\n\n\n###############################################################################\n\ndef print_tree(node, spacing=\"\"):\n\n if isinstance(node, Leaf):\n print (spacing + \"Predict\", node.predictions)\n \n return\n \n print (spacing + str(node.question))\n \n print (spacing + '--> True:')\n print_tree(node.true_branch, spacing + \" \")\n\n print (spacing + '--> False:')\n print_tree(node.false_branch, spacing + \" \")\n\n###############################################################################\n\ndef classify(dataset, tree):\n \"input = dataset, build_tree\"\n\n if isinstance(tree, Leaf):\n return tree.predictions\n\n if tree.question.match(dataset):\n return classify(dataset, tree.true_branch)\n else:\n return classify(dataset, tree.false_branch)\n\n###############################################################################\n\ndef leaf(op_cla):\n \"input = output of classify.\"\n total = sum(op_cla.values()) * 1.0\n prob = {}\n \n for entry in op_cla.keys():\n prob[entry] = str(int(op_cla[lbl] / total * 100)) + \"%\"\n \n \"return the probability of decision.\"\n return prob\n\n\n###############################################################################\n\n# The next two sections are for calc accu and counting the number of unambiguous answers\ndef accuracy(dataset, my_tree):\n \n data_length = len(dataset)\n true_case = 0\n \n for data in dataset:\n classify_result = classify(data, my_tree)\n \n if max(classify_result, key=lambda x:classify_result[x]) == data[-1]:\n true_case += 1\n \n accuracy = true_case / data_length\n \n return accuracy\n\n###############################################################################\n\ndef unambiguous(dataset, my_tree, thres):\n \n unambiguous_data = []\n \n for data in dataset:\n classify_result = classify(data, my_tree)\n if max(classify_result.values()) >= thres:\n # if len(classify(data, my_tree)) == 1: \n if data not in unambiguous_data:\n unambiguous_data.append(data)\n \n return unambiguous_data\n\n\n\n\n###############################################################################\n\nif __name__ == '__main__':\n \n \"Build Decision Tree and print\"\n tree = build_tree(training_data)\n print(\"....................................................\")\n print_tree(tree)\n print(\"....................................................\")\n \n \"Test data\"\n testing_data = test \n \n \"Classify the test data.\"\n # for data in testing_data:\n # print (\"Actual: %s. Predicted: %s\" %\n # (data[-1], leaf(classify(row, my_tree))))\n \n \"Print accuracy and the unambiguous answers\"\n traacc = accuracy(training_data, tree) \n print(\"The accuracy of training data =\", traacc)\n \n testacc = accuracy(testing_data, tree)\n print(\"The accuracy of testing data =\", testacc)\n \n threshold = 0.8\n unambiguous_ans = unambiguous(testing_data, tree, threshold)\n # print(unambiguous_ans)\n print(\"There are %s unambiguous answers.\" % (len(unambiguous_ans)))\n","sub_path":"Coursework 1/Q6&Q5.py","file_name":"Q6&Q5.py","file_ext":"py","file_size_in_byte":12391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"594961186","text":"import os.path\nimport sys\nimport logging\nfrom utils.arcgis_logging import setup_logging\n\nsys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'external'))\n\nimport arcpy\nfrom utils.addresulttodisplay import add_result_to_display\nfrom gistools.tools.combine_peilingen import combine_peilingen, convert_to_metfile, results_dict_to_csv\nfrom gistools.utils.conversion_tools import get_float\n\nlogging.basicConfig(level=logging.INFO)\nsetup_logging(arcpy)\nlog = logging.getLogger(__file__)\nlog.setLevel(logging.INFO)\n\n# Read the parameter values\n# 0: Metfile inpeilingen\n# 1: Volgorde slib-vaste bodem inpeiling\n# 2: Locatie uniek profiel-ID inpeiling\n# 3: Metfile uitpeilingen\n# 4: Volgorde slib-vaste bodem uitpeiling\n# 5: Locatie uniek profiel-ID uitpeiling\n# 6: Link tabel\n# 7: Project naam\n# 8: Volgorde slib-vaste bodem\n# 9: Schaaldrempel\n# 10: Oeverpunten meeschalen\n# 11: Take waterlevel from inpeiling or uitpeiling\n# 12: Take shore points from inpeiling or uitpeiling\n# 13: Take width waterway from inpeiling or uitpeiling\n# 14: Take profielID form inpeilin or uitpeiling\n# 15: Past de vaste bodem aan, zodat die altijd laagste punt is. Geeft dus de nieuwe situatie weer wanneer er vaste\n# bodem is gebaggerd.\n# 16: keuze coordinaten uit in- of uitpeilingsbestand halen\n# 17: Doelbestand voor metfile\n# 18: Doelbestand non-scaled uitpeilingen\n \ninput_inpeilingen = arcpy.GetParameterAsText(0)\norder_in = arcpy.GetParameterAsText(1)\nloc_in = arcpy.GetParameterAsText(2)\ninput_uitpeilingen = arcpy.GetParameterAsText(3)\norder_uit = arcpy.GetParameterAsText(4)\nloc_uit = arcpy.GetParameterAsText(5)\nlink_table = arcpy.GetParameterAsText(6)\nproject = arcpy.GetParameterAsText(7)\norder = arcpy.GetParameterAsText(8)\nscale_threshold = float(arcpy.GetParameter(9))/100\nscale_bank_distance = arcpy.GetParameter(10)\nlevel_peiling = arcpy.GetParameterAsText(11)\nshore_peiling = arcpy.GetParameterAsText(12)\nwidth_peiling = arcpy.GetParameterAsText(13)\nID_peiling = arcpy.GetParameterAsText(14)\nvaste_bodem = arcpy.GetParameter(15)\noutput_file = arcpy.GetParameterAsText(16)\noutput_unscaled = arcpy.GetParameterAsText(17)\n\n# test zonder GUI\n# input_inpeilingen = './testdata/input/Testdata_Metfile_Inpeiling.met'\n# order_in = \"z1z2\"\n# loc_in = \"Eerste plaats\"\n# input_uitpeilingen = './testdata/input/Testdata_Metfile_Uitpeiling.met'\n# order_uit = \"z1z2\"\n# loc_uit = \"Eerste plaats\"\n# link_table = './testdata/input/Testdata_Combi_In_uitpeiling.csv'\n# project = \"TI20237\"\n# order = \"z1z2\"\n# scale_threshold = 100.0/100\n# scale_bank_distance = False\n# level_peiling = \"Inpeiling\"\n# shore_peiling = \"Inpeiling\"\n# width_peiling = \"Inpeiling\"\n# vaste_bodem = False\n# ID_peiling = \"Inpeiling\"\n# output_file = './testdata/output/3_e1_output.met'\n# output_unscaled = './testdata/output/3_e1_output.shp'\n\n# Print ontvangen input naar console\narcpy.AddMessage('Ontvangen parameters:')\narcpy.AddMessage('Metfile inpeilingen = ' + str(input_inpeilingen))\narcpy.AddMessage('Volgorde slib inpeiling = ' + order_in)\narcpy.AddMessage('Plaats uniek profiel-ID inpeiling = ' + loc_in)\narcpy.AddMessage('Metfile uitpeilingen = ' + str(input_uitpeilingen))\narcpy.AddMessage('Volgorde slib uitpeiling = ' + order_uit)\narcpy.AddMessage('Plaats uniek profiel-ID uitpeiling = ' + loc_uit)\narcpy.AddMessage('Link tabel = ' + str(link_table))\narcpy.AddMessage('Project = ' + str(project))\narcpy.AddMessage('Volgorde slib doelbestand metfile = ' + order)\narcpy.AddMessage('Schaaldrempel = ' + str(scale_threshold))\narcpy.AddMessage('Oevers meeschalen? = ' + str(scale_bank_distance))\narcpy.AddMessage('Waterpeil meenemen van = ' + level_peiling)\narcpy.AddMessage('Oevers meenemen van = ' + shore_peiling)\narcpy.AddMessage('Watergang breedte meenemen van = ' + str(width_peiling))\narcpy.AddMessage('Aanpassen van de vaste bodem = ' + str(vaste_bodem))\narcpy.AddMessage('Doelbestand metfile = ' + str(output_file))\narcpy.AddMessage('Doelbestand niet behandelde uitpeilingen = ' + str(output_unscaled))\n\n# Define name for output results csv\noutput_name = os.path.basename(output_file).split('.')[0]\noutput_name_results = output_name + '_processingResults.csv'\noutput_dir = os.path.dirname(output_file)\nresults_path = os.path.join(output_dir, output_name_results)\n\n# Process input data\narcpy.AddMessage('Bezig met combineren van de peilingen...')\nid_peiling = 1 if ID_peiling == \"Uitpeiling\" else 0\ncombined_points, results_list, unscaled_points = combine_peilingen(input_inpeilingen, input_uitpeilingen, order_in,\n order_uit, loc_in, loc_uit, link_table,\n width_peiling, id_peiling, scale_threshold,\n scale_bank_distance)\n\n# Generate metfile\narcpy.AddMessage('Bezig met genereren van metfile...')\nresults_list = convert_to_metfile(combined_points, project, output_file, results_list, order=order,\n level_peiling=level_peiling, shore_peiling=shore_peiling, vaste_bodem_aanpassen=vaste_bodem)\nresults_dict_to_csv(results_list, results_path)\n\n# Generate shapefile with unscaled points\nif unscaled_points:\n arcpy.AddMessage('Bezig met het genereren van het doelbestand...')\n\n output_name = os.path.basename(output_unscaled).split('.')[0]\n output_dir = os.path.dirname(output_unscaled)\n\n output_fl = arcpy.CreateFeatureclass_management(output_dir, output_name, 'POINT',\n spatial_reference=28992)\n\n # Add the fields\n arcpy.AddField_management(output_fl, 'prof_ids', \"TEXT\")\n arcpy.AddField_management(output_fl, 'datum', \"TEXT\")\n arcpy.AddField_management(output_fl, 'code', \"TEXT\")\n arcpy.AddField_management(output_fl, 'tekencode', \"TEXT\")\n arcpy.AddField_management(output_fl, 'volgnr', \"TEXT\")\n arcpy.AddField_management(output_fl, 'afstand', \"DOUBLE\")\n arcpy.AddField_management(output_fl, 'x_coord', \"DOUBLE\")\n arcpy.AddField_management(output_fl, 'y_coord', \"DOUBLE\")\n arcpy.AddField_management(output_fl, '_bk_wp', \"DOUBLE\")\n arcpy.AddField_management(output_fl, '_bk_nap', \"DOUBLE\")\n arcpy.AddField_management(output_fl, '_ok_wp', \"DOUBLE\")\n arcpy.AddField_management(output_fl, '_ok_nap', \"DOUBLE\")\n\n # Start filling the shapefile with the new points (new geometry and same properties as input file)\n dataset = arcpy.InsertCursor(output_fl)\n\n for p in unscaled_points.filter():\n arcpy.AddMessage('meetpunt: ' + str(p['properties']['prof_ids']) + ' ' + str(p['properties']['volgnr']))\n arcpy.AddMessage('geometrie: ' + str(p['geometry']['coordinates']))\n\n point = arcpy.Point()\n point.X = p['geometry']['coordinates'][0]\n point.Y = p['geometry']['coordinates'][1]\n\n row = dataset.newRow()\n row.Shape = point\n\n for field in ['prof_ids', 'datum', 'code', 'tekencode']:\n row.setValue(field, p['properties'].get(field, ''))\n\n for field in ['volgnr', 'afstand', 'x_coord', 'y_coord', '_bk_wp', '_bk_nap', '_ok_wp', '_ok_nap']:\n value = get_float(p['properties'].get(field, ''))\n row.setValue(field, value)\n\n dataset.insertRow(row)\n\n # Add results to display\n add_result_to_display(output_fl, output_name)\n\n\narcpy.AddMessage('Gereed')\n","sub_path":"3_e1_combine_in_uit_peilingen.py","file_name":"3_e1_combine_in_uit_peilingen.py","file_ext":"py","file_size_in_byte":7365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"613562736","text":"#!/usr/bin/env python\n\n# Copyright 2013 by Laszlo Nagy \n# This file is part of Puli [see file LICENSE.txt for more]\n\nimport json\nimport logging\nimport string\nimport os\n\nimport puli.graph\nimport puli.parallel\nimport puli.package\n\n\n# clang compile and get includes section\ndef compile_module(entry, func):\n import puli.clang.cindex\n\n def find_flags(cmd, fn):\n return [x for x in cmd.split(' ') if len(x) != 0 and x != fn][1:]\n\n module = entry['file']\n flags = find_flags(entry['command'], module)\n logging.info('{} : {}'.format(module, flags))\n\n compiler = puli.clang.cindex.Index.create()\n translation_unit = compiler.parse(module, args=flags)\n if not translation_unit:\n logging.critical('unable to load input: {}'.format(module))\n exit()\n return func(translation_unit)\n\n\ndef include_edges(module):\n\n def extract_includes(tu):\n from os.path import normpath\n return [(normpath(e.source.name), normpath(e.include.name))\n for e in [x for x in tu.get_includes() if not x.is_input_file]]\n\n return compile_module(module, extract_includes)\n\n\ndef register_includes(graph, edges):\n for src, dst in edges:\n if not graph.has_node(src):\n graph.add_node(dict(key=src, file=src, label=src))\n if not graph.has_node(dst):\n graph.add_node(dict(key=dst, file=dst, label=dst))\n graph.add_edge(src, dst)\n\n\n# clustering on graph\ndef trim_labels(graph, src_dir):\n\n def simplify(src, prefix):\n cut = 0 if string.find(src, prefix + os.sep) != 0 else len(prefix) + 1\n return src[cut:]\n\n for node in graph.nodes.values():\n root_dir = src_dir if node.get('pkg') is None else '/usr/include'\n node['label'] = simplify(node['file'], root_dir)\n\n\ndef cluster_on_subdir(node):\n current = node.get('cluster')\n if current is not None:\n return current\n else:\n dirname = os.path.dirname(node['label'])\n return dirname.split(os.sep)\n\n\n# driver section\ndef main():\n from multiprocessing import freeze_support\n freeze_support()\n\n from argparse import ArgumentParser\n parser = ArgumentParser()\n parser.add_argument(\"--output\",\n metavar='FILE',\n default=\"include_graph.dot\",\n help=\"Specify output file\\\n (default include_graph.dot)\")\n parser.add_argument(\"--input\",\n metavar='FILE',\n default=\"compile_commands.json\",\n help=\"The JSON compilation database\\\n (default compile_commands.json)\")\n parser.add_argument(\"--cut-packages\",\n metavar='PACKAGE_MANAGER',\n choices='rpm dpkg pacman'.split(),\n help=\"Cut the graph on headers which are from package.\\\n Known package managers: rpm, dpkg, pacman\")\n parser.add_argument('--log-level',\n metavar='LEVEL',\n choices='DEBUG INFO WARN ERROR'.split(),\n default='WARN',\n help=\"Choose a log level from DEBUG, INFO, WARN,\\\n (default) or ERROR\")\n parser.add_argument(\"--subdir\",\n metavar='DIR',\n help=\"Shorten label name under directory name\")\n args = parser.parse_args()\n\n logging.basicConfig(level=args.log_level)\n\n g = puli.graph.DependencyGraph()\n with open(args.input, \"r\") as fd:\n puli.parallel.run(json.load(fd), include_edges, register_includes, g)\n if args.cut_packages:\n pmgr = puli.package.lookup_factory(args.cut_packages)\n g.cut_packages(pmgr)\n trim_labels(g, args.subdir)\n g.group(cluster_on_subdir)\n with open(args.output, \"w\") as fd:\n g.format_dot(args.input, fd)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bin/include_graph.py","file_name":"include_graph.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508498932","text":"\"\"\" Compiled: 2020-09-18 10:38:49 \"\"\"\n\n#__src_file__ = \"extensions/advanced_corporate_actions/./etc/FCorpActionPayoutViewer.py\"\nimport acm\nimport FUxCore\n\ndef SelectFirstItem(objList, itemList):\n if objList:\n firstItem = objList[0]\n itemList.SetData(firstItem)\n\n\ndef RemoveItem(objList, itemList, item):\n index = objList.index(item)\n objList.remove(item)\n itemList.RemoveItem(item)\n if objList:\n if len(objList) <= index:\n index -= 1\n newItem = objList[index]\n if newItem:\n itemList.SetData(newItem)\n\n\ndef OnDeleteClicked(self, cd):\n val = self.m_values.GetData()\n if val:\n acm.FCorporateActionPayout[val].Delete()\n RemoveItem(self.valList, self.m_values, val)\n\n\ndef OnValDoubleClicked(self, cd):\n val = self.m_values.GetData()\n if val:\n acm.StartRunScript(acm.FCorporateActionPayout[val], 'Modify')\n\n\nclass PayoutsListCustomDialog(FUxCore.LayoutDialog):\n\n LIST_VALUES = 'listValues'\n BTN_DELETE = 'btnDelete'\n\n def __init__(self, params):\n self.choices = params['choices']\n self.selected = params['selected']\n self.caption = 'Payouts List'\n self.valLabel = 'Payouts'\n self.valList = []\n self.selectList = []\n\n def HandleApply(self):\n resultDic = acm.FDictionary()\n resultDic.AtPut('result', self.valList)\n return resultDic\n\n def SetControlData(self):\n SelectFirstItem(self.valList, self.m_values)\n\n def HandleCreate(self, dlg, layout):\n self.m_fuxDlg = dlg\n self.m_fuxDlg.Caption(self.caption)\n self.m_values = layout.GetControl(self.LIST_VALUES)\n self.m_values.AddCallback('DefaultAction', OnValDoubleClicked, self)\n self.m_btnDelete = layout.GetControl(self.BTN_DELETE)\n self.m_btnDelete.AddCallback('Activate', OnDeleteClicked, self)\n self.PopulateControls()\n self.SetControlData()\n\n def CreateLayout(self):\n b = acm.FUxLayoutBuilder()\n b.BeginVertBox()\n b. BeginHorzBox()\n b. AddSpace(3)\n b. BeginVertBox()\n b. AddLabel(\"lblValues\", self.valLabel)\n b. AddList(self.LIST_VALUES, 10, -1, 15, -1)\n b. EndBox()\n b. AddSpace(3)\n b. EndBox()\n b. AddSpace(5)\n b. BeginHorzBox()\n b. AddFill()\n b. AddButton(self.BTN_DELETE, \"Delete\")\n b. AddButton('ok', 'Close')\n b. AddSpace(3)\n b. EndBox()\n b.EndBox()\n return b\n\n def PopulateControls(self):\n self.valList = [s for s in self.selected]\n self.valList.sort()\n self.m_values.Populate(self.valList)\n if self.valList:\n self.m_values.SetData(self.valList[0])","sub_path":"Extensions/Advanced Corporate Actions/FPythonCode/FCorpActionPayoutViewer.py","file_name":"FCorpActionPayoutViewer.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"105745921","text":"'''\nCreated on 2015年10月17日\n\n@author: apple\n'''\nfrom io import BytesIO\n\n# write to BytesIO:\nf = BytesIO()\nf.write(b'hello')\nf.write(b' ')\nf.write(b'world!')\nprint(f.getvalue())\n\n# read from BytesIO:\ndata = '我爱Python'.encode('utf-8')\nf = BytesIO(data)\nprint(f.read())","sub_path":"IO/bytesio_test.py","file_name":"bytesio_test.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"340177033","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io.wavfile as wav\nfrom sklearn.decomposition import FastICA\n\nRATE = 44100\n\nmixed1 = wav.read('mixed1.wav')[1]\nmixed2 = wav.read('mixed2.wav')[1]\noutput1 = wav.read('output1.wav')[1]\noutput2 = wav.read('output2.wav')[1]\n\nplt.subplot(4,1,1)\nplt.plot(mixed1)\nplt.title('mixed1')\nplt.subplot(4,1,2)\nplt.plot(mixed2)\nplt.title('mixed2')\nplt.subplot(4,1,3)\nplt.plot(output1)\nplt.title('output1')\nplt.subplot(4,1,4)\nplt.plot(output2)\nplt.title('output2')\n\n\n#plt.subplots_adjust(0.09,0.04,0.94,0.94,0.26,0.46)\n\nplt.show()\n\n\n","sub_path":"cocktail/FDICA_real2/plot_wave.py","file_name":"plot_wave.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"474649644","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nN = 500\nfreq = 3.\nt = np.linspace(0.,(N/20.)*np.pi, N)\nphi = 0.\nx = 0.4*np.cos((freq/1.6)*t + phi) + 0.6*np.sin(freq*t + phi)\nf = np.linspace(0., 5., N)\npower = np.zeros(len(x))\nprint(freq/1.6, freq)\nfor i, fi in enumerate(f):\n\tn = np.arange(0., N, 1.)\n\tfftsin = np.sin(t*fi)\n\tfftcos = np.cos(t*fi)\n\tfft = (np.dot(x, fftsin))**2. + (np.dot(x, fftcos))**2.\n\tpower[i] = fft\npower = power/np.max(power)\n\nprint(f[np.argmax(power)])\n\nfig = plt.figure()\nax1 = fig.add_subplot(211)\nax1.plot(t, x,'--')\nax1.set_xlim((0., 2.*np.pi))\nax2 = fig.add_subplot(212)\nax2.plot(f, power,'-')\nplt.show()","sub_path":"Exploration/fft.py","file_name":"fft.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"187304041","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Profile, User,Neighbourhood,Business,Post\nfrom django.contrib.auth import login, authenticate, logout\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .forms import RegisterForm,UpdateUserForm,NeighbourHoodForm\n# Create your views here.\n@login_required(login_url='login')\ndef index(request):\n return render(request, 'index.html')\n\ndef register(request):\n if request.method == 'POST':\n form = RegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password1')\n email = form.cleaned_data['email']\n\n send_welcome_email(username=username,email=email)\n user = authenticate(username=username, password=password)\n login(request, user)\n return redirect('index')\n else:\n form = RegisterForm()\n return render(request, 'registration/signup.html', {'form': form}) \n\n\n@login_required(login_url='login')\ndef profile(request, username):\n return render(request, 'profile.html')\n\n\n@login_required(login_url='login')\ndef edit_profile(request, username):\n user = User.objects.get(username=username)\n if request.method == 'POST':\n user_form = UpdateUserForm(request.POST, instance=request.user)\n prof_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)\n if user_form.is_valid() and prof_form.is_valid():\n user_form.save()\n prof_form.save()\n return redirect('profile', user.username)\n else:\n user_form = UpdateUserForm(instance=request.user)\n prof_form = UpdateProfileForm(instance=request.user.profile)\n \n return render(request, 'edit_profile.html', {'user_form': user_form, 'prof_form': prof_form})\ndef hood(request, hood_id):\n hood = Neighbourhood.objects.get(id=hood_id)\n\n return render(request, 'hoodz.html', {'hood':mtaa})\n\ndef mahoodz(request):\n mahoodz = Neighbourhood.objects.all()\n mahoodz = mahoodz[::-1]\n \n return render(request, 'mahoodz.html', {\"mahoodz\":mahoodz})\n\ndef create_hood(request):\n if request.method == 'POST':\n form = NeighbourHoodForm(request.POST, request.FILES)\n if form.is_valid():\n hood = form.save(commit=False)\n hood.admin = request.user.profile\n hood.save()\n return redirect('mahoodz')\n else:\n form = NeighbourHoodForm()\n return render(request, 'newhoodz.html', {'form': form})\n\ndef join_hood(request, id):\n neighbourhood = get_object_or_404(Neighbourhood, id=id)\n request.user.profile.neighbourhood = neighbourhood\n request.user.profile.save()\n return redirect('mahoodz')\n\ndef leave_hood(request, id):\n request.user.profile.neighbourhood = None\n request.user.profile.save()\n return redirect('mahoodz')\n\n\ndef hood_occupants(request, mtaa_id):\n mtaa = Neighbourhood.objects.get(id=mtaa_id)\n occupants = Profile.objects.filter(neighbourhood=mtaa)\n return render(request, 'occupants.html', {'occupants': occupants})\n\ndef post(request, hood_id):\n hood = Neighbourhood.objects.get(id=hood_id)\n post = Post.objects.filter(neighbourhood=hood)\n if request.method == 'POST':\n form = PostForm(request.POST)\n if form.is_valid():\n form = form.save(commit=False)\n form.neighbourhood = hood\n form.user = request.user.profile\n form.save()\n return redirect('post', hood.id)\n else:\n form = PostForm()\n return render(request, 'post.html', {'post': post,'form':form})\n\ndef business(request, hood_id):\n hood = Neighbourhood.objects.get(id=hood_id)\n business = Business.objects.filter(neighbourhood=hood)\n if request.method == 'POST':\n form = BusinessForm(request.POST)\n if form.is_valid():\n form = form.save(commit=False)\n form.neighbourhood = hood\n form.user = request.user.profile\n form.save()\n return redirect('business', hood.id)\n else:\n form = BusinessForm()\n return render(request, 'business.html', {'business': business,'form':form})\n\n\ndef search(request):\n if request.method == 'GET':\n name = request.GET.get(\"title\")\n search = Business.objects.filter(name__icontains=name).all()\n message = f'name'\n return render(request, 'search.html', {'search': search,'message': message })\n else:\n message = \"You haven't searched for any image category\"\n return render(request, \"search.html\")\n\n","sub_path":"hoodapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"606224509","text":"# -*- coding: utf-8 -*-\nfrom PyQt4 import QtCore, QtGui\nimport sys\n\n\nclass MyWidget(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.label = QtGui.QLabel(\"Содержимое страницы\")\n self.box = QtGui.QVBoxLayout()\n self.box.addWidget(self.label)\n self.setLayout(self.box)\n\n def contextMenuEvent(self, event):\n act1 = QtGui.QAction(\"Пункт &1\", self)\n act1.triggered.connect(self.on_act1)\n act2 = QtGui.QAction(\"Пункт &2\", self)\n act2.triggered.connect(self.on_act2)\n QtGui.QMenu.exec_([act1, act2], event.globalPos(),\n act2, self)\n\n def on_act1(self):\n print(\"on_act1\")\n\n def on_act2(self):\n print(\"on_act2\")\n\n\nclass MyWindow(QtGui.QMainWindow):\n def __init__(self, parent=None):\n QtGui.QMainWindow.__init__(self, parent)\n self.w = MyWidget()\n self.setCentralWidget(self.w)\n\n\napp = QtGui.QApplication(sys.argv)\nwindow = MyWindow()\nwindow.setWindowTitle(\"Класс QMenu\")\nwindow.resize(500, 350)\n\nwindow.show()\nsys.exit(app.exec_())","sub_path":"140_gui/pyqt_pyside/examples/PyQt_PySide_book/009_Creating SDI- and MDI-applications/002_Menu/736_QMenu_exec_.py","file_name":"736_QMenu_exec_.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"152557376","text":"import yaku\nfrom enum import Enum\n\nclass Block(Enum) :\n PON = 1\n CHI = 2\n ANKAN = 3\n MINKAN = 4\n ANKO = 5\n SYUNTSU = 6\n TOITSU = 7\n\ndef calcFu(fuuro, ron, agarihai, jikaze ,bakaze, temp) : \n fu = 0\n menzen = False\n for i in range(0,4) : \n if fuuro[i*4] == 0 : \n menzen = True\n break\n elif fuuro[i*4] == 3 : \n continue\n else : break\n\n if yaku.pinfu(temp, agarihai, bakaze, jikaze) : \n if not(ron) : fu = 20\n else : fu = 30\n return fu\n\n fu = 20\n if menzen and ron : fu += 10\n elif not(ron) : fu += 2\n for i in range(0,10,2) :\n if temp[i] == Block.TOITSU.value : \n if temp[i+1] == agarihai : \n fu += 2\n break\n elif temp[i] == Block.SYUNTSU.value : \n if (temp[i+1] == agarihai - 2 and temp[i+1] % 10 == 1) or (temp[i+1] == agarihai and temp[i+1] % 10 == 7) or temp[i+1] == agarihai - 1 or temp[i+1] == agarihai + 1 :\n fu += 2\n break\n for i in range(0,10,2) :\n if temp[i] == Block.TOITSU.value : \n if temp[i+1] >= 35 or temp[i+1] == bakaze : fu += 2\n if temp[i+1] == jikaze : fu += 2\n \n for i in range(0,10,2) :\n if temp[i] == Block.ANKO.value :\n if temp[i+1] % 10 == 1 or temp[i+1] % 10 == 9 or temp[i+1] > 30 : fu += 8\n else : fu += 4\n if temp[i] == Block.PON.value :\n if temp[i+1] % 10 == 1 or temp[i+1] % 10 == 9 or temp[i+1] > 30 : fu += 4\n else : fu += 2\n if temp[i] == Block.ANKAN.value :\n if temp[i+1] % 10 == 1 or temp[i+1] % 10 == 9 or temp[i+1] > 30 : fu += 32\n else : fu += 16\n if temp[i] == Block.MINKAN.value :\n if temp[i+1] % 10 == 1 or temp[i+1] % 10 == 9 or temp[i+1] > 30 : fu += 16\n else : fu += 8\n if fu == 20 : fu = 30\n if fu % 10 > 0 : fu = (fu + 10) - (fu % 10)\n \n return fu\n","sub_path":"src/fu.py","file_name":"fu.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"177646525","text":"\"\"\" go_your_way.py\n\nQualification Round - Code Jam 2019 - You can go your own way\nAuthor: AlbertHolmes\n\n\"\"\"\n\n\n# Helper\ndef solve(path):\n\n res = \"\"\n for footprint in path:\n res += \"E\" if footprint == \"S\" else \"S\"\n return res\n\n# Main\ntest_cases = int(input())\nfor test_case in range(test_cases):\n grid_size = int(input())\n rival_path = input()\n answer = solve(rival_path)\n print(\"Case #{}: {}\".format(test_case + 1, answer))\n","sub_path":"google/competitions/code_jam/2019/qualification_round/go_your_way.py","file_name":"go_your_way.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"492366133","text":"#!/home/suhan/public_html/cgi-bin/anaconda3/envs/osnap/bin/python\nimport cgitb, cgi, json, sys, re, os\nimport time\nfrom datetime import datetime\ncgitb.enable()\n\nimport pandas as pd\nimport numpy as np\n#import plotly.graph_objs as go\nimport pysal as ps \n#import dash\n#import dash_core_components as dcc\n#import dash_html_components as html\n#from dash.dependencies import Input, Output , State\nfrom scipy import stats\nfrom scipy.stats import rankdata\n\n#app = dash.Dash()\n#app.config['suppress_callback_exceptions']=True # If you have an id in the layout/callbacks that is not in the callbacks/layout\n\n# Boostrap CSS.\n#app.css.append_css({'external_url': 'https://codepen.io/amyoshino/pen/jzXypZ.css'}) # noqa: E501\n\n# Reading Data\n# Read http://darribas.org/gds_scipy16/ipynb_md/01_data_processing.html\ncsv_path = ps.examples.get_path('usjoin.csv')\nshp_path = ps.examples.get_path('us48.shp')\n#print(csv_path)\n#print(shp_path)\n#print(os.path.getsize(csv_path))\n#print(os.path.getsize(shp_path))\n#print(\"last modified: %s\" % time.ctime(os.path.getmtime(csv_path)))\n#print(\"last modified: %s\" % time.ctime(os.path.getmtime(shp_path)))\n#print(\"last modified: %s\" % int(os.path.getmtime(csv_path)))\n#\n#print(os.path.basename(csv_path))\n#print(os.path.basename(shp_path))\n\n# relative path ???\ncache_path = '/home/suhan/public_html/STARS/cache/' + \\\n\t\t\t os.path.basename(csv_path) + '(' + str(os.path.getsize(csv_path)) + ')_' + \\\n\t\t\t os.path.basename(shp_path) + '(' + str(os.path.getsize(shp_path)) + ').json'\n#print(cache_path)\n\nmodifiedtime = max(os.path.getmtime(csv_path), os.path.getmtime(shp_path))\n#print(modifiedtime)\njsonString = ''\nif (os.path.isfile(cache_path) and os.path.getmtime(cache_path) > modifiedtime):\n\t#print(os.path.getmtime(cache_path))\n\tifile = open(cache_path, 'r') \n\tjsonString = ifile.read()\n\t#print('jsonString:', len(jsonString))\n\tifile.close()\nelse:\n\tusjoin = pd.read_csv(csv_path)\n\tus48_map = ps.pdio.read_files(shp_path)\n\t#print('usjoin:')\n\t#print(usjoin)\n\t#print('us48_map:')\n\t#print(us48_map)\n\t\n\t# Columns to calculate PCR's and Moran'I as strings/objects\n\tyears = list(range(1929, 2010)) \n\tcols_to_calculate = list(map(str, years))\n\t\n\t# For dropdowns\n\t#years_aux = [str(i) for i in years] # Converting each element to string (it could be list(map(str, years)))\n\t#years_options = [{'label': i, 'value': i} for i in years_aux]\n\t\n\t# us48_map has a left zero in states that have FIPS under 10\n\t#usjoin.STATE_FIPS\n\t#us48_map.STATE_FIPS\n\tus48_map.STATE_FIPS = us48_map.STATE_FIPS.astype(int)\n\t\n\tdf_map_raw = us48_map.merge(usjoin, on='STATE_FIPS')\n\t#print(df_map_raw)\n\t#json_split = df_map_raw.to_json(orient='split') # 32,257 bytes\n\t#json_records = df_map_raw.to_json(orient='records') # 63,864 bytes\n\t#print(len(json_split), len(json_records))\n\t#print(json_split[0:3000])\n\t\n\t#rk_map_raw = us48_map.merge(usjoin, on='STATE_FIPS')\n\t#for year in years: rk_map_raw[str(year)] = rankdata(df_map_raw[str(year)], method='ordinal')\n\t\n\t\n\t\n\t# Calculating PCR\n\tdef calculate_pcr(x):\n\t\treturn x / np.mean(x)\n\t\n\tall_pcrs = usjoin[cols_to_calculate].apply(calculate_pcr)\n\t\n\tusjoin[cols_to_calculate] = all_pcrs\n\t\n\tW = ps.queen_from_shapefile(shp_path)\n\t#print('W0:', type(W))\n\t#print(W)\n\tW.transform = 'r'\n\t#print('W1:', type(W))\n\t#print(W)\n\t\n\tdf_map_pcr = us48_map.merge(usjoin, on='STATE_FIPS') \n\t#print(df_map_pcr)\n\t#json_split = df_map_pcr.to_json(orient='split') # 62,280 bytes\n\t#json_records = df_map_pcr.to_json(orient='records') # 93,887 bytes\n\t#print(len(json_split), len(json_records))\n\t#print(json_split[0:3000])\n\t\n\t#rk_map_pcr = us48_map.merge(usjoin, on='STATE_FIPS')\n\t#for year in years: rk_map_pcr[str(year)] = rankdata(df_map_pcr[str(year)], method='ordinal')\n\t\n\t\n\t# Calculating Moran'I for every column\n\tstarted_datetime = datetime.now()\n\tdateYYMMDD = started_datetime.strftime('%Y%m%d')\n\ttimeHHMMSS = started_datetime.strftime('%H%M%S')\n\t#print(\"Calculating Moran'I start at %s %s\" % (started_datetime.strftime('%Y-%m-%d'), started_datetime.strftime('%H:%M:%S')))\n\tmorans = {}\n\tfor i in cols_to_calculate:\n\t\taux = ps.Moran(df_map_pcr[i], W).I\n\t\tmorans[i] = aux\n\t#print('morans:', len(morans))\n\t#print(morans)\n\tended_datetime = datetime.now()\n\telapsed = ended_datetime - started_datetime\n\ttotal_seconds = int(elapsed.total_seconds())\n\thours, remainder = divmod(total_seconds,60*60)\n\tminutes, seconds = divmod(remainder,60)\t\n\t#print(\"Calculating Moran'I ended at %s %s Elapsed %02d:%02d:%02d\" % (ended_datetime.strftime('%Y-%m-%d'), ended_datetime.strftime('%H:%M:%S'), hours, minutes, seconds))\n\t\n\t# Test code form timepath-graph\n\tdef calculate_lag_value(x):\n\t\treturn ps.lag_spatial(W, x)\n\tlagged_pcr = df_map_pcr[cols_to_calculate].apply(calculate_lag_value)\n\t#print('lagged_pcr:')\n\t#print(lagged_pcr)\n\t\n\tout_data = {'years': years, 'morans': morans }\n\tout_data['df_map_pcr'] = df_map_pcr.to_json(orient='split')\n\tout_data['lagged_pcr'] = lagged_pcr.to_json(orient='split')\n\t\n\tjsonString = json.dumps(out_data)\n\tofile = open(cache_path, 'w')\n\tofile.write(jsonString)\n\tofile.close()\n\n\nprint (\"Content-Type: text/html\\n\")\n#print (json.dumps(out_data)) # 118,091 bytes\nprint (jsonString) # 118,091 bytes\n\n############################################################ \n\n \n'''\n############################################################ \n# Layout #\n############## \napp.layout = html.Div(\n html.Div([ \n html.Div([\n \n html.H1(children='Web STARS'),\n \n html.Div(children=''\"\n Web STARS: A web-based version of Space-Time Analysis of Regional Systems\n ''\"),\n \n html.Div([ \n dcc.Checklist(\n id='auto-check',\n options=[{'label': ' Time Travel Animation ', 'value': 'auto'}],\n values=[],\n ),\n ], style={'padding-top': '20px', 'display': 'inline-block', 'float': 'left'}),\n \n html.Div([\n dcc.Slider(\n id='years-slider',\n min=min(years),\n max=max(years),\n value=min(years),\n marks={str(year): str(year) for year in years_by_step},\n ), \n dcc.Interval(\n id='interval-event',\n interval=24*60*60*1000,\n n_intervals=0\n ),\n \n dcc.RadioItems(\n id='type_data_selector',\n options=[\n {'label': 'Per Capita Relative Ratio (PCR)', 'value': 'pcr'},\n {'label': 'Raw Income Data', 'value': 'raw'}\n ],\n value='pcr',\n #labelStyle={'display': 'inline-block'},\n style={'margin-top': '50'}\n )\n \n ], style={'width':800, 'margin':25, 'float': 'left'}),\n \n ], className=\"row\"),\n \n html.Div([\n dcc.Checklist(\n id='spatial_travel-check',\n options=[{'label': ' Spatial Travel Animation ', 'value': 'auto'}],\n values=[],\n ),\n dcc.Interval(\n id='spatial_interval-event',\n interval=24*60*60*1000,\n n_intervals=0\n ),\n ], className=\"row\"),\n \n html.Div([ \n html.Div([\n \n dcc.Graph(\n id='choropleth-graph'\n ),\n \n dcc.Graph( # ?dcc.Graph to learn more about the properties\n id='timeseries-graph',\n clear_on_unhover = 'True' # Sets the slider year when the mouse hover if off the graph\n ), \n \n # dcc.Graph(\n # id='timepath-graph'\n #),\n \n ], className=\"four columns\"), \n html.Div([ \n \n dcc.Graph(\n id='scatter-graph'\n ),\n \n html.P('Choose a pair of years for densities:'),\n \n html.Div([\n dcc.Dropdown(\n id='initial_years_dropdown',\n options=years_options,\n value='1929'\n ),\n dcc.Dropdown(\n id='final_years_dropdown',\n options=years_options,\n value='2009'\n )], className=\"row\"),\n \n dcc.Graph(\n id='density-graph' \n ),\n \n # dcc.Graph(\n # id='boxplot-graph'\n #) \n \n ], className=\"four columns\"), \n html.Div([\n dcc.Graph(\n id='timepath-graph'\n ),\n dcc.Graph(\n id='boxplot-graph'\n ), \n\t\t\t\t\t ], className=\"four columns\"), \n ], className=\"row\")\n ], className='ten columns offset-by-one')\n)\n\n\n\n\n############################################################ \n@app.callback(\n Output('interval-event', 'interval'), \n [Input('auto-check', 'values')],\n [State('interval-event', 'interval')]\n)\ndef change_auto(checkedValues, interval):\n #print(checkedValues, interval)\n if (len(checkedValues) != 0): return 2*1000 # AUTO is checked\n else: return 24*60*60*1000 # AUTO is not checked\n\n\n#@app.callback(Output('years-slider', 'value'), [Input('interval-event', 'n_intervals')], events=[Event('interval-event', 'interval')])\n@app.callback(\n Output('years-slider', 'value'), \n [Input('interval-event', 'n_intervals')],\n [State('years-slider', 'value'), State('years-slider', 'min'), State('years-slider', 'max'), State('auto-check', 'values')]\n)\ndef update_slider(n, theYear, minValue, maxValue, checkedValues):\n if (len(checkedValues) == 0): return theYear # AUTO is not checked\n newValue = theYear + 1\n if (newValue > maxValue): newValue = minValue\n #print(n, theYear, minValue, maxValue, newValue, checkedValues)\n return newValue\n\n\n# hide the options of the spatial_travel-check when AUTO is checked\n@app.callback(\n Output('spatial_travel-check', 'options'), \n [Input('auto-check', 'values')],\n)\ndef hide_show_spatial_travel_checkbox(checkedValues):\n print(checkedValues)\n if (len(checkedValues) != 0): return [] # AUTO is checked\n else: return [{'label': ' Spatial Travel Animation ', 'value': 'auto'}] # AUTO is not checked\n\n# clear the values of the spatial_travel-check when AUTO is checked or not\n@app.callback(\n Output('spatial_travel-check', 'values'), \n [Input('auto-check', 'values')],\n)\ndef clear_values_of_spatial_travel_checkbox(checkedValues):\n #print(checkedValues)\n return []\n\n# reset n_intervals in the Sspatial_interval-event when AUTO is checked or not\n# reset n_intervals in the Sspatial_interval-event when year is changed in the years-slider\n@app.callback(\n Output('spatial_interval-event', 'n_intervals'), \n [Input('auto-check', 'values'), Input('years-slider','value')],\n [State('spatial_interval-event', 'n_intervals')],\n)\ndef reset_n_intervals_of_spatial_interval_event(checkedValues, year, oldValue):\n #print(checkedValues, 'oldValue:', oldValue)\n return 0\n\n# set the spatial_interval-event using the Spatial Travel Animation check box\n@app.callback(\n Output('spatial_interval-event', 'interval'), \n [Input('spatial_travel-check', 'values')],\n [State('spatial_interval-event', 'interval'), State('spatial_interval-event', 'n_intervals')]\n)\ndef change_spatial_travel_interval(checkedValues, interval, n):\n print(checkedValues, interval, n)\n if (len(checkedValues) != 0): return 2*1000 # AUTO is checked\n else: return 24*60*60*1000 # AUTO is not checked\n\n############################################################ \n\n\n\n############################################################\n\n@app.callback(\n Output('choropleth-graph', 'figure'),\n [Input('type_data_selector', 'value'),\n Input('timeseries-graph','hoverData'),\n Input('years-slider','value'), \n Input('spatial_interval-event', 'n_intervals')],\n [State('spatial_travel-check', 'values')],\n)\ndef update_map(type_data, year_hovered, year_selected_slider, n, checkedValues):\n \n if type_data == 'raw': \n df_map = df_map_raw\n rk_map = rk_map_raw\n title_map = '(Raw)'\n \n else:\n df_map = df_map_pcr\n rk_map = rk_map_pcr\n title_map = '(PCR)'\n \n if year_hovered is None: \n year = year_selected_slider\n \n else:\n year = year_hovered['points'][0]['x']\n\n heading = 'Income of US by State in ' + str(year)\n ranking = -1\n if (len(checkedValues) != 0):\n ranking = n % len(df_map[str(year)]) + 1\n msg = str(ranking) + 'th'\n if (ranking == 1): msg = '1st'\n if (ranking == 2): msg = '2nd'\n if (ranking == 3): msg = '3rd'\n for i, rank in enumerate(rk_map[str(year)]):\n if (rank == ranking): msg += ' ' + rk_map['STATE_NAME'][i] + ': {0:.2f}'.format(df_map[str(year)][i])\n heading += '
(' + msg + ')'\n \n scl = [[0.0, '#eff3ff'],[0.2, '#c6dbef'],[0.4, '#9ecae1'],[0.6, '#6baed6'],[0.8, '#3182bd'],[1.0, '#08519c']]\n scl2 = [[0.0, '#ffffff'],[1.0, '#FFFF00']]\n\n Choropleth_Data = [ dict(\n type='choropleth',\n colorscale = scl,\n autocolorscale = False,\n locations = df_map['STATE_ABBR'],\n z = df_map[str(year)],\n locationmode = 'USA-states',\n text = df_map['Name'],\n marker = dict(\n line = dict (\n color = 'rgb(255,255,255)',\n width = 1\n ) ),\n colorbar = dict(\n thickness = 10, # default: 30 \n title = title_map)\n ) ]\n \n Choropleth_Layout = dict(\n #title = 'Income of US by State in 1929
(Hover for breakdown)',\n title = heading,\n geo = dict(\n scope='usa',\n projection=dict( type='albers usa' ),\n showlakes = True,\n lakecolor = 'rgb(255, 255, 255)'),\n )\n Choropleth = {\n 'data': Choropleth_Data,\n 'layout': Choropleth_Layout\n }\n\n if (ranking > 0):\n Choropleth_highlighted = [ dict(\n type='choropleth',\n colorscale = scl2,\n autocolorscale = False,\n locations = df_map['STATE_ABBR'],\n z = [1 if i == ranking else 0 for i in rk_map[str(year)]],\n showscale = False,\n locationmode = 'USA-states',\n text = df_map['Name'],\n marker = dict(\n opacity = 0.5,\n line = dict (\n color = 'rgb(255,255,255)',\n width = 0\n ) ),\n ) ]\n Choropleth = {\n 'data': Choropleth_Data + Choropleth_highlighted,\n 'layout': Choropleth_Layout\n }\n\n return Choropleth\n\n############################################################\n\n# https://dash.plot.ly/interactive-graphing\n\n@app.callback(\n Output('scatter-graph', 'figure'),\n [Input('type_data_selector', 'value'),\n Input('timeseries-graph','hoverData'),\n Input('years-slider','value'),\n Input('choropleth-graph','selectedData'),\n Input('choropleth-graph','clickData')])\ndef update_scatter(type_data, year_hovered, year_selected_slider, states_selected_choropleth, state_clicked_choropleth):\n \n if type_data == 'raw': \n df_map = df_map_raw\n \n else:\n df_map = df_map_pcr\n \n if ((states_selected_choropleth is None) & (state_clicked_choropleth is None)):\n state_selected = 'California'\n \n elif ((states_selected_choropleth is None) & (state_clicked_choropleth is not None)):\n state_selected = str(state_clicked_choropleth['points'][0]['text'])\n \n else:\n state_selected = [i['text'] for i in states_selected_choropleth['points']]# state_selected_choropleth['points'][0]['text']\n \n if year_hovered is None: \n year = year_selected_slider\n \n else:\n year = year_hovered['points'][0]['x']\n \n #df_map[str(year)] = [48,2,3,4,5,6,7,8,9,60,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,1]\n\n print(df_map[str(year)])\n VarLag = ps.lag_spatial(W, df_map[str(year)])\n Var = df_map[str(year)]\n\n states = np.array(df_map['Name'])\n colors = np.where(np.isin(states, state_selected), '#FF0066', '#0066FF')\n \n b,a = np.polyfit(Var, VarLag, 1)\n line0 = { 'x':[min(Var), max(Var)], 'y': [a + i * b for i in [min(Var), max(Var)]] }\n\n Scatter_Data = [\n {\n 'x': Var, \n 'y': VarLag,\n 'mode': 'markers',\n 'marker': {'size': 10,\n 'color': colors},\n 'name': str(year),\n 'text': df_map['Name']},\n {\n 'x': line0['x'], \n 'y': line0['y'],\n 'mode': 'lines',\n 'line': {'color': '#009999'},\n 'name': 'Reg'}\n ]\n if (states_selected_choropleth is not None):\n var = [v['z'] for v in states_selected_choropleth['points']]\n varLag = [VarLag[v['pointIndex']] for v in states_selected_choropleth['points']]\n b,a = np.polyfit(var, varLag, 1)\n line1 = { 'x':[min(Var), max(Var)], 'y': [a + i * b for i in [min(Var), max(Var)]] }\n line2 = { 'x':[min(var), max(var)], 'y': [a + i * b for i in [min(var), max(var)]] }\n\n # recalculation line1 to fit scatter-graph area # y = a * x + b\n minVar = min(Var)\n maxVar = max(Var)\n aa = (line1['y'][1] - line1['y'][0]) / (line1['x'][1] - line1['x'][0])\n bb = line1['y'][0] - aa * line1['x'][0]\n if (line1['y'][0] > max(VarLag)): minVar = (line0['y'][1] - bb) / aa # x = ( y - b ) / a\n if (line1['y'][0] < min(VarLag)): minVar = (line0['y'][0] - bb) / aa # x = ( y - b ) / a\n if (line1['y'][1] > max(VarLag)): maxVar = (line0['y'][1] - bb) / aa # x = ( y - b ) / a\n if (line1['y'][1] < min(VarLag)): maxVar = (line0['y'][0] - bb) / aa # x = ( y - b ) / a\n line1 = { 'x':[minVar, maxVar], 'y': [a + i * b for i in [minVar, maxVar]] }\n\n #print(var)\n Scatter_Data.append(\n \t{\n \t\t'x': line1['x'], \n 'y': line1['y'],\n 'mode': 'lines', \n #'line': {'color': '#FF6600'},\n 'line': {'color': '#0000FF'},\n 'name': 'Reg'}\n )\n Scatter_Data.append(\n \t{\n \t\t'x': line2['x'], \n 'y': line2['y'],\n 'mode': 'lines', \n 'line': {'color': '#FF0000'},\n 'name': 'Reg'}\n )\n \n Scatter_Layout = {\n 'xaxis': {'title': 'Original Variable'},\n 'yaxis': {'title': \"Lagged Variable\"},\n 'showlegend': False,\n 'title': 'Scatterplot for {}
{} highlighted'.format(year, state_selected)\n }\n \n Scatter = {\n 'data': Scatter_Data,\n 'layout': Scatter_Layout\n }\n return Scatter\n\n############################################################\n \n\n@app.callback(\n Output('timeseries-graph', 'figure'),\n [Input('timeseries-graph','hoverData'),\n Input('years-slider', 'value')],\n [State('years-slider', 'min')]\n)\ndef update_TimeSeries(year_hovered, year_selected_slider, minValue):\n \n if year_hovered is None: \n theIDX = year_selected_slider - minValue\n \n else:\n theIDX = year_hovered['points'][0]['x'] - minValue\n \n TimeSeries_Data = [\n {\n 'x': years, \n 'y': morans,\n 'mode': 'lines', \n 'name': 'Moran\\'s I'\n },\n {\n 'x': [years[theIDX]], \n 'y': [morans[theIDX]],\n 'mode': 'markers', \n 'marker': {'size': 10},\n 'name': 'Moran\\'s I',\n 'showlegend': False,\n 'hoverinfo': 'none'\n } # To supress the tooltip\n ] \n\n TimeSeries_Choropleth_Layout = {\n 'xaxis': {'title': 'Years'},\n 'yaxis': {'title': \"Moran's I\"}\n }\n \n TimeSeries = {\n 'data': TimeSeries_Data,\n 'layout': TimeSeries_Choropleth_Layout\n }\n \n return TimeSeries\n\n\n#################################################################\n\n\n\n@app.callback(\n Output('boxplot-graph', 'figure'),\n [Input('type_data_selector', 'value'),\n Input('timeseries-graph','hoverData'),\n Input('choropleth-graph','selectedData'),\n Input('years-slider','value')])\ndef update_boxplot(type_data, year_hovered, states_selected_choropleth, year_selected_slider):\n \n if type_data == 'raw': \n df_map = df_map_raw\n \n else:\n df_map = df_map_pcr\n\n selected = []\n if ((states_selected_choropleth is None)):\n state_selected = 'California'\n else:\n state_selected = [i['text'] for i in states_selected_choropleth['points']]\n selected = [i['pointIndex'] for i in states_selected_choropleth['points']]\n \n if year_hovered is None: \n year = year_selected_slider\n \n else:\n year = year_hovered['points'][0]['x']\n\n #states = np.array(df_map['Name'])\n #colors = np.where(np.isin(states, state_selected), '#FF0066', '#0066FF')\n \n trace0 = go.Box(\n y = df_map[str(year)],\n name = 'Boxplot of the variable',\n boxpoints='all', # Show the underlying point of the boxplot\n jitter=0.15, # Degree of fuzziness\n pointpos=0, # Adjust horizontal location of point\n #marker = dict(color = '#FF0066'),\n line = dict(color = '#444'),\n selected = dict(marker = dict(color = '#FF0066')),\n unselected = dict(marker = dict(color = '#0066FF', opacity = 1.0)),\n selectedpoints = selected,\n )\n BoxPlot_Data = [trace0]\n #print(BoxPlot_Data)\n \n BoxPlot = {\n 'data': BoxPlot_Data,\n 'layout': {'title': 'Boxplot of the year {}'.format(str(year))}\n } \n return BoxPlot\n\n \n\n\n############################################################\n\n\n@app.callback(\n Output('timepath-graph', 'figure'),\n [Input('type_data_selector', 'value'),\n Input('choropleth-graph','clickData')])\ndef update_timepath(type_data, state_clicked):\n \n if type_data == 'raw': \n df_map = df_map_raw\n \n else:\n df_map = df_map_pcr\n \n if state_clicked is None: \n chosen_state = 'California'\n \n else:\n chosen_state = str(state_clicked['points'][0]['text'])\n \n def calculate_lag_value(x):\n return ps.lag_spatial(W, x)\n \n all_lagged = df_map[cols_to_calculate].apply(calculate_lag_value)\n \n state_row_index = list(df_map['Name']).index(chosen_state)\n \n VarLag = all_lagged.iloc[state_row_index,:]\n Var = df_map[cols_to_calculate].iloc[state_row_index,:]\n \n TimePath_Data = [\n {\n 'x': Var, \n 'y': VarLag,\n 'mode': 'markers',\n 'marker': {'size': 12},\n 'name': '',\n 'text': Var.index},\n {\n 'x': Var, \n 'y': VarLag,\n 'mode': 'lines', \n 'name': 'Path',\n 'hoverinfo': 'none'}\n ]\n \n TimePath_Layout = {\n 'xaxis': {'title': 'Original Variable'},\n 'yaxis': {'title': \"Lagged Variable\"},\n 'showlegend': False,\n 'title': 'Time-path for {}'.format(str(chosen_state))\n }\n \n TimePath = {\n 'data': TimePath_Data,\n 'layout': TimePath_Layout\n }\n return TimePath\n\n############################################################ \n\n\n\n\n@app.callback(\n Output('density-graph', 'figure'),\n [Input('type_data_selector', 'value'),\n Input('initial_years_dropdown','value'),\n Input('final_years_dropdown','value'),\n Input('choropleth-graph','clickData'),\n Input('spatial_interval-event', 'n_intervals')],\n [State('spatial_travel-check', 'values')])\ndef update_density(type_data, initial_year, final_year, state_clicked, n, checkedValues):\n \n if type_data == 'raw': \n df_map = df_map_raw\n rk_map = rk_map_raw\n \n else:\n df_map = df_map_pcr\n rk_map = rk_map_pcr\n \n \n pair_of_years = [initial_year, final_year]\n \n \n if state_clicked is None: \n chosen_state = 'California'\n \n else:\n chosen_state = str(state_clicked['points'][0]['text'])\n \n ranking = -1\n if (len(checkedValues) != 0):\n \tranking = n % len(df_map[str(year)]) + 1\n \n else:\n ranking = rk_map.loc[list(df_map['Name']).index(chosen_state), initial_year]\n \n state_row_index = list(rk_map[initial_year]).index(ranking)\n \n initial_state_value = df_map[initial_year][state_row_index]\n final_state_value = df_map[final_year][state_row_index]\n \n X1 = np.array(df_map[pair_of_years[0]])\n X2 = np.array(df_map[pair_of_years[1]])\n \n kde1 = stats.gaussian_kde(X1, bw_method = 'silverman')\n kde2 = stats.gaussian_kde(X2, bw_method = 'silverman')\n \n # Joint grid\n min_grid_aux = min(np.concatenate([X1, X2]))\n max_grid_aux = max(np.concatenate([X1, X2]))\n X_grid = np.linspace(min_grid_aux - 0.1 * abs(max_grid_aux), \n max_grid_aux + 0.1 * abs(max_grid_aux), \n 10000)\n \n dens1 = kde1.evaluate(X_grid)\n dens2 = kde2.evaluate(X_grid)\n \n Density_Data = [ # Densities traces\n {\n 'x': X_grid, \n 'y': dens1,\n 'mode': 'lines',\n 'fill': 'tozeroy',\n 'name': initial_year,\n 'text': 'Year of {}'.format(initial_year),\n 'line': {'color': '#AAAAFF',\n 'width': 3}},\n {\n 'x': X_grid, \n 'y': dens2,\n 'mode': 'lines',\n 'fill': 'tozeroy',\n 'name': final_year,\n 'text': 'Year of {}'.format(final_year),\n 'line': {'color': '#FF0000',\n 'width': 3}},\n \n \n # Segments of lines traces\n {\n 'x': [initial_state_value, initial_state_value], # x-values of each point do draw a line\n 'y': [0, kde1.evaluate(initial_state_value)[0]], # Extract only the value from an array: https://stackoverflow.com/questions/21030621/how-to-extract-value-from-a-numpy-ndarray\n 'mode': 'lines',\n 'name': 'name_to_put',\n 'text': 'text_to_put_line',\n 'showlegend': False,\n 'line': {'color': '#AAAAFF',\n 'width': 3}},\n {\n 'x': [final_state_value, final_state_value], # x-values of each point do draw a line\n 'y': [0, kde2.evaluate(final_state_value)[0]],\n 'mode': 'lines',\n 'name': 'name_to_put_line',\n 'text': 'text_to_put_line',\n 'showlegend': False,\n 'line': {'color': '#FF0000',\n 'width': 3}}\n \n ]\n \n Density_Layout = {\n 'xaxis': {'title': 'Original Variable'},\n 'yaxis': {'title': \"Density Estimation\"},\n 'title': '{} locations in densities for {} and {}'.format(chosen_state, initial_year, final_year)\n }\n \n Density = {\n 'data': Density_Data,\n 'layout': Density_Layout\n }\n return Density\n\n############################################################ \n'''\n\n\nif __name__ == '__main__':\n #app.run_server() # ,port=8055 debug=True,port=8000, host='0.0.0.0'\n\ti = 0","sub_path":"web/python/STARS_V2.py","file_name":"STARS_V2.py","file_ext":"py","file_size_in_byte":31141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"437140513","text":"import logging\nfrom importlib import metadata\nfrom pathlib import Path\n\nimport toml # tomllib is coming out on python 3.11 as standard lib\n\n\n# -- Version ----------------------\n__version__ = metadata.version(__name__)\n\n# -- Define logger and the associated formatter and handler -------------\nformatter = logging.Formatter(\n \"%(asctime)s [%(filename)s] %(levelname)s: %(message)s\", datefmt=\"%Y-%m-%d %H:%M:%S\"\n)\n\nhandler = logging.StreamHandler()\nhandler.setLevel(logging.INFO)\nhandler.setFormatter(formatter)\n\nlogger = logging.getLogger(\"tnpy\")\nlogger.setLevel(logging.INFO)\nlogger.addHandler(handler)\n\n\n# -- Load configurations from toml file ----------------------\nclass ConfigReader:\n def __init__(self, file):\n self.__dict__.update(**toml.load(file))\n\n\nwith open(Path(__file__).absolute().parent / \"config.toml\", \"r\", encoding=\"utf-8\") as f:\n config = ConfigReader(f)\n","sub_path":"tnpy/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"332293927","text":"# -*- coding: utf-8 -*-\nfrom datetime import timedelta\nfrom celery.schedules import crontab\n# Broker and Backend\nBROKER_URL = 'pyamqp://guest@localhost//'\n#CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'\n# Timezone\nCELERY_TIMEZONE = 'Asia/Shanghai' # 指定时区,不指定默认为 'UTC'\n# CELERY_TIMEZONE='UTC'\n# import\nCELERY_IMPORTS = (\n 'celery_app.tongcheng_worker'\n)\n\nCELERY_ANNOTATIONS = {\n 'celery_app.task1.hotel_message_fetch': {'rate_limit': '100/m'},\n 'celery_app.task1.hotel_price': {'rate_limit': '100/m'},\n 'celery_app.task1.hotel_ids_fetch': {'rate_limit': '30/m'},\n 'celery_app.task1.get_hotel_info_increment': {'rate_limit': '5000/m'}\n}\n\nCELERYD_TASK_TIME_LIMIT = 60\n\n# CELERYBEAT_SCHEDULE = {\n# 'add-every-600-seconds': {\n# 'task': 'celery_app.task1.token_fetch',\n# 'schedule': timedelta(seconds=10), # 每 10 分钟执行一次\n# # 'options': {'queue': \"schedule\"} # 配置队列\n# }\n# }\n","sub_path":"local/celery/celery_tongcheng/celery_app/celeryconfig.py","file_name":"celeryconfig.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"482350915","text":"def str_to_time(time_str, now=None):\n peeked = time_str[:1]\n if peeked.isdigit():\n from calendar import timegm\n from dateutil.parser import parse as parse_fuzzy\n rv = parse_fuzzy(time_str)\n rv = rv.utctimetuple()\n rv = timegm(rv)\n else:\n if now is None:\n from time import time\n now = time()\n if peeked == r'+':\n sign = 1\n elif peeked == r'-':\n sign = -1\n else:\n raise ValueError(time_str)\n rv = now + sign * _offset(time_str[1:])\n return rv\n\n\ndef _offset(time_str):\n from .str.split_to_at_most_nitems import split_to_at_most_nitems\n from datetime import timedelta\n day, time = split_to_at_most_nitems(time_str, 2, r'T', r'0')\n day = int(day)\n hour, min_, sec = map(int, split_to_at_most_nitems(time, 3, r':', r'0'))\n sec += 60 * (60 * hour + min_)\n delta = timedelta(days=day, seconds=sec)\n return delta.total_seconds() + delta.microseconds\n","sub_path":"x19290/str_to_time.py","file_name":"str_to_time.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"350620752","text":"d = 0\ndef util(root):\n if root == None:\n return 0\n global d\n l = util(root.left)\n r = util(root.right)\n d = max(d, l+r+1)\n return 1 + max(l, r)\n \ndef diameter(root):\n global d\n d = 0\n util(root)\n return d\n\nfrom collections import deque\nimport sys\nsys.setrecursionlimit(50000)\n# Tree Node\nclass Node:\n def __init__(self, val):\n self.right = None\n self.data = val\n self.left = None\n\n# Function to Build Tree \ndef buildTree(s):\n #Corner Case\n if(len(s) == 0 or s[0] == \"N\"): \n return None\n \n # Creating list of strings from input \n # string after spliting by space\n ip = list(map(str,s.split()))\n \n # Create the root of the tree\n root = Node(int(ip[0])) \n size = 0\n q = deque()\n \n # Push the root to the queue\n q.append(root) \n size = size+1 \n \n # Starting from the second element\n i = 1 \n while(size > 0 and i < len(ip)):\n # Get and remove the front of the queue\n currNode = q[0]\n q.popleft()\n size = size-1\n \n # Get the current node's value from the string\n currVal = ip[i]\n \n # If the left child is not null\n if(currVal != \"N\"):\n \n # Create the left child for the current node\n currNode.left = Node(int(currVal))\n \n # Push it to the queue\n q.append(currNode.left)\n size = size+1\n # For the right child\n i = i+1\n if(i >=len(ip)):\n break\n currVal = ip[i]\n \n # If the right child is not null\n if(currVal != \"N\"):\n \n # Create the right child for the current node\n currNode.right = Node(int(currVal))\n \n # Push it to the queue\n q.append(currNode.right)\n size = size+1\n i = i+1\n return root\n \n \nif __name__==\"__main__\":\n t = int(input('Enter the number of test cases:- '))\n for _ in range(0,t):\n s = input('Enter the elements of the tree:- ')\n root = buildTree(s)\n k = diameter(root)\n print(k)","sub_path":"Placement Prepration/Tree/diameter_of_binary_tree.py","file_name":"diameter_of_binary_tree.py","file_ext":"py","file_size_in_byte":2250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"547893373","text":"import qiskit\nfrom qiskit import IBMQ\nfrom qiskit import Aer\nfrom qiskit.tools.visualization import plot_histogram\nimport matplotlib as mpl\nmpl.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\n\nclear = False\n\nif clear and not IBMQ.stored_account() is None:\n IBMQ.delete_account()\n print(\"Account cleared!\")\ntoken = \"746644d897c000cb3df3ad4207ab3b892563771823df485921c9f6f5159b86fa0da28e1789e0f9da7a88b181a250e8be8bcd89881747518113174a88e00638be\"\nIBMQ.save_account(token, overwrite=True)\nIBMQ.load_account()\nprint(\"IBMQ providers list\")\nprint(IBMQ.providers())\nprovider = IBMQ.get_provider(hub=\"ibm-q\")\nprint(\"\\nand here available backends on IBM hq (sw emulator or IBM Q computer\")\nprint((provider.backends()))\nprint(\"\\nand here local backend given by Aer\")\nprint(Aer.backends())\nbackend = provider.get_backend(\"ibmq_qasm_simulator\")\n\nq = qiskit.QuantumRegister(5)\nc = qiskit.ClassicalRegister(5)\nqc = qiskit.QuantumCircuit(q, c)\nqc.measure_all()\njob = qiskit.execute(qc, backend=backend)\nplot_histogram(job.result().get_counts(qc))\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"121209398","text":"def level_decomposition(graph):\n no_tops=len(graph)\n levels = [0]*no_tops\n degree = [0]*no_tops\n not_marked_top = []\n marked_top = []\n successor = []\n # Remplissage des degrés\n for i in range(0,no_tops):\n for j in range(0,no_tops):\n if(graph[i][j] != float('Inf')):\n degree[j]+=1\n\n # Remplissage de L\n for i in range(0,no_tops):\n if (degree[i]==0) and (i not in marked_top) :\n not_marked_top.append(i)\n\n\n while(len(not_marked_top)>0): # Pour chaque x\n # not_marked_top[0] -> x\n # successor[0] -> y\n\n # Remplissage des successeurs\n for i in range(0,no_tops):\n if graph[not_marked_top[0]][i] != float('Inf'):\n successor.append(i)\n \n while(len(successor)>0): # Pour chaque y\n if levels[successor[0]]50:\n c='0.9'\n else:\n c='black'\n ax.text(x+0.5,y +0.5,'%.1f%%' % val,horizontalalignment='center',verticalalignment='center',color=c,fontsize=6)\nif confusionMatrixFigFileName.lower() in [\"none\",\"false\",\"default\"]:\n confusionMatrixFigFileName='confusionmatrix.pdf'\nplt.savefig('/'.join((resultsDir+'/'+confusionMatrixFigFileName).split('//')),bbox_inches='tight',dpi=600)\n\nsys.stderr.write(\"total time spent testing classifier stored in %s on feature vector sets in %s: %f secs\\n\" %(classifierPickleFileName,fvecDir,(time.clock()-startTime)))\n\n","sub_path":"testing_deep_learning_classify.py","file_name":"testing_deep_learning_classify.py","file_ext":"py","file_size_in_byte":5936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"81315594","text":"from xbot._core import robot\nimport os, ctypes\nimport threading\nimport time\nimport argparse\nimport math\nfrom collections import namedtuple\n\ncmd_parser = argparse.ArgumentParser(allow_abbrev=True)\ncmd_parser.add_argument('--disable-block-progress', type=bool, required=False)\ncmd_args, _ = cmd_parser.parse_known_args()\ndisable_block_progress = cmd_args.disable_block_progress\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n\ndef excel_column_name_to_index(column_name):\n \"\"\"Excel列名称转列索引,从1开始\"\"\"\n if not column_name.isalpha():\n raise ValueError(f'列名\"{column_name}\"名称不合法!') \n\n index = 0\n for li, ln in enumerate(column_name[::-1]):\n if li == 0:\n index = index + ord(ln)-64\n else:\n index = index + math.pow(26, li) * (ord(ln)-64)\n return int(index)\n\n\ndef excel_column_index_to_name(col_index):\n \"\"\"Excel列索引转列名称,从1开始\"\"\"\n result = []\n while col_index:\n col_index, rem = divmod(col_index-1, 26)\n result[:0] = LETTERS[rem]\n return ''.join(result)\n\n\ndef parsesudoku_from_args(args, key, default='middleCenter') -> str:\n return args.get(key, default)\n\n\ndef parseint_from_args(args, key, default=0):\n value = args.get(key, default)\n if isinstance(value, int):\n return value\n elif isinstance(value, str):\n try:\n return int(value.strip())\n except ValueError:\n raise ValueError(f'参数{key}类型错误, 必须为整数类型')\n else:\n raise ValueError(f'参数{key}类型错误, 必须为整数类型')\n\n\ndef parsefloat_from_args(args, key, default=0):\n value = args.get(key, default)\n if isinstance(value, (int, float)):\n return value\n elif isinstance(value, str):\n try:\n return float(value.strip())\n except ValueError:\n raise ValueError(f'参数{key}类型错误, 必须为数字类型')\n else:\n raise ValueError(f'参数{key}类型错误, 必须为数字类型')\n\n\ndef visual_action(func):\n def wrapper(**kwargs):\n inputs = {}\n try:\n if kwargs is not None:\n\n # 通知Block进度\n if not disable_block_progress:\n # (\"main\", 4, \"打开网页\")\n block_info = kwargs.pop('_block', None)\n if block_info is not None:\n _progress.report(block_info)\n\n for key, value in kwargs.items():\n if _isalambda(value):\n inputs[key] = value() # calc lambda\n else:\n inputs[key] = value\n return func(**inputs)\n except Exception as e:\n if inputs.get('_ignore_exception', 'False') == 'True':\n print(f'{e}')\n else:\n raise e\n finally:\n pass\n return wrapper\n\n# python dict 转 python object\n# object通过.来访问属性, dict通过['']来访问key\ndef dict_to_object(typename, d):\n return namedtuple(typename, d.keys())(*d.values())\n\n\n\ndef _isalambda(v):\n return callable(v) and v.__name__ == ''\n\ndef _expand_path(path):\n '''\n 功能:将path中的环境变量替换成实际路径\n '''\n ret_path = ctypes.create_unicode_buffer(1024)\n ctypes.windll.Kernel32.ExpandEnvironmentStringsW(path, ret_path, 1024)\n return ret_path.value\n\nclass _Progress(object):\n \"\"\" 实现Flow进度通知功能\n 通知Flow改变Block状态,为了防止刷新过于频繁,这里通过timer降低频率\n \"\"\"\n\n def __init__(self):\n self._block_info = None\n self._thread = threading.Thread(target=self._monitor, daemon=True)\n self._thread.start()\n\n def report(self, block_info):\n self._block_info = block_info\n\n def _monitor(self):\n while True:\n block_info = self._block_info\n self._block_info = None\n if block_info is not None:\n robot.execute(f'Progress.HitBlock', {\n 'flowName': block_info[0], 'line': block_info[1], 'blockTitle': block_info[2]})\n time.sleep(0.5)\n\n\n_progress = _Progress()\n\nclass Rectangle(object):\n '''\n 元素位置信息\n self, left, top, right, bottom, center_x, center_y, width, height\n '''\n def __init__(self, left, top, right, bottom, center_x, center_y, width, height):\n self.left = left\n self.top = top\n self.right = right\n self.bottom = bottom\n self.center_x = center_x\n self.center_y = center_y\n self.width = width\n self.height = height\n","sub_path":"RPA/组件/ShadowBot/3.9.9/xbot_visual/_core.py","file_name":"_core.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134858879","text":"\"\"\"\nGiven an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].\n\nYou need to return the number of important reverse pairs in the given array.\n\nExample1:\n\nInput: [1,3,2,3,1]\nOutput: 2\nExample2:\n\nInput: [2,4,3,5,1]\nOutput: 3\nNote:\nThe length of the given array will not exceed 50,000.\nAll the numbers in the input array are in the range of 32-bit integer.\n\"\"\"\nimport bisect\nclass Solution:\n # BIT\n # update backward: every time updates an index, also update nodes with smaller \n # numbers since we are looking for larger values\n def reversePairs(self, nums):\n def update(index, bit):\n while index > 0:\n bit[index] += 1\n index -= index & -index\n\n def query(index, bit):\n s = 0\n while index < len(bit):\n s += bit[index]\n index += index & -index\n return s\n\n def get_index(n):\n return bisect.bisect_left(index_arr, n) + 1\n\n index_arr = sorted(nums)\n bit = [0] * (len(nums) + 1)\n count = 0\n for n in nums:\n count += query(get_index(2*n+1), bit)\n update(get_index(n), bit) \n return count\n \n # merge sort, tle\n def reversePairs2(self, nums):\n def merge(nums, lo, hi):\n mid = (lo + hi) // 2\n tmp = [0] * (hi-lo+1)\n i, j, k = lo, mid+1, 0\n while i <= mid or j <= hi:\n if i <= mid and (j > hi or nums[i] <= nums[j]):\n tmp[k] = nums[i]\n i += 1\n else:\n tmp[k] = nums[j]\n j += 1\n k += 1\n for i in range(lo, hi+1):\n nums[i] = tmp[i-lo]\n \n def merge_sort(nums, lo, hi):\n if lo >= hi:\n return 0\n mid = (lo + hi) // 2\n count = merge_sort(nums, lo, mid) + merge_sort(nums, mid+1, hi)\n\n for i in range(lo, mid+1):\n j = mid+1\n while j <= hi and nums[i] > 2*nums[j]:\n j += 1\n count += j - (mid+1) \n \n merge(nums, lo, hi)\n return count\n \n return merge_sort(nums, 0, len(nums)-1)\n\n #TLE, bisect\n def reversePairs2(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n arr = []\n count = 0\n for n in nums:\n index = bisect.bisect(arr, 2*n)\n count += len(arr) - index\n bisect.insort(arr, n)\n return count\n\ns = Solution()\nassert s.reversePairs([1,3,2,3,1]) == 2\nassert s.reversePairs([2,4,3,5,1]) == 3\nassert s.reversePairs([5,4,3,2,1]) == 4 \n","sub_path":"leetcode/reversePairs/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"184811685","text":"# -*- coding=utf-8\n'''\nCreated on 2016年9月23日\n\n@author: zhaol\n'''\nfrom majiang2.table_state_processor.processor import MProcessor\nfrom freetime.util import log as ftlog\nfrom majiang2.table_state.state import MTableState\nfrom majiang2.table.table_config_define import MTDefine\n\n\"\"\"\n加牌的操作处理,最对一个人\n分析\n1)摸牌,会有杠/胡两种情况\n2)吃/碰一张牌,之后主动出一张牌\n3)杠牌后,发一张牌,之后主动出一张牌\n\"\"\"\nclass MAddCardProcessor(MProcessor):\n def __init__(self):\n super(MAddCardProcessor, self).__init__()\n self.__tile = 0\n self.__state = MTableState.TABLE_STATE_NEXT\n self.__seatId = 0\n self.__extend_info = None\n self.__must_ting = False\n \n @property\n def extendInfo(self):\n \"\"\"扩展信息\"\"\"\n return self.__extend_info\n \n @property\n def state(self):\n \"\"\"获取本轮出牌状态\"\"\"\n return self.__state\n \n def getState(self):\n return self.__state\n \n def getTile(self):\n \"\"\"获取手牌\n \"\"\"\n return self.__tile\n \n @property\n def seatId(self):\n \"\"\"获取座位号\n \"\"\"\n return self.__seatId\n \n def getSeatId(self):\n return self.__seatId\n \n def getPlayer(self):\n \"\"\"获取玩家\"\"\"\n return self.players[self.__seatId]\n \n @property\n def mustTing(self):\n return self.__must_ting\n \n def setMustTing(self, mustTing):\n self.__must_ting = mustTing\n \n def reset(self):\n \"\"\"重置数据\"\"\"\n self.__tile = 0\n self.__state = MTableState.TABLE_STATE_NEXT\n self.__seatId = 0\n self.__extend_info = None\n self.__must_ting = False\n \n def initProcessor(self, actionID, state, seatId, tile, extendInfo, timeOut = 9):\n \"\"\"\n 初始化处理器\n 参数\n state - 状态集合,当前座位号可以做出的全部选择\n \"\"\"\n ftlog.debug('MAddCardProcessor.initProcessor actionID', actionID\n , ' state:', state\n , 'seatId:', seatId\n , ' tile:', tile\n , ' extendInfo:', extendInfo)\n self.setActionID(actionID)\n self.__state = state\n self.__seatId = seatId\n self.__tile = tile\n self.__extend_info = extendInfo\n self.setTimeOut(timeOut)\n \n def hasAutoDecideAction(self, curSeat, trustTeeSet):\n \"\"\"是否有托管可以处理的行为\"\"\"\n if self.__state == MTableState.TABLE_STATE_NEXT:\n return MTDefine.INVALID_SEAT\n \n if self.isUserAutoDecided(self.seatId, trustTeeSet, self.state):\n return self.__seatId\n \n return MTDefine.INVALID_SEAT\n \n def updateProcessor(self, actionID, state, seatId):\n \"\"\"\n 用户做出了选择\n 只有出牌一个解的时候,不能放弃,一定要出牌\n 参数\n state - 最终做出的选择\n 返回值:\n True - 动作有效\n False - 动作无效\n \"\"\"\n if actionID != self.actionID:\n ftlog.debug('MAddCardProcessor.updateProcessor actionId error...')\n return False\n \n if seatId != self.__seatId:\n return False\n \n if self.players[seatId].isTing() and (self.__state & MTableState.TABLE_STATE_HU):\n # 听牌状态,过胡,充值processor,后台自动替玩家打出当前的牌\n self.reset()\n return True\n\n if not (state & self.__state):\n ftlog.debug('MAddCardProcessor.updateProcessor state not match... processorState:', self.state\n , ' updateState:', state)\n return False\n \n self.reset()\n return True\n \n","sub_path":"majiang2/src/majiang2/table_state_processor/add_card_processor.py","file_name":"add_card_processor.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"355025467","text":"from ds_format.cmd import UsageError\nimport ds_format as ds\nimport aquarius_time as aq\n\ndef pretty(x, var):\n\tif var.get('units_comment') == 'julian_date(utc)':\n\t\treturn aq.to_datetime(x).strftime('%Y-%m-%dT%H:%M:%S')\n\treturn str(x)\n\ndef cat(vars_, *input_, **opts):\n\tif not isinstance(vars_, list):\n\t\tvars_ = [vars_]\n\tfor filename in input_:\n\t\td = ds.read(filename, vars_,\n\t\t\tfull=False,\n\t\t\tjd=(opts.get('jd') or opts.get('h')),\n\t\t)\n\t\tvarsx = [x for x in d.keys() if not x.startswith('.')]\n\t\tif len(varsx) == 0:\n\t\t\treturn\n\t\tdims0 = d['.'][varsx[0]]['.dims']\n\t\tfor var in varsx:\n\t\t\tdims = d['.'][var]['.dims']\n\t\t\tif dims != dims0:\n\t\t\t\traise ValueError('incompatible dimensions')\n\t\tn = d[vars_[0]].flatten().shape[0]\n\t\tfor i in range(n):\n\t\t\tif opts.get('h'):\n\t\t\t\ts = ','.join([pretty(d[var].flatten()[i], d['.'][var]) for var in vars_])\n\t\t\telse:\n\t\t\t\ts = ','.join([str(d[var].flatten()[i]) for var in vars_])\n\t\t\tprint(s)\n","sub_path":"ds_format/cmd/cat.py","file_name":"cat.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"424914090","text":"import utilities.paths as paths\nimport keras_code.models as models\nfrom keras_code.predict import predict\nfrom evaluation.metrics import score\nfrom scipy import spatial\nimport numpy as np\nimport math\nfrom keras import backend as K\nfrom random import randint\nimport datasets.dataset_reader\nfrom PIL import Image, ImageFont, ImageDraw\nimport os\nimport pickle\nDRIVE = paths.get_drive()\n\n\ncolours = [[100, 100, 100], [35, 118, 211], [34, 190, 204], [191, 185, 31], [79, 180, 30], [31, 31, 191],\n [160, 26, 26], [100, 200, 0], [200, 100, 0], [200, 0, 100], [0, 200, 100], [100, 0, 200], [0, 100, 200]]\n\n\ndo_frames = None # range(120000,140000)\n\nbreak_every = 5000\nscale = 4\nf_gap = 1\n\n\nmodel_id = 'MVK_60_01'\nmodel_id = 'MVSK_65_47'\nidentifier = '00001'\nmodel_path = DRIVE + 'MODELS/VISUAL/KERAS/'\nsplit = 'test'\nforce_noneq = True\nbatch_size = 16\nload_epoch = 1\nload_epoch = 2\nlayer_name = 'pred'\nsave_path = paths.get_drive(2) + 'DATASETS/VIDEO/TENNIS/VISUALISATIONS/' + model_id + '_' + identifier + '-e' + str(load_epoch) + '/' + layer_name + '/png/'\n\nmodel_path = model_path + model_id + '_' + identifier\nlabels_short = [' O','HNR','HNL','HFR','HFL','SN','SF']\ndataset = models.get_dataset(model_id, split, force_noneq=True, batch_size=batch_size)\ndataset.frame_order()\npredictions = {}\n# Check if preditions saved, if not, save them\npred_path = paths.get_drive(2) + 'DATASETS/VIDEO/TENNIS/FEATURES/' + model_id + '_' + identifier + '-e' + str(\n load_epoch) + '/' + layer_name + '/pkl/' + split + '.pkl'\ntest_stats_path = model_path + '/testing_stats-e'+str(load_epoch)+'-NE.npy'\nif os.path.exists(pred_path):\n predictions = pickle.load(open(pred_path, 'rb'), encoding='latin1')\nelif os.path.exists(test_stats_path):\n [Yne, Pne, Sne, labels] = np.load(test_stats_path) # S might not be in some old files\n for s in range(len(Sne)):\n predictions[Sne[s]] = {'gt': Yne[s], 'pred': Pne[s]}\nelse: # make some predictions\n print('Need to run predictions')\n feat_path = paths.get_drive(2) + 'DATASETS/VIDEO/TENNIS/FEATURES/'\n predict(model_id, identifier, model_path, split, batch_size, load_epoch, True, [layer_name], save_path=feat_path)\n\n\n # add events with text files we generated to test they are correct\n # gt = []\n # pr = []\n # for class_num in [0,1,2,3,4,5,6]:\n # event_txt_path = model_path + '/events_new/gt_events_1_c'+str(class_num)+'.txt'\n # with open(event_txt_path) as f:\n # lines = f.readlines()\n #\n # for line in lines:\n # gt.append(line.split())\n #\n # event_txt_path = model_path + '/events_new/pr_events_1.txt'\n # with open(event_txt_path) as f:\n # lines = f.readlines()\n #\n # for line in lines:\n # pr.append(line.split())\n #\n # for k in dataset.keys:\n # sid = dataset.get_data_key(k)\n #\n # gt_arr = [0]*7\n # for gtl in gt:\n # if sid.split('_')[0] == gtl[0]:\n # if int(sid.split('_')[1][1:]) >= int(gtl[1]):\n # if int(sid.split('_')[1][1:]) <= int(gtl[2]):\n # gt_arr[int(gtl[3])] = float(gtl[4])\n #\n # pr_arr = [0]*7\n # for prl in pr:\n # if sid.split('_')[0] == prl[0]:\n # if int(sid.split('_')[1][1:]) >= int(prl[1]):\n # if int(sid.split('_')[1][1:]) <= int(prl[2]):\n # pr_arr[int(prl[3])] = float(prl[4])\n #\n #\n # predictions[sid] = {'gt': np.asarray(gt_arr), 'pred':np.asarray(pr_arr)}\n #\n# for do_video in ['V006', 'V007', 'V008', 'V010']:\nfor do_video in ['V007']:\n # do_video = 'V006'\n c = 0\n av_preds = {}\n gt_evs = []\n pred_evs = []\n av_pred_evs = []\n img = np.ones((60 * scale, 1 * scale, 3), dtype=np.uint8) * 255\n for k in dataset.keys:\n sid = dataset.get_data_key(k)\n\n if do_video is not None:\n if not sid.split('_')[0] == do_video:\n continue\n if do_frames is not None:\n if int(sid.split('_')[1][1:]) not in do_frames:\n continue\n\n if sid in predictions.keys():\n gt = predictions[sid]['gt']\n gt_i = int(np.argmax(gt))\n pred = predictions[sid][layer_name]\n pred_i = int(np.argmax(pred))\n\n if c > 0:\n imgn = np.ones((60*scale, (c+1)*scale, 3), dtype=np.uint8) * 255\n imgn[:,:c*scale,:] = img\n img=imgn\n img[5*scale:10*scale, f_gap+(c-1)*scale:c*scale, :] = colours[gt_i]\n # img[20*scale, :, :] = [30,30,30]\n if gt_i == pred_i:\n img[31*scale:32*scale, f_gap+(c-1)*scale:c*scale, :] = [105,239,79]\n img[20 * scale:30 * scale, (c - 1) * scale:c * scale, :] = [220, 255, 220]\n else:\n img[31 * scale:32 * scale, f_gap + (c - 1) * scale:c * scale, :] = [239, 105, 79]\n img[20 * scale:30 * scale, (c - 1) * scale:c * scale, :] = [255, 220, 220]\n img[int((20+(10-10*pred[pred_i]))*scale):30*scale, f_gap+(c-1)*scale:c*scale, :] = colours[pred_i]\n\n\n # smooth by mean pooling over frames\n w = 40\n cf = int(sid.split('_')[1][1:])\n av_c = 0\n av = 0\n for t in range(cf - int(math.floor(w / 2.0)), 1 + cf + int(math.floor(w / 2.0))):\n t_sid = \"%s_F%08d\" % (sid.split('_')[0], t)\n if t_sid in predictions.keys():\n av += predictions[t_sid][layer_name]\n av_c += 1\n\n av_preds[sid] = av / av_c\n av_pred_i = int(np.argmax(av_preds[sid]))\n\n # join frames into events\n # img[40*scale, :, :] = [30,30,30]\n\n if gt_i == av_pred_i:\n img[51*scale:52*scale, f_gap+(c-1)*scale:c*scale, :] = [105,239,79]\n img[40 * scale:50 * scale, (c - 1) * scale:c * scale, :] = [220, 255, 220]\n else:\n img[51 * scale:52 * scale, f_gap + (c - 1) * scale:c * scale, :] = [239, 105, 79]\n img[40 * scale:50 * scale, (c - 1) * scale:c * scale, :] = [255, 220, 220]\n\n\n img[int((40+(10-10*av_preds[sid][av_pred_i]))*scale):50*scale, f_gap+(c-1)*scale:c*scale, :] = colours[av_pred_i]\n\n\n\n if gt_i == av_pred_i:\n img[51*scale:52*scale, f_gap+(c-1)*scale:c*scale, :] = [105,239,79]\n else:\n img[51 * scale:52 * scale, f_gap + (c - 1) * scale:c * scale, :] = [239, 105, 79]\n\n\n if c == 0:\n cur_gt_ev = [gt_i, c, c]\n cur_pr_ev = [pred_i, c, c]\n cur_avpr_ev = [av_pred_i, c, c]\n else:\n if gt_i != cur_gt_ev[0]:\n cur_gt_ev[2] = c-1\n gt_evs.append(cur_gt_ev)\n cur_gt_ev = [gt_i, c, c]\n if pred_i != cur_pr_ev[0]:\n cur_pr_ev[2] = c-1\n pred_evs.append(cur_pr_ev)\n cur_pr_ev = [pred_i, c, c]\n if av_pred_i != cur_avpr_ev[0]:\n cur_avpr_ev[2] = c-1\n av_pred_evs.append(cur_avpr_ev)\n cur_avpr_ev = [av_pred_i, c, c]\n\n c += 1\n\n img = Image.fromarray(np.uint8(img))\n # print(gt_evs)\n for gev in gt_evs:\n overlap = 0\n\n font = ImageFont.truetype(\"DroidSans.ttf\", 16)\n # draw.text((x, y),\"Sample Text\",(r,g,b))\n draw = ImageDraw.Draw(img)\n text = \"%s\" % (labels_short[gev[0]])\n text = \"%s\" % (labels_short[gev[0]])\n draw.text((int(np.mean(gev[1:3])*scale)-15, 11*scale), text, (colours[gev[0]][0],colours[gev[0]][1],colours[gev[0]][2]), font=font)\n\n for pev in pred_evs:\n overlap = 0\n if pev[2]-pev[1]>5:\n for i in range(len(gt_evs)):\n tev = gt_evs[i]\n tov = len(range(max(pev[1], tev[1]), min(pev[2], tev[2])+1))\n if tov > overlap and pev[0] == tev[0]:\n gev = tev\n overlap = tov\n\n pev.append(gev[1])\n pev.append(gev[2])\n union = len(range(min(pev[1], gev[1]), max(pev[2], gev[2])+1))\n if union > 0:\n iou = float(overlap) / union\n else:\n iou = 0\n font = ImageFont.truetype(\"DroidSans.ttf\", 16)\n # draw.text((x, y),\"Sample Text\",(r,g,b))\n draw = ImageDraw.Draw(img)\n text = \"%.3f\" % (iou)\n draw.text((int(np.mean(pev[1:3])*scale)-20, 34*scale), text, (colours[pev[0]][0],colours[pev[0]][1],colours[pev[0]][2]), font=font)\n\n for pev in av_pred_evs:\n overlap = 0\n for i in range(len(gt_evs)):\n tev = gt_evs[i]\n tov = len(range(max(pev[1], tev[1]), min(pev[2], tev[2])+1))\n if tov > overlap and pev[0] == tev[0]:\n gev = tev\n overlap = tov\n\n pev.append(gev[1])\n pev.append(gev[2])\n union = len(range(min(pev[1], gev[1]), max(pev[2], gev[2])+1))\n if union > 0:\n iou = float(overlap) / union\n else:\n iou = 0\n font = ImageFont.truetype(\"DroidSans.ttf\", 16)\n # draw.text((x, y),\"Sample Text\",(r,g,b))\n draw = ImageDraw.Draw(img)\n text = \"%.3f\" % (iou)\n draw.text((int(np.mean(pev[1:3])*scale)-20, 54*scale), text, (colours[pev[0]][0],colours[pev[0]][1],colours[pev[0]][2]), font=font)\n\n\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n img = np.array(img)\n for i in range(c):\n if i % break_every == 0:\n imgf = Image.fromarray(img[:,i:i+break_every,:])\n imgs = imgf.save(save_path + split + '_' + do_video + '_' + str(i) +'.png')","sub_path":"visualisations/timeline_imgs.py","file_name":"timeline_imgs.py","file_ext":"py","file_size_in_byte":9558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"161551966","text":"class Util:\r\n\t_DEBUG = TRUE\r\n\t\r\n\t@staticmethod\r\n\tdef bytes2numL(data, offset, length):\r\n\t\tnum = 0\r\n\t\t_data = data[offset:offset+length-1]\r\n\t\tfor i in _data:\r\n\t\t\tnum += _data[len(_data)-i-1]\r\n\t\t\tif i < len(_data) - 1:\r\n\t\t\t\tnum = num << 8\r\n\t\treturn num\r\n\t\r\n\tdef dprint(msg):\r\n\t\tif _DEBUG:\r\n\t\t\tprint(msg)\r\n","sub_path":"KeyServerAP/Util.py","file_name":"Util.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"112528166","text":"\r\n#B_IA --> Motor B PWM Spdr.forward()eed\r\n#B_IB --> Motor B Direction \r\n\r\n## Left\r\n# m1 = MotorDC(13,12)\r\n## Right \r\n# m2 = MotorDC(5,23)\r\n\r\ndr = L9110URA(13,12,5,23) \r\n\r\ndr.forward()\r\n\r\ndr.backward() \r\n\r\ndr.stop() \r\n\r\ndr.trunLeft() \r\n\r\ndr.turnRight() \r\n","sub_path":"devs/SpeedControl/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"220886191","text":"#!/usr/bin/python3\n\nimport os\nimport pyperclip\n\nfiles = []\n\nfor r, d, f in os.walk('./'):\n for file in f:\n if file.endswith('.hpp') or file.endswith('.cpp'):\n files.append(\n '\"${GX_ENGINE_SRC_DIR}' +\n r[2:].replace('\\\\', '/') +\n '/' +\n file +\n '\"')\n\nfiles.sort()\n\nfiles_text = ''\n\nfor f in files:\n files_text += f + '\\n'\n\npyperclip.copy(files_text)\n","sub_path":"scripts/file-lister.py","file_name":"file-lister.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"128103342","text":"#!/usr/bin/env python3\nfrom flask import Flask, jsonify, request, send_from_directory, render_template\nfrom flask_restful import Api, Resource\nfrom pymongo import MongoClient\nimport bcrypt\nfrom flask_jwt_extended import JWTManager \nfrom flask_jwt_extended import create_access_token\n# d9aac332ec5044139d950b0060a89933 --> API Key For News\n\n# For Web Scraping\nimport requests\nfrom bs4 import BeautifulSoup\n\n# For multithreading\nimport threading\nfrom concurrent.futures import ThreadPoolExecutor\n\napp = Flask(__name__, static_folder=\"build/static\", template_folder=\"build\")\napi = Api(app)\n\nclient = MongoClient(\"mongodb://localhost:27017\") # change to db when using Docker\ndb = client.UsersManagementDB\nusers = db[\"Users\"]\n\n# Global variables to keep track of the CURRENT USER'S INFO\ncurrent_user = {}\nuser_list_news = dict()\ntracked_urls = []\n\napp.config[\"JWT_SECRET_KEY\"] = \"secret\"\n\njwt = JWTManager(app)\n\n\n\"\"\"\nREST API SECTION\nThis is where we gather the information from APIs whether it is through webscraping or using a news source api \nfrom the Internet.\n\"\"\"\ndef NewsFromTechRadar():\n # Mashable news api \n main_url = \"https://newsapi.org/v2/top-headlines?sources=techradar&apiKey=d9aac332ec5044139d950b0060a89933\"\n \n open_polygon= requests.get(main_url).json()\n\n list_articles = open_polygon[\"articles\"]\n news_links = dict()\n for news in list_articles:\n article_title = news[\"title\"]\n article_link = news[\"url\"]\n news_links[article_title] = article_link\n return news_links\n\ndef NewsFromMedicalToday():\n URL = \"https://www.medicalnewstoday.com\"\n page = requests.get(URL)\n soup = BeautifulSoup(page.content, \"html.parser\")\n results = soup.find(\"div\", class_=\"css-stl7tm\")\n elems = results.find_all(\"div\", class_=\"css-8sm3l3\")\n news_links = dict()\n for news in elems:\n title = news.find(\"a\", class_=\"css-ni2lnp\")\n links = news.find(\"a\", class_=\"css-ni2lnp\")[\"href\"]\n if None in (title, links):\n continue\n\n news_links[title.text.strip()] = URL + links\n return news_links\n\ndef NewsFromBuzzFeed():\n URL = \"https://www.buzzfeednews.com/section/books\"\n page = requests.get(URL)\n soup = BeautifulSoup(page.content, \"html.parser\")\n results = soup.find(\"div\", class_=\"grid-layout-wrapper content-column\")\n elems = results.find_all(\"span\", class_=\"newsblock-story-card__info xs-pr1 xs-block\")\n news_links = dict()\n for news in elems:\n links = news.find(\"a\", class_=\"newsblock-story-card__link xs-flex\")[\"href\"]\n title = news.find(\"a\", class_=\"newsblock-story-card__link xs-flex\")\n if None in (title, links):\n continue\n\n news_links[title.text.strip()] = links\n return news_links\n\ndef NewsFromPolygon(): \n # Mashable news api \n main_url = \"https://newsapi.org/v2/top-headlines?sources=polygon&apiKey=d9aac332ec5044139d950b0060a89933\"\n \n open_polygon= requests.get(main_url).json()\n\n list_articles = open_polygon[\"articles\"]\n news_links = dict()\n for news in list_articles:\n article_title = news[\"title\"]\n article_link = news[\"url\"]\n news_links[article_title] = article_link\n return news_links\n\ndef NewsFromESPN(): \n # Mashable news api \n main_url = \"https://newsapi.org/v2/top-headlines?sources=espn&apiKey=d9aac332ec5044139d950b0060a89933\"\n \n open_polygon= requests.get(main_url).json()\n\n list_articles = open_polygon[\"articles\"]\n news_links = dict()\n for news in list_articles:\n article_title = news[\"title\"]\n article_link = news[\"url\"]\n news_links[article_title] = article_link\n return news_links\n\nclass WebScraperTechRadar(Resource):\n def get(self):\n return NewsFromTechRadar()\n \nclass WebScraperMedicalToday(Resource):\n def get(self):\n return NewsFromMedicalToday()\n\nclass WebScraperBuzzFeedBooks(Resource):\n def get(self):\n return NewsFromBuzzFeed()\nclass WebScraperPolygon(Resource):\n def get(self):\n return NewsFromPolygon()\n\nclass WebScraperESPN(Resource):\n def get(self):\n return NewsFromESPN()\n\nclass WebScraperUser(Resource): #MAIN FUNCTION TO GET USER'S FEEDS\n def get(self):\n return user_feeds()\n\ndef UserExist(username):\n if users.count_documents({\"username\":username}) == 0:\n return False\n else:\n return True\n\n\"\"\"\nPARALLEL SECTION\nThis is where we put the parallelism.\n\"\"\"\ndef gatherFeed(news_source):\n global user_list_news\n feeds = news_source\n\n for title in feeds: # Iterate through each url and put it in one big dictionary\n print(\"Title: \", title)\n print(\"Link: \", feeds[title])\n user_list_news[title] = feeds[title]\n print(\"List of news: \" ,user_list_news)\n\ndef parallel(id):\n name = threading.current_thread().getName()\n print(name, 'Thread ID:', id)\n global tracked_urls\n global user_list_news\n\n if id not in tracked_urls:\n tracked_urls.append(id)\n\n if id == 'Tech Radar':\n print('Tech Radar')\n gatherFeed(NewsFromTechRadar())\n elif id == 'ESPN':\n print('ESPN')\n gatherFeed(NewsFromESPN())\n elif id == 'Polygon':\n print('Polygon')\n gatherFeed(NewsFromPolygon())\n elif id == 'BuzzFeed':\n print('BuzzFeed')\n gatherFeed(NewsFromBuzzFeed())\n elif id == 'Medical News Today':\n print('Medical News Today')\n gatherFeed(NewsFromMedicalToday())\n\n # print(\"News feeds\", user_list_news)\n return user_list_news\n\n\ndef user_feeds():\n pool = ThreadPoolExecutor(max_workers=5) # limit to only 5 threads\n global user_list_news\n global tracked_urls\n user_list_news = dict() # restart the news feeds when user logs in\n tracked_urls = []\n\n selected_urls = current_user['urls']\n for id in range(len(selected_urls)):\n pool.submit(parallel, selected_urls[id])\n pool.shutdown()\n return user_list_news\n\n# Gather all news for one user (SEQUENTIAL)\ndef user_feeds_seq():\n global user_list_news\n global tracked_urls\n user_list_news = dict() # restart the news feeds when user logs in\n tracked_urls = []\n\n # Put all five URLS to test out sequence code\n selected_urls = current_user['urls']\n for id in range(len(selected_urls)):\n parallel(selected_urls[id])\n return user_list_news\n\n\"\"\"\nDATABASE AND BACK-END HANDLING: PUT USER'S INFO AND SUGGESTED URLS IN THE MONGODB DATABASE\n\"\"\"\nclass Register(Resource):\n def post(self):\n #Step 1 is to get posted data by the user\n postedData = request.get_json()\n\n #Get the data\n username = postedData[\"username\"]\n password = postedData[\"password\"] #\"123xyz\"\n urls = postedData[\"urls\"]\n\n if UserExist(username):\n retJson = {\n 'status':301,\n 'msg': 'Invalid username'\n }\n return jsonify(retJson)\n\n hashed_pw = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())\n\n #Store username and pw into the database\n users.insert_one({\n \"username\": username,\n \"password\": hashed_pw,\n \"urls\": urls \n })\n\n retJson = {\n \"status\": 200,\n \"msg\": \"Success\"\n }\n return jsonify(retJson)\n\nclass Login(Resource):\n def post(self):\n postedData = request.get_json()\n username = postedData['username']\n password = postedData['password'] #'123xyz'\n\n result = \"\"\n found_username = users.find_one({'username': username})\n print(found_username)\n hashed_pw = users.find_one({ \"username\":username })['password']\n\n \n if found_username:\n if bcrypt.hashpw(password.encode('utf8'), hashed_pw) == hashed_pw:\n global current_user\n global user_list_news\n current_user = found_username # server keeps track of current user when web scraping\n \n access_token = create_access_token(identity = {\n 'username': found_username ['username'],\n 'urls': found_username['urls'] # connect with front-end the info\n })\n result = jsonify({'token':access_token})\n else:\n result = jsonify({\"error\":\"Invalid username and password\"})\n else:\n result = jsonify({\"result\":\"No results found\"})\n print(\"Current User: \", current_user )\n return result\n\napi.add_resource(Register, \"/api/register\")\napi.add_resource(Login, \"/api/login\")\napi.add_resource(WebScraperTechRadar, \"/api/techradar/scrape\")\napi.add_resource(WebScraperMedicalToday, \"/api/medical/scrape\")\napi.add_resource(WebScraperBuzzFeedBooks, \"/api/books/scrape\")\napi.add_resource(WebScraperPolygon, \"/api/polygon/scrape\")\napi.add_resource(WebScraperESPN, \"/api/espn/scrape\")\napi.add_resource(WebScraperUser, \"/api/user/scrape\")\n\n@app.route(\"/\")\ndef home():\n return render_template('index.html')\n\n@app.route(\"/manifest.json\")\ndef manifest():\n return send_from_directory('./build', 'manifest.json')\n\n\n@app.route('/favicon.ico')\ndef favicon():\n return send_from_directory('./build', 'favicon.ico')\n\nif __name__==\"__main__\":\n app.run(debug=True, host=\"0.0.0.0\", port=5000)\n\"\"\" \nFIXES TO DO: THE ./build directory is not working to deploy it and have servers work together. \n\"\"\"\n\n","sub_path":"client/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":9422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"378820597","text":"\"\"\"removing redundant fields from order\n\nRevision ID: 254495565185\nRevises: 2843d6469f25\nCreate Date: 2014-09-16 12:09:23.716390\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '254495565185'\ndown_revision = '2843d6469f25'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.drop_column('orders', 'secret_mode')\n op.drop_column('orders', 'secret_algorithm')\n op.drop_column('orders', 'secret_bit_length')\n op.drop_column('orders', 'secret_expiration')\n op.drop_column('orders', 'secret_payload_content_type')\n op.drop_column('orders', 'secret_name')\n\n\ndef downgrade():\n op.add_column('orders', sa.Column('secret_name', sa.String(length=255),\n nullable=True))\n op.add_column('orders', sa.Column('secret_payload_content_type',\n sa.String(length=255),\n nullable=True))\n op.add_column('orders', sa.Column('secret_expiration',\n sa.DateTime(), nullable=True))\n op.add_column('orders', sa.Column('secret_bit_length',\n sa.Integer(),\n autoincrement=False,\n nullable=True))\n op.add_column('orders', sa.Column('secret_algorithm',\n sa.String(length=255),\n nullable=True))\n op.add_column('orders', sa.Column('secret_mode', sa.String(length=255),\n nullable=True))\n","sub_path":"barbican/model/migration/alembic_migrations/versions/254495565185_removing_redundant_fields_from_order.py","file_name":"254495565185_removing_redundant_fields_from_order.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"147682885","text":"import csv\nimport random\n\n# set starting numbers for net_file\nNETWORK_POP = 100\nINFLUENCERS = 20\nFOLLOWERS = 50\nMAX_INF_FOLS = 20\nMAX_NORM_FOLS = 5\n\n# for event file\nNORM_POSTS = 3\nNORM_MIN_NEG = 0\nNORM_MAX_NEG = 1\n\nINF_POSTS = 10\nINF_MIN_NEG = 0.5\nINF_MAX_NEG = 0.8\nNEW_RAND_FOLS = 50\n\n# -----------------------------------------------------------------------\n# populate the names list\nnames = []\nwith open('misc/RandomNames.csv', 'rt') as file:\n reader = csv.reader(file)\n i = 0\n for row in reader:\n if i < NETWORK_POP:\n names.append(row[1])\n i += 1\n\n# populate the influencers list\ninfluencers = []\nfor i in range(0, INFLUENCERS):\n temp_inf = random.choice(names)\n if temp_inf not in influencers:\n influencers.append(temp_inf)\n\n# populate the followers list\n# followers are those more likely to\nfollowers = []\nfor i in range(0, FOLLOWERS):\n temp_fol = random.choice(names)\n if temp_fol not in followers:\n followers.append(temp_fol)\n\n\n# --------------------------------------------------------------------------\n# generate the net_file\nfile = open(\"net_file.txt\", \"w\")\n# write names\nfor name in names:\n file.write(name)\n file.write(\"\\n\")\n\n# write influencer:follower for the popular people\n# popular people are assigned a random number of followers from the followers\n# group, and 1 follower randomly selected from the entire pop.\n# NB: duplicates possible\nfor influencer in influencers:\n # add random no. of followers from followers list\n for i in range(0, random.randint(0, MAX_INF_FOLS)):\n file.write(influencer + \":\" + random.choice(followers))\n file.write(\"\\n\")\n # add 1 random follower from all names\n file.write(influencer + \":\" + random.choice(names))\n file.write(\"\\n\")\n\n# write influencer:follower for the normal people\n# all normal people get allocated a random number of followers, randomly\n# chosen from the entire population\n# NB: duplicates and following self possible\nfor name in names:\n for i in range(0, random.randint(0, MAX_NORM_FOLS)):\n file.write(name + \":\" + random.choice(names))\n file.write(\"\\n\")\nfile.close()\n\n# ---------------------------------------------------------------------------\n# generate the event_file\n\nevents = []\n\n# posts from all users\nfor name in names:\n for i in range(0, NORM_POSTS):\n negativity_rating = round(random.uniform(NORM_MIN_NEG, NORM_MAX_NEG), 2)\n new_post = \"P:\" + name + \":\" + str(negativity_rating)\n events.append(new_post)\n\n# posts from influencers\nfor influencer in influencers:\n for i in range(0, INF_POSTS):\n negativity_rating = round(random.uniform(INF_MIN_NEG, INF_MAX_NEG), 2)\n new_post = \"P:\" + influencer + \":\" + str(negativity_rating)\n events.append(new_post)\n\n# random new follows\nfor i in range(0, NEW_RAND_FOLS):\n new_follower = random.choice(names)\n new_inf = random.choice(names)\n if new_inf != new_follower:\n new_follow = \"F:\" + new_inf + \":\" + new_follower\n events.append(new_follow)\n\nrandom.shuffle(events)\n\n\n# ------------------------\n# write to txt file\nfile = open(\"event_file.txt\", \"w\")\n# write events\nfor event in events:\n file.write(event)\n file.write(\"\\n\")\nfile.close()\n","sub_path":"SocialSim/name_gen.py","file_name":"name_gen.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"436405598","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport logging\nimport requests\nimport json\n# import question_queue\n# import weather_api\nfrom rasa_core_sdk import Action\n\nlogger = logging.getLogger(__name__)\n\n# basic_info_flag = False\n\nclass ActionJoke(Action):\n def name(self):\n # define the name of the action which can then be included in training stories\n return \"action_joke\"\n\n def run(self, dispatcher, tracker, domain):\n # what your action should do\n request = json.loads(\n requests.get(\"https://api.chucknorris.io/jokes/random\").text\n ) # make an api call\n joke = request[\"value\"] # extract a joke from returned json response\n dispatcher.utter_message(joke) # send the message back to the user\n return []\n\n\nclass ProvideWeather(Action):\n def name(self):\n # define the name of the action which can then be included in training stories\n return \"get_weather\"\n\n def run(self, dispatcher, tracker, domain):\n # what your action should do\n\n api_key = \"60226e96c08099f9a5c196d66d4be818\"\n api_url = \"http://api.openweathermap.org/data/2.5/weather\"\n\n zipcode_slot = tracker.get_slot('zipcode')\n query_string_payload = {'units': 'metric',\n 'zip': zipcode_slot, 'appid': api_key}\n\n response = requests.get(api_url, params=query_string_payload)\n\n response_data = response.json()\n\n temp_temp = int(response_data['main']['temp'])\n\n weather = str(temp_temp)\n # return nice text to the user\n weather_nice_text = \"The temperature in \" + tracker.get_slot('zipcode') + \" is \" + weather + \" degrees Celsius\"\n # send the message back to the user\n dispatcher.utter_message(weather_nice_text)\n return []\n\n# prove I can add a random aspect to next question\n# prove I can access the open slots logically\n\n\nclass CheckOpenSlots(Action):\n def name(self):\n # define the name of the action which can then be included in training stories\n return \"get_open_slots\"\n\n def run(self, dispatcher, tracker, domain):\n # what your action should do\n\n get_open_slots = tracker.current_slot_values()\n\n somestring = str(get_open_slots)\n\n # events can be used to set actions to take place in future\n\n # send the message back to the user\n dispatcher.utter_message(somestring)\n return []\n\n\n# intial questions should quickly verify sets of information that are needed or not \n\n\nclass DetermineNextQuestion(Action):\n def name(self):\n # define the name of the action which can then be included in training stories\n return \"get_next_question\"\n\n def run(self, dispatcher, tracker, domain):\n # what your action should do\n\n # for i in question queue that is also in slots filled, skip, else, ask question\n\n if tracker.get_slot('name') == None:\n # do something\n next_question = \"Would you mind repeating your name?\"\n dispatcher.utter_message(next_question)\n return\n elif tracker.get_slot('address') == None:\n # do something\n next_question = \"Would you mind repeating your address?\"\n dispatcher.utter_message(next_question)\n return\n elif tracker.get_slot('zipcode') == None:\n # do something\n next_question = \"Would you mind repeating your zipcode?\"\n dispatcher.utter_message(next_question)\n return\n elif tracker.get_slot('city') == None:\n # do something\n next_question = \"Would you mind repeating your city?\"\n dispatcher.utter_message(next_question)\n return\n elif tracker.get_slot('state') == None:\n # do something\n next_question = \"Would you mind repeating your state?\"\n dispatcher.utter_message(next_question)\n return\n exit_message = \"basic information complete\"\n dispatcher.utter_message(exit_message)\n return\n","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"470708163","text":"def getChangeByGreed(change, coins):\r\n\r\n\t'''\r\n\ttakes\r\n\t\t- change, integer to get the change of.\r\n\t\t- coins, list of integers denoting the coins available for change.\r\n\r\n\treturns\r\n\t\t- list of integers denoting the coins used for change.\r\n\t'''\r\n\t\r\n\tused = []\r\n\twhile(change != 0):\r\n\t\t\r\n\t\tfor coin in coins:\r\n\t\t\tif coin > change:\r\n\t\t\t\tpass\r\n\t\t\telse:\r\n\t\t\t\tused.append(coin)\r\n\t\t\t\tbreak\r\n\t\t\r\n\t\tchange = change - coin\r\n\r\n\treturn used\r\n\r\n# ============================================================================\r\n\r\ndef getChangeByDP(change, coins, known, used):\r\n\r\n\t'''\r\n\ttakes\r\n\t\t- change, integer to get the change of.\r\n\t\t- coins, list of integers denoting the coins available for change.\r\n\t\t- known, list with indices equal to change having 0 at each index.\r\n\t\t- used, list with indices equal to change having 0 at each index.\r\n\r\n\treturns\r\n\t\t- integer indicating the number of coins used for change.\r\n\t'''\r\n\t\r\n\tfor cent in range(change + 1):\r\n\t\tcount = cent\r\n\t\tnewCoin = 1\r\n\r\n\t\tfiltered_coins = [x for x in coins if x <= cent]\r\n\r\n\t\tfor j in filtered_coins:\r\n\t\t\tif known[cent - j] + 1 < count:\r\n\t\t\t\tcount = known[cent - j] + 1\r\n\t\t\t\tnewCoin = j\r\n\t\t\t\t\r\n\t\tknown[cent] = count\r\n\t\tused[cent] = newCoin\r\n\t\t\r\n\treturn known[change]\r\n\r\n# ============================================================================\r\n\r\ndef getUsedCoins(change, traversed):\r\n\r\n\t'''\r\n\ttakes\r\n\t\t- change, integer to get the change of.\r\n\t\t- traversed, list of integers showing the coin used by DP approach.\r\n\r\n\treturns\r\n\t\t- list of integers denoting the coins used for change.\r\n\t'''\r\n\r\n\tused = []\r\n\r\n\tcoin = change\r\n\twhile (coin > 0):\r\n\t\tcurrCoin = traversed[coin]\r\n\t\tused.append(currCoin)\r\n\t\tcoin = coin - currCoin\r\n\r\n\treturn used\r\n\r\n# ============================================================================\r\n\r\ndef main(change):\r\n\r\n\t'''\r\n\ttakes\r\n\t\t- change, integer to get the change of.\r\n\r\n\timplementation\r\n\t\t- calls the `getChangeByGreed()` to get the coins used by greedy approach.\r\n\t\t- calls the `getChangeByDP()` to get the coins used by DP approach.\r\n\t\t- prints out the data retrieved after calling above funcs.\r\n\r\n\treturns\r\n\t\t- nothing\r\n\t'''\r\n\t\r\n\tcoins = [25, 10, 5, 1]\r\n\r\n\tusedByGreed = getChangeByGreed(change, coins)\r\n\r\n\tknown = [0] * (change + 1); traversed = [0] * (change + 1)\r\n\r\n\tnumOfCoinsByDP = getChangeByDP(change, coins, known, traversed)\r\n\tusedByDP = getUsedCoins(change, traversed)\r\n\r\n\tstring = \"Greedy Algorithm\"\r\n\tprint(string + \" |\\n\" + \"=\" * (len(string) + 2))\r\n\tprint(\"number of coins used:\", len(usedByGreed))\r\n\tprint(\"coins used:\", usedByGreed, \"\\n\")\r\n\r\n\tstring = \"Dynamic Programming Algorithm\"\r\n\tprint(string + \" |\\n\" + \"=\" * (len(string) + 2))\r\n\tprint(\"number of coins used:\", numOfCoinsByDP)\r\n\tprint(\"coins used:\", usedByDP)\r\n\r\n# ============================================================================\r\n\r\nif __name__ == '__main__':\r\n\t\r\n\tmain(63)","sub_path":"RanaAwais_6804_4A_AP_LAB08/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"535862226","text":"\nfrom django.conf.urls import url\nfrom integration_config.views import (\n IntegrationListView,\n IntegrationCreate,\n IntegrationUpdate\n)\n\napp_name = 'integrations'\nurlpatterns = [\n url(r'^create/$', IntegrationCreate.as_view(), name='create-integration'),\n url(r'^(?P[-\\w]+)/$', IntegrationUpdate.as_view(), name='update-integration'),\n url(r'^$', IntegrationListView.as_view(), name='list-integrations'),\n]","sub_path":"integration_config/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"507529416","text":"import os\nimport signal\nimport sys\nimport time\nimport subprocess\nimport glob\nfrom os.path import expanduser\nfrom util_serilize import *\nfrom termcolor import colored\nimport datetime\nfrom multiprocessing.dummy import Pool as ThreadPool\nimport threading\n\nhome = expanduser(\"~\")\n\n# non-blocking or blocking actually depends on whether cmd is bg or fg\ndef blocking_run(cmd):\n ret = subprocess.check_output(['/bin/bash', '-c', cmd], universal_newlines=True)\n # ret = subprocess.check_output(['/bin/bash', '-c', cmd], stderr=subprocess.STDOUT, universal_newlines=True)\n return str(ret)\n\n# always non-blocking, as it is running in a subprocess.\ndef non_blocking_run(cmd):\n subprocess.Popen(['/bin/bash', '-c', cmd])\n\n# def exe_gem5_sim(cmd_line):\n# try:\n# print(f'{threading.currentThread().getName()} running: {cmd_line}', flush=True)\n# os.popen(cmd_line).read()\n# print(f'{threading.currentThread().getName()} okay: {cmd_line}', flush=True)\n# return f'okay: {cmd_line}'\n# except Exception:\n# print(f'{threading.currentThread().getName()} fails: {cmd_line}', flush=True)\n# return f'fails: {cmd_line}'\n\n# def run_gem5_sim(commands):\n# # 1 thread is left.\n# pool = ThreadPool(64)\n# results = pool.map(exe_gem5_sim, commands)\n# pool.close()\n# pool.join()\n# for res in results:\n# print(res)\n\nif __name__ == \"__main__\":\n database = 'tpcds10'\n toStorage = 'alluxio://node0:19998'\n # 'hdfs://node0:9000'\n\n if len(sys.argv) == 3:\n database = sys.argv[1]\n if sys.argv[2] == 'alluxio':\n toStorage = 'alluxio://node0:19998'\n elif sys.argv[2] == 'hdfs':\n toStorage = 'hdfs://node0:9000'\n else:\n print('Usage: python hdfs2alluxio.py tpcds_bin_partitioned_orc_2 alluxio/hive')\n sys.exit(0)\n\n print(database, toStorage)\n\n cmd = f'~/spark-2.4.5-bin-hadoop2.7/bin/spark-sql --database {database} -e \"show tables;\"'\n tables = blocking_run(cmd).strip().split()[1::3]\n print(tables)\n sql = open('./log/transfer.sql', 'w')\n for table in tables: \n if toStorage == 'alluxio':\n cmd = f'ALTER TABLE {table} SET LOCATION \"{toStorage}/mnt/alluxio1/{database}.db/{table}\";'\n else:\n cmd = f'ALTER TABLE {table} SET LOCATION \"{toStorage}/user/hive/warehouse/{database}.db/{table}\";'\n sql.write(cmd + '\\n')\n # cmd = f'~/spark-2.4.5-bin-hadoop2.7/bin/spark-sql --database {database} -e \"show partitions {table};\"'\n # try:\n # partitions = blocking_run(cmd).strip().split()\n # except Exception:\n # continue\n # partitions = list(filter(lambda x: '=' in x, partitions))\n # print(partitions)\n # for partition in partitions:\n # partition_str = partition.replace('__HIVE_DEFAULT_PARTITION__', '\"__HIVE_DEFAULT_PARTITION__\"')\n # cmd = f'ALTER TABLE {table} partition ({partition_str}) SET LOCATION \"{toStorage}/user/hive/warehouse/{database}.db/{table}/{partition}\";'\n # sql.write(cmd + '\\n')\n sql.close()\n cmd = f'~/spark-2.4.5-bin-hadoop2.7/bin/spark-sql --database {database} -f ./log/transfer.sql' \n blocking_run(cmd)\n\n","sub_path":"hdfs2alluxio.py","file_name":"hdfs2alluxio.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"55959672","text":"# This is a sample Python script.\r\n\r\n# Press Shift+F10 to execute it or replace it with your code.\r\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\r\ntry:\r\n # list of variables\r\n middle_name = \"kelly\"\r\n guess = str\r\n guess_count = 0 # how many times the user has guessed\r\n guess_limit = 3 # how many guesses are available\r\n out_of_names = False # boolean to let us know if the user is out of guesses\r\n\r\n\r\n\r\n while guess != middle_name and not out_of_names: # while condition is true as long as word is not guessed and have guesses left\r\n\r\n if guess_count < guess_limit: # if guess count is less then guess limit they have more guesses to run\r\n guess = str(input(\"Enter name: \")) # the input has been set to accept a string only\r\n guess_count += 1 # this will add 1 to each guess count // increment the guess count by 1\r\n guesses_left = guess_limit - guess_count # this variable is created by subtracting guess count from the guess limit to reveal how many guesses are left\r\n\r\n # print(\"you have \", guesses_left ,\" guesses left\") # this print will feature the number of guesses left\r\n\r\n\r\n\r\n else: # if they are out of guesses they can no longer loop and the game is over\r\n out_of_names = True\r\n\r\n\r\n if out_of_names: # if user is out of guess then do this\r\n print(\"Out of Guesses, Come on Kelly do Better!!!\")\r\n else:\r\n print(\"Our Little Girls full name is: Reese Kelly Bell!!\")\r\n\r\n\r\n\r\nexcept:\r\n print(\"Invalid Input\")\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"131817651","text":"# here we are desanding the character of string.\n\nMAX_CHAR = 26;\ndef sortString(str):\n charCount = [0]*MAX_CHAR;\n for i in range(len(str)):\n charCount[ord(str[i]) - ord('a')]+=1;\n \n for i in range(MAX_CHAR - 1,-1, -1):\n for j in range(charCount[i]):\n print(chr(97+i),end=\"\");\ns = input(\"enter any string=\");\nsortString(s);","sub_path":"character_of_string_desandinig.py","file_name":"character_of_string_desandinig.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"152308008","text":"import os\nimport json\n\nfrom cloudmesh.volume.VolumeABC import VolumeABC\nfrom cloudmesh.common.util import banner\nfrom datetime import datetime\nfrom cloudmesh.common.Shell import Shell\nfrom cloudmesh.configuration.Config import Config\nimport boto3\nfrom cloudmesh.common.DateTime import DateTime\nfrom cloudmesh.common.Printer import Printer\n\nimport collections\n\nclass Provider(VolumeABC):\n kind = \"volume\"\n\n sample = \"\"\"\n cloudmesh:\n cloud:\n {name}:\n cm:\n active: true\n heading: AWS\n host: TBD\n label: {name}\n kind: aws\n version: TBD\n service: volume\n default:\n volume_type: \"gp2\"\n size: 2\n iops: 1000\n encrypted: False\n multi_attach_enabled: True\n region: 'us-east-2'\n credentials:\n EC2_SECURITY_GROUP: cloudmesh\n EC2_ACCESS_ID: {EC2_ACCESS_ID}\n EC2_SECRET_KEY: {EC2_SECRET_KEY}\n EC2_PRIVATE_KEY_FILE_PATH: \n EC2_PRIVATE_KEY_FILE_NAME: \n \"\"\"\n\n volume_states = [\n 'in-use',\n 'available',\n 'creating',\n 'deleted',\n 'deleting',\n 'error',\n 'inuse'\n ]\n\n output = {\n\n \"volume\": {\n \"sort_keys\": [\"cm.name\"],\n \"order\": [\"cm.name\",\n \"cm.cloud\",\n \"cm.kind\",\n \"cm.region\",\n #\"AvailabilityZone\",\n \"CreateTime\",\n \"Encrypted\",\n \"Size\",\n #\"SnapshotId\",\n \"States\",\n #\"VolumeId\",\n \"Iops\",\n #\"Tags\",\n \"VolumeType\",\n #\"created\",\n \"AttachedToVm\"\n ],\n \"header\": [\"Name\",\n \"Cloud\",\n \"Kind\",\n \"Region\",\n #\"AvailabilityZone\",\n \"CreateTime\",\n \"Encrypted\",\n \"Size\",\n #\"SnapshotId\",\n \"Status\",\n #\"VolumeId\",\n \"Iops\",\n #\"Tags\",\n \"VolumeType\",\n #\"Created\",\n \"AttachedToVm\"\n ],\n }\n }\n\n def __init__(self, name=None):\n self.cloud = name\n #self.ec2 = boto3.resource('ec2')\n\n def update_dict(self, results):\n \"\"\"\n This function adds a cloudmesh cm dict to each dict in the list\n elements.\n Libcloud\n returns an object or list of objects With the dict method\n this object is converted to a dict. Typically this method is used\n internally.\n\n :param results: the original dicts.\n :param kind: for some kinds special attributes are added. This includes\n key, vm, image, flavor.\n :return: The list with the modified dicts\n \"\"\"\n\n # {'Volumes':\n # [\n # {'Attachments':\n # [\n # {'AttachTime': datetime.datetime(2020, 3, 16, 20, 0, 35, tzinfo=tzutc()),\n # 'Device': '/dev/sda1',\n # 'InstanceId': 'i-0765529fec90ba56b',\n # 'State': 'attached',\n # 'VolumeId': 'vol-09db404935694e941',\n # 'DeleteOnTermination': True}\n # ],\n # 'AvailabilityZone': 'us-east-2c',\n # 'CreateTime': datetime.datetime(2020, 3, 16, 20, 0, 35, 257000, tzinfo=tzutc()),\n # 'Encrypted': False,\n # 'Size': 8,\n # 'SnapshotId': 'snap-085c8383cc8833286',\n # 'State': 'in-use',\n # 'VolumeId': 'vol-09db404935694e941',\n # 'Iops': 100,\n # 'Tags':\n # [{'Key': 'Name',\n # 'Value': 'xin-vol-3'}],\n # 'VolumeType': 'gp2'},\n # {...}\n # ]\n # }\n\n\n if results is None:\n return None\n # elif type(elements) == list:\n # _elements = elements\n # else:\n # _elements = [elements]\n d = []\n\n elements = results['Volumes']\n #print(type(elements))\n for entry in elements:\n #print(\"entry\", entry)\n #print(type(entry))\n try:\n for item in entry['Tags']:\n if item['Key'] == 'Name':\n volume_name = item['Value']\n else:\n volume_name =\" \"\n except:\n pass\n if \"cm\" not in entry:\n entry['cm'] = {}\n\n entry[\"cm\"].update({\n \"cloud\": self.cloud,\n \"kind\": \"volume\",\n \"name\": volume_name,\n \"region\": entry[\"AvailabilityZone\"], # for aws region = AvailabilityZone\n })\n\n# entry[\"cm\"][\"created\"] = str(DateTime.now())\n\n d.append(entry)\n return d\n\n def create(self, name=None, **kwargs): #name is volume name\n cloud = kwargs['cloud']\n config = Config()\n default = config[f\"cloudmesh.volume.{cloud}.default\"]\n #banner(f\"print default {default}\")\n #banner(f\"print kwargs {kwargs}\")\n for key in default.keys():\n if key not in kwargs.keys():\n kwargs[key] = default[key]\n elif kwargs[key] == None:\n kwargs[key] = default[key]\n\n #default.update(kwargs)\n #banner(f\"print kwargs after update {kwargs}\")\n result = self._create(name=name, **kwargs)\n\n #size: 2\n #iops: 1000\n #encrypted: False\n #multi_attach_enabled: True\n result = self.update_dict(result)\n return result\n\n def _create(self,\n **kwargs):\n \"\"\"\n Create a volume.\n\n :param name (string): name of volume\n :param zone (string): availability-zone\n :param encrypted (boolean): True|False\n :param size (integer): size of volume\n\n :param volume_type (string): type of volume. This can be gp2 for General\n Purpose SSD, io1 for Provisioned IOPS SSD,\n st1 for Throughput Optimized HDD, sc1 for\n Cold HDD, or standard for Magnetic volumes.\n :param iops (integer): The number of I/O operations per second (IOPS)\n that the volume supports\n (from 100 to 64,000 for io1 type volume). If iops\n is specified, the volume_type must be io1.\n :param kms_key_id (string): The identifier of the AWS Key Management\n Service (AWS KMS) customer master key (CMK)\n to use for Amazon EBS encryption. If\n KmsKeyId is specified, the encrypted state\n must be true.\n :param outpost_arn (string): The Amazon Resource Name (ARN) of the Outpost.\n :param image:\n :param snapshot (string): snapshot id\n :param source:\n :param description (string):\n :param tag_key (string): Tag keys are case-sensitive and accept a\n maximum of 127 Unicode characters.\n May not begin with aws.\n :param tag_value (string): Tag values are case-sensitive and accept a\n maximum of 255 Unicode characters.\n :param multi_attach_enabled (boolean):\n :return:\n\n \"\"\"\n\n #banner(f\"create volume {kwargs}\")\n client = boto3.client('ec2')\n\n if kwargs['volume_type']=='io1':\n\n raise NotImplementedError\n\n if kwargs['volume_type']=='sc1':\n if int(kwargs['size']) < 500:\n raise Exception(\"minimum volume size for sc1 is 500 GB\")\n\n\n r = client.create_volume(\n AvailabilityZone=kwargs['region'],\n Encrypted=kwargs['encrypted'],\n #Iops=kwargs['iops'],\n #KmsKeyId=None,\n #OutpostArn=None,\n Size=int(kwargs['size']),\n #SnapshotId=None,\n VolumeType=kwargs['volume_type'],\n DryRun=kwargs['dryrun'],\n TagSpecifications=[\n {\n 'ResourceType': 'volume',\n 'Tags': [\n {\n 'Key': \"Name\",\n 'Value': kwargs['NAME']\n },\n ]\n },\n ],\n #MultiAttachEnabled=kwargs['multi_attach_enabled']\n )\n r = [r]\n result = {}\n result['Volumes']= r\n\n #banner(\"raw results\")\n #print(result)\n #banner(\"raw results end\")\n\n return result\n\n\n # PROPOSAL 2\n def list(self,\n **kwargs\n ):\n\n \"\"\"\n THis command list all volumes as follows\n\n If vm is defined, all vloumes of teh vm are returned.\n If region is defined all volumes of the vms in that region are returned.\n ....\n\n #The filter allows us to specify cloud specific filter option\n #a filter for this cloud looks like ....????\n\n :param dryrun:\n :param refresh:\n :return:\n \"\"\"\n\n # dont filter_name=None,\n # dont filter_value=None,\n # dryrun=False):\n\n #:param filter_name (string)\n #:param filter_value (string)\n #:param volume_ids (list): The volume IDs\n\n # filter = \"[[\n # {\n # 'Name': 'xyz',\n # 'Values': [\n # 'abc',\n # ]\n # },\n # ]\"\n\n # filter = eval(filter)\n\n #banner('print kwargs')\n #print(kwargs)\n #print(kwargs['output'])\n\n client = boto3.client('ec2')\n dryrun = kwargs['--dryrun']\n #region = kwargs['--region']\n #vm = kwargs['--vm']# will need vm id from mongo records\n result = client.describe_volumes(\n DryRun=dryrun,\n # Filters=[\n # {\n # 'Name': {},\n # 'Values': [\n # filter_value,\n # ]\n # },\n # ],\n )\n #banner(\"raw results\")\n #print(result)\n #banner(\"raw results end\")\n result = self.update_dict(result)\n\n #print(self.Print(result, kind='volume', output=kwargs['output']))\n\n return result\n\n def delete(self, volume_id, dryrun=False):\n \"\"\"\n delete volume\n\n :param volume_id (string): volume id\n :param dryrun (boolean): True|False\n :return: dict\n \"\"\"\n\n banner(f\"delete volume\")\n volume = self.ec2.Volume(volume_id)\n result = volume.delete(\n DryRun=dryrun\n )\n # This is wrong not updated\n return result\n\n def attach(self,\n NAME,\n vm,\n device=\"/dev/sdh\",\n dryrun=False):\n \"\"\"\n mounts volume\n\n :param volume_id (string): volume id\n :param vm_id (string): instance id\n :param device (string): The device name (for example, /dev/sdh or xvdh)\n :param dryrun (boolean): True|False\n :return: dict\n\n \"\"\"\n client = boto3.client('ec2')\n volume = client.describe_volumes(\n DryRun=dryrun,\n Filters=[\n {\n 'Name': 'tag:Name',\n 'Values': [NAME,]\n },\n ],\n )\n volume_id = volume['Volumes'][0]['VolumeId']\n instance = client.describe_instances(\n Filters=[\n {\n 'Name': 'tag:Name',\n 'Values': [vm,]\n },\n ],\n DryRun=dryrun\n )\n vm_id = instance['Reservations'][0]['Instances'][0]['InstanceId']\n response = client.attach_volume(\n Device=device,\n InstanceId=vm_id,\n VolumeId=volume_id,\n DryRun=dryrun\n )\n result = client.describe_volumes(\n DryRun=dryrun,\n Filters=[\n {\n 'Name': 'tag:Name',\n 'Values': [NAME]\n },\n ],\n )\n result['Volumes'][0]['AttachedToVm']=[vm]\n\n result = self.update_dict(result)\n return result\n\n def detach(self,\n NAME):\n \"\"\"\n Detach a volume from vm\n\n :param NAME: name of volume to dettach\n :return: str\n \"\"\"\n\n client = boto3.client('ec2')\n volume = client.describe_volumes(\n Filters=[\n {\n 'Name': 'tag:Name',\n 'Values': [NAME, ]\n },\n ],\n )\n volume_id = volume['Volumes'][0]['VolumeId']\n rresponse = client.detach_volume(\n VolumeId=volume_id,\n )\n result = client.describe_volumes(\n Filters=[\n {\n 'Name': 'tag:Name',\n 'Values': [NAME]\n },\n ],\n )\n result['Volumes'][0]['AttachedToVm'] = \" \"\n\n result = self.update_dict(result)\n return result\n\n\n def migrate(self,\n name=None,\n fvm=None,\n tvm=None,\n fregion=None,\n tregion=None,\n fservice=None,\n tservice=None,\n fcloud=None,\n tcloud=None,\n cloud=None,\n region=None,\n service=None):\n \"\"\"\n Migrate volume from one vm to another vm.\n\n :param name: name of volume\n :param fvm: name of vm where volume will be moved from\n :param tvm: name of vm where volume will be moved to\n :param fregion: the region where the volume will be moved from\n :param tregion: region where the volume will be moved to\n :param fservice: the service where the volume will be moved from\n :param tservice: the service where the volume will be moved to\n :param fcloud: the provider where the volume will be moved from\n :param tcloud: the provider where the volume will be moved to\n :param cloud: the provider where the volume will be moved within\n :param region: the region where the volume will be moved within\n :param service: the service where the volume will be moved within\n :return: dict\n\n \"\"\"\n\n raise NotImplementedError\n\n def sync(self,\n volume_id,\n zone=None,\n cloud=None,\n dryrun=False\n ):\n \"\"\"\n sync contents of one volume to another volume\n\n :param volume_id (string): list of id of volume\n :param zone (string): zone where new volume will be created\n :param cloud (string): the provider where volumes will be hosted\n :return: dict\n\n \"\"\"\n banner(f\"sync volume\")\n volume = self.ec2.Volume(volume_id)\n snapshot = volume.create_snapshot()\n if zone is None:\n availability_zone = self.ec2.describe_volumes(\n VolumeIds=[volume_id])['Volumes'][0]['availability-zone']\n else:\n availability_zone = zone\n result = self.ec2.create_volume(SnapshotId=snapshot,\n AvailabilityZone=availability_zone,\n DryRun=dryrun)\n # This is wrong not updated\n raise NotImplementedError\n\n\n\n\n def set(self,\n volume_id,\n attribute=None,\n tag_key=None,\n tag_value=None,\n size=None,\n voltype=None,\n iops=None,\n dryrun=False):\n\n \"\"\"\n modify-volume-attribute: resume I/O access to the volume, or add or\n overwrite the specified tags, \\\n or modify volume size, volume type, iops value\n\n :param volume_id <(string): volume id\n :param attribute (sting): can be \"auto_enable_io\", \"tag\"\n :param tag_key (string): Tag keys are case-sensitive and accept a\n maximum of 127 Unicode characters.\n May not begin with aws.\n :param tag_value (string): Tag values are case-sensitive and accept\n a maximum of 255 Unicode characters.\n :param size (integer): The target size of the volume, in GiB.\n :param voltype (string): Type of volume. This can be 'gp2' for\n General Purpose SSD,\n 'io1' for Provisioned IOPS SSD, 'st1'\n for Throughput Optimized HDD,\n 'sc1' for Cold HDD, or 'standard' for\n Magnetic volumes.\n :param iops (integer): The number of I/O operations per second\n (IOPS) that the volume supports\n (from 100 to 64,000 for io1 type volume).\n :param dryrun (boolean): True | False\n \"\"\"\n\n volume = self.ec2.Volume(volume_id)\n if attribute == \"auto_enable_io\":\n result = volume.modify_attribute(\n AutoEnableIO={\n 'Value': True\n },\n DryRun=dryrun\n )\n\n elif attribute == \"tag\":\n result = volume.create_tags(\n DryRun=dryrun,\n Tags=[\n {\n 'Key': tag_key,\n 'Value': tag_value\n },\n ]\n )\n\n else:\n result = volume.modify_volume(\n DryRun=dryrun,\n VolumeId=volume_id,\n Size=size,\n VolumeType=volume_type, # BUG\n Iops=iops\n )\n\n # This is wrong not updated\n return result\n\n def unset(self, volume_id, attribute=None, dryrun=False):\n\n \"\"\"\n modify-volume-attribute: suspend I/O access to the volume, or\n overwrite tag by an empty string\n\n :param volume_id (string): volume id\n :param attribute (sting): \"no_auto_enable_io\" | \"tag\"\n :param dryrun (boolean): True | False\n \"\"\"\n\n volume = self.ec2.Volume(volume_id)\n if attribute == \"no_auto_enable_io\":\n result = volume.modify_attribute(\n AutoEnableIO={\n 'Value': False\n },\n DryRun=dryrun\n )\n\n elif attribute == \"tag\":\n result = volume.create_tags(\n DryRun=dryrun,\n Tags=[\n {\n 'Key': \" \",\n 'Value': \" \"\n },\n ]\n )\n # This is wrong not updated\n return result\n\n\nif __name__ == \"__main__\":\n # region = 'us-east-2'\n p = Provider()\n\n p.list()\n","sub_path":"cloudmesh/volume/aws/Provider.py","file_name":"Provider.py","file_ext":"py","file_size_in_byte":19952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"428423108","text":"from django.urls import path\r\n\r\nfrom API import views\r\n\r\nurlpatterns = [\r\n path(\"user/\", views.user),\r\n # 为类视图定义url\r\n path(\"users/\", views.UserView.as_view()),\r\n\r\n path(\"student/\", views.StudentView.as_view()),\r\n path(\"student//\", views.StudentView.as_view()),\r\n\r\n # DRF的类视图 调用的as_view与Django的不是同一个方法\r\n path(\"user_api/\", views.UserAPIView.as_view()),\r\n]","sub_path":"drf_1/API/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"278423604","text":"import os\nimport re\nimport sys\nimport pickle\nimport pairmsa\nimport json\n\nimport colabfold as cf\n\nfrom alphafold.data import parsers\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom Bio import SeqIO\n\nimport argparse\nargparser = argparse.ArgumentParser(description='run alphafold.')\nargparser.add_argument('fasta_file', type=str)\nargparser.add_argument('homooligomer_counts', type=str)\nargs = argparser.parse_args()\nfasta_file = args.fasta_file\nhomooligomer_counts = args.homooligomer_counts\n\ndef get_msa(sequence, jobname, homooligomer_counts):\n\n sequence = re.sub(\"[^A-Z:/]\", \"\", sequence.upper())\n sequence = re.sub(\":+\",\":\",sequence)\n sequence = re.sub(\"/+\",\"/\",sequence)\n\n jobname = re.sub(r'\\W+', '', jobname)\n\n # define number of copies\n homooligomer = homooligomer_counts\n homooligomer = re.sub(\"[:/]+\",\":\",homooligomer)\n if len(homooligomer) == 0: homooligomer = \"1\"\n homooligomer = re.sub(\"[^0-9:]\", \"\", homooligomer)\n homooligomers = [int(h) for h in homooligomer.split(\":\")]\n\n #@markdown - `sequence` Specify protein sequence to be modelled.\n #@markdown - Use `/` to specify intra-protein chainbreaks (for trimming regions within protein).\n #@markdown - Use `:` to specify inter-protein chainbreaks (for modeling protein-protein hetero-complexes).\n #@markdown - For example, sequence `AC/DE:FGH` will be modelled as polypeptides: `AC`, `DE` and `FGH`. A seperate MSA will be generates for `ACDE` and `FGH`.\n #@markdown If `pair_msa` is enabled, `ACDE`'s MSA will be paired with `FGH`'s MSA.\n #@markdown - `homooligomer` Define number of copies in a homo-oligomeric assembly.\n #@markdown - Use `:` to specify different homooligomeric state (copy numer) for each component of the complex.\n #@markdown - For example, **sequence:**`ABC:DEF`, **homooligomer:** `2:1`, the first protein `ABC` will be modeled as a homodimer (2 copies) and second `DEF` a monomer (1 copy).\n\n ori_sequence = sequence\n sequence = sequence.replace(\"/\",\"\").replace(\":\",\"\")\n seqs = ori_sequence.replace(\"/\",\"\").split(\":\")\n\n if len(seqs) != len(homooligomers):\n if len(homooligomers) == 1:\n homooligomers = [homooligomers[0]] * len(seqs)\n homooligomer = \":\".join([str(h) for h in homooligomers])\n else:\n while len(seqs) > len(homooligomers):\n homooligomers.append(1)\n homooligomers = homooligomers[:len(seqs)]\n homooligomer = \":\".join([str(h) for h in homooligomers])\n print(\"WARNING: Mismatch between number of breaks ':' in 'sequence' and 'homooligomer' definition\")\n\n full_sequence = \"\".join([s*h for s,h in zip(seqs,homooligomers)])\n\n # prediction directory\n output_dir = 'outputs/prediction_' + jobname #+ '_' + cf.get_hash(full_sequence)[:5]\n os.makedirs(output_dir, exist_ok=True)\n # delete existing files in working directory\n for f in os.listdir(output_dir):\n os.remove(os.path.join(output_dir, f))\n\n MIN_SEQUENCE_LENGTH = 16\n MAX_SEQUENCE_LENGTH = 2500\n\n aatypes = set('ACDEFGHIKLMNPQRSTVWY') # 20 standard aatypes\n if not set(full_sequence).issubset(aatypes):\n raise Exception(f'Input sequence contains non-amino acid letters: {set(sequence) - aatypes}. AlphaFold only supports 20 standard amino acids as inputs.')\n if len(full_sequence) < MIN_SEQUENCE_LENGTH:\n raise Exception(f'Input sequence is too short: {len(full_sequence)} amino acids, while the minimum is {MIN_SEQUENCE_LENGTH}')\n if len(full_sequence) > MAX_SEQUENCE_LENGTH:\n raise Exception(f'Input sequence is too long: {len(full_sequence)} amino acids, while the maximum is {MAX_SEQUENCE_LENGTH}. Please use the full AlphaFold system for long sequences.')\n\n if len(full_sequence) > 1400:\n print(f\"WARNING: For a typical Google-Colab-GPU (16G) session, the max total length is ~1400 residues. You are at {len(full_sequence)}! Run Alphafold may crash.\")\n\n print(f\"homooligomer: '{homooligomer}'\")\n print(f\"total_length: '{len(full_sequence)}'\")\n print(f\"working_directory: '{output_dir}'\")\n #%%\n TQDM_BAR_FORMAT = '{l_bar}{bar}| {n_fmt}/{total_fmt} [elapsed: {elapsed} remaining: {remaining}]'\n\n msa_method = \"mmseqs2\" #@param [\"mmseqs2\",\"jackhmmer\",\"single_sequence\",\"precomputed\"]\n pair_msa = False #@param {type:\"boolean\"}\n pair_cov = 50 #@param [50,75,90] {type:\"raw\"}\n pair_qid = 20 #@param [15,20,30,40,50] {type:\"raw\"}\n include_unpaired_msa = True #@param {type:\"boolean\"}\n\n add_custom_msa = False #@param {type:\"boolean\"}\n msa_format = \"fas\" #@param [\"fas\",\"a2m\",\"a3m\",\"sto\",\"psi\",\"clu\"]\n\n # --- Search against genetic databases ---\n os.makedirs('tmp', exist_ok=True)\n msas, deletion_matrices = [],[]\n\n if add_custom_msa:\n print(f\"upload custom msa in '{msa_format}' format\")\n msa_dict = files.upload()\n lines = msa_dict[list(msa_dict.keys())[0]].decode()\n\n # convert to a3m\n with open(f\"tmp/upload.{msa_format}\",\"w\") as tmp_upload:\n tmp_upload.write(lines)\n os.system(f\"reformat.pl {msa_format} a3m tmp/upload.{msa_format} tmp/upload.a3m\")\n a3m_lines = open(\"tmp/upload.a3m\",\"r\").read()\n\n # parse\n msa, mtx = parsers.parse_a3m(a3m_lines)\n msas.append(msa)\n deletion_matrices.append(mtx)\n\n if len(msas[0][0]) != len(sequence):\n raise ValueError(\"ERROR: the length of msa does not match input sequence\")\n\n if msa_method == \"precomputed\":\n print(\"upload precomputed pickled msa from previous run\")\n pickled_msa_dict = files.upload()\n msas_dict = pickle.loads(pickled_msa_dict[list(pickled_msa_dict.keys())[0]])\n msas, deletion_matrices = (msas_dict[k] for k in ['msas', 'deletion_matrices'])\n\n elif msa_method == \"single_sequence\":\n if len(msas) == 0:\n msas.append([sequence])\n deletion_matrices.append([[0]*len(sequence)])\n\n else:\n seqs = ori_sequence.replace('/','').split(':')\n _blank_seq = [\"-\" * len(seq) for seq in seqs]\n _blank_mtx = [[0] * len(seq) for seq in seqs]\n def _pad(ns,vals,mode):\n if mode == \"seq\": _blank = _blank_seq.copy()\n if mode == \"mtx\": _blank = _blank_mtx.copy()\n if isinstance(ns, list):\n for n,val in zip(ns,vals): _blank[n] = val\n else: _blank[ns] = vals\n if mode == \"seq\": return \"\".join(_blank)\n if mode == \"mtx\": return sum(_blank,[])\n\n if not pair_msa or (pair_msa and include_unpaired_msa):\n # gather msas\n if msa_method == \"mmseqs2\":\n prefix = cf.get_hash(\"\".join(seqs))\n prefix = os.path.join('tmp',prefix)\n print(f\"running mmseqs2\")\n A3M_LINES = cf.run_mmseqs2(seqs, prefix, filter=True)\n\n for n, seq in enumerate(seqs):\n # tmp directory\n prefix = cf.get_hash(seq)\n prefix = os.path.join('tmp',prefix)\n\n if msa_method == \"mmseqs2\":\n # run mmseqs2\n a3m_lines = A3M_LINES[n]\n msa, mtx = parsers.parse_a3m(a3m_lines)\n msas_, mtxs_ = [msa],[mtx]\n\n # pad sequences\n for msa_,mtx_ in zip(msas_,mtxs_):\n msa,mtx = [sequence],[[0]*len(sequence)]\n for s,m in zip(msa_,mtx_):\n msa.append(_pad(n,s,\"seq\"))\n mtx.append(_pad(n,m,\"mtx\"))\n\n msas.append(msa)\n deletion_matrices.append(mtx)\n\n ####################################################################################\n # PAIR_MSA\n ####################################################################################\n\n if pair_msa and len(seqs) > 1:\n print(\"attempting to pair some sequences...\")\n\n if msa_method == \"mmseqs2\":\n prefix = cf.get_hash(\"\".join(seqs))\n prefix = os.path.join('tmp',prefix)\n print(f\"running mmseqs2_noenv_nofilter on all seqs\")\n A3M_LINES = cf.run_mmseqs2(seqs, prefix, use_env=False, filter=False)\n\n _data = []\n for a in range(len(seqs)):\n print(f\"prepping seq_{a}\")\n _seq = seqs[a]\n _prefix = os.path.join('tmp',cf.get_hash(_seq))\n\n if msa_method == \"mmseqs2\":\n a3m_lines = A3M_LINES[a]\n _msa, _mtx, _lab = pairmsa.parse_a3m(a3m_lines,\n filter_qid=pair_qid/100,\n filter_cov=pair_cov/100)\n\n elif msa_method == \"jackhmmer\":\n _msas, _mtxs, _names = run_jackhmmer(_seq, _prefix)\n _msa, _mtx, _lab = pairmsa.get_uni_jackhmmer(_msas[0], _mtxs[0], _names[0],\n filter_qid=pair_qid/100,\n filter_cov=pair_cov/100)\n\n if len(_msa) > 1:\n _data.append(pairmsa.hash_it(_msa, _lab, _mtx, call_uniprot=False))\n else:\n _data.append(None)\n\n Ln = len(seqs)\n O = [[None for _ in seqs] for _ in seqs]\n for a in range(Ln):\n if _data[a] is not None:\n for b in range(a+1,Ln):\n if _data[b] is not None:\n print(f\"attempting pairwise stitch for {a} {b}\")\n O[a][b] = pairmsa._stitch(_data[a],_data[b])\n _seq_a, _seq_b, _mtx_a, _mtx_b = (*O[a][b][\"seq\"],*O[a][b][\"mtx\"])\n print(f\"found {len(_seq_a)} pairs\")\n if len(_seq_a) > 0:\n msa,mtx = [sequence],[[0]*len(sequence)]\n for s_a,s_b,m_a,m_b in zip(_seq_a, _seq_b, _mtx_a, _mtx_b):\n msa.append(_pad([a,b],[s_a,s_b],\"seq\"))\n mtx.append(_pad([a,b],[m_a,m_b],\"mtx\"))\n msas.append(msa)\n deletion_matrices.append(mtx)\n\n\n ####################################################################################\n ####################################################################################\n\n # save MSA as pickle\n pickle.dump({\"msas\":msas,\"deletion_matrices\":deletion_matrices},\n open(os.path.join(output_dir,\"msa.pickle\"),\"wb\"))\n pickle.dump({\"seqs\":seqs, \"homooligomers\":homooligomers, 'full_sequence':full_sequence, 'ori_sequence':ori_sequence},\n open(os.path.join(output_dir,\"seqs_oligos.pickle\"),\"wb\"))\n\n #########################################\n # Merge and filter\n #########################################\n msa_merged = sum(msas,[])\n if len(msa_merged) > 1:\n print(f'{len(msa_merged)} Sequences Found in Total')\n '''\n if pair_msa:\n ok = {0:True}\n print(\"running mmseqs2 to merge and filter (-id90) the MSA\")\n with open(\"tmp/raw.fas\",\"w\") as fas:\n for n,seq in enumerate(msa_merged):\n seq_unalign = seq.replace(\"-\",\"\")\n fas.write(f\">{n}\\n{seq_unalign}\\n\")\n os.system(\"mmseqs easy-linclust tmp/raw.fas tmp/clu tmp/mmseqs/tmp -c 0.9 --cov-mode 1 --min-seq-id 0.9 --kmer-per-seq-scale 0.5 --kmer-per-seq 80\")\n for line in open(\"tmp/clu_cluster.tsv\",\"r\"):\n ok[int(line.split()[0])] = True\n print(f'{len(ok)} Sequences Found in Total (after filtering)')\n else:\n '''\n ok = dict.fromkeys(range(len(msa_merged)),True)\n\n Ln = np.cumsum(np.append(0,[len(seq) for seq in seqs]))\n Nn,lines = [],[]\n n,new_msas,new_mtxs = 0,[],[]\n for msa,mtx in zip(msas,deletion_matrices):\n new_msa,new_mtx = [],[]\n for s,m in zip(msa,mtx):\n if n in ok:\n new_msa.append(s)\n new_mtx.append(m)\n n += 1\n if len(new_msa) > 0:\n new_msas.append(new_msa)\n new_mtxs.append(new_mtx)\n Nn.append(len(new_msa))\n msa_ = np.asarray([list(seq) for seq in new_msa])\n gap_ = msa_ != \"-\"\n qid_ = msa_ == np.array(list(sequence))\n gapid = np.stack([gap_[:,Ln[i]:Ln[i+1]].max(-1) for i in range(len(seqs))],-1)\n seqid = np.stack([qid_[:,Ln[i]:Ln[i+1]].mean(-1) for i in range(len(seqs))],-1).sum(-1) / gapid.sum(-1)\n non_gaps = gap_.astype(np.float)\n non_gaps[non_gaps == 0] = np.nan\n lines.append(non_gaps[seqid.argsort()]*seqid[seqid.argsort(),None])\n\n msas = new_msas\n deletion_matrices = new_mtxs\n\n Nn = np.cumsum(np.append(0,Nn))\n\n #########################################\n # Display\n #########################################\n\n lines = np.concatenate(lines,0)\n if len(lines) > 1:\n plt.figure(figsize=(8,5),dpi=100)\n plt.title(\"Sequence coverage\")\n plt.imshow(lines,\n interpolation='nearest', aspect='auto',\n cmap=\"rainbow_r\", vmin=0, vmax=1, origin='lower',\n extent=(0, lines.shape[1], 0, lines.shape[0]))\n for i in Ln[1:-1]:\n plt.plot([i,i],[0,lines.shape[0]],color=\"black\")\n\n for j in Nn[1:-1]:\n plt.plot([0,lines.shape[1]],[j,j],color=\"black\")\n\n plt.plot((np.isnan(lines) == False).sum(0), color='black')\n plt.xlim(0,lines.shape[1])\n plt.ylim(0,lines.shape[0])\n plt.colorbar(label=\"Sequence identity to query\",)\n plt.xlabel(\"Positions\")\n plt.ylabel(\"Sequences\")\n plt.savefig(os.path.join(output_dir,\"msa_coverage.png\"), bbox_inches = 'tight', dpi=200)\n # plt.show()\n\nfor record in SeqIO.parse(fasta_file, 'fasta'):\n jobname = record.description\n sequence = str(record.seq)\n get_msa(sequence, jobname, homooligomer_counts)","sub_path":"get_mmseq2.py","file_name":"get_mmseq2.py","file_ext":"py","file_size_in_byte":12971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619380145","text":"import json\n\n\nfor count in range(4):\n\n\tpathIn = \"C:\\\\Users\\\\Rohit\\\\Downloads\\\\jsontry\\\\\" + str(count) +\".json\"\n\tpathOut = \"C:\\\\Users\\\\Rohit\\\\Desktop\\\\Output\\\\\"+ str(count) +\".json\"\n\n\tpath_to_input = pathIn\n\tpath_to_output = pathOut\n\n\twith open(path_to_input) as json_file:\n\t\tdata_read =json.loads(json_file.read())\n\n\t\tdata_write = []\n\t\tpoints_json = {} \n\n\t\tfor pts in data_read['points']:\n\t\t\tdata = {};\n\t\t\trow = str(pts['x']) + \" \" + str(pts['y']) + \" \" + str(pts['z']) + \" \" + str(int(pts['i']))\n\t\t\tdata = row\n\n\t\t\tdata_write.append(data)\n\n\t\t\t\n\t\t\twith open(path_to_output, 'w') as write_json_file:\n\t\t\t\tjson.dump(data_write,write_json_file, indent =4)\n\t\tprint(len(data_read))\n","sub_path":"json2pcd.py","file_name":"json2pcd.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"321663189","text":"from __future__ import division\nfrom servoMotor_beta import *\nfrom collections import deque\nfrom tqdm import tqdm\nfrom camera import *\nfrom reachingLogs import *\nimport time\nimport threading\nimport os\nimport numpy as np\nimport argparse\n\nparser = argparse.ArgumentParser(description='Firmware for running the ReachingBot.')\nparser.add_argument('-v', '--videoSave', action='store_true', help='Do you want to save the videos?')\nparser.add_argument('-s', '--showImage', action='store_true', help='Do you want to display the live image?')\nparser.add_argument('-m', '--maxTrials', type=int, metavar='', required=True, help='Number of trials to execute.')\nparser.add_argument('-o', '--timeTrial', type=int, metavar='', required=True, help='Number of minutes for session.')\nparser.add_argument('-r', '--RFID', metavar='', help='RFID number of the animal.')\nparser.add_argument('-t','--timePoint', metavar='', help='Time point within your study in weeks.')\nparser.add_argument('-f','--flipped', action='store_true', help='Is the camera to the left?')\n\nargs = parser.parse_args()\n\ntrial_number = 1\n\nif args.videoSave and (args.RFID is None or args.timePoint is None):\n parser.error('--videoSave requires --RFID and --timePoint.')\n\nif args.videoSave:\n folder = \"{}_{}\".format(args.RFID, args.timePoint)\n if not os.path.exists(folder):\n os.makedirs((folder))\n else:\n trials = os.listdir(folder)\n nums = []\n for i in trials:\n if i.endswith('.avi'):\n tr = i.split(\"l\")[1].split(\".\")[0]\n nums.append(int(tr))\n if nums:\n trial_number = max(nums) + 1\n print(\"Reassigning trial number to {}\".format(trial_number))\n\nelse:\n pLog(\"Not saving videos.\")\n\ncroppingParameters = [120,200,160,260]\n\noverallTime = args.timeTrial * 60\nwaitTime = 5 * 60\nCam = Camera()\nframesforvideo = deque(maxlen=350) #contains the frames that'll get stored to video\ncameraStream = deque(maxlen=10) #containts the frames from the live stream\nblobs = deque(maxlen=10) #contains instances of the Pellet class\npelletPlaced = False #used to stop and start appending frames to buffer that'll get\nmotorSlow = False\ncameraOn = True\nactiveTimer = True\n\ndef remove(itemToRemove, wholeString):\n new = \"\"\n for i in wholeString:\n if i != itemToRemove:\n new += i\n return new\n\nclass Pellet:\n def __init__(self, x, y, size, timestamp):\n self.x = x\n self.y = y\n self.size = size\n self.timestamp = timestamp\n\ndef stopCamera():\n global cameraOn\n cameraOn = False\n\ndef videoProcess(finalFrames):\n global trial_number\n videoName = \"{}/{}_{}_trial{}.avi\".format(folder, args.RFID, args.timePoint, trial_number)\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(videoName, fourcc, 15, (320, 240))\n fps = len(finalFrames) / (finalFrames[-1].time - finalFrames[0].time)\n pLog((fps, \"- FPS\"))\n for n in tqdm(range(len(finalFrames)), position=1, desc=\"{} saving...\".format(videoName)):\n try:\n roi = cv2.cvtColor(finalFrames[n].frame, cv2.COLOR_GRAY2BGR)\n out.write(roi)\n except:\n pLog(\"this was the frame number: {}\".format(n))\n out.release()\n pLog(\"{} saved.\".format(videoName))\n trial_number += 1\n\ndef processFrame(frametoProcess, cropping=croppingParameters):\n y1, y2, x1, x2 = cropping\n _frame_ = frametoProcess[y1:y2, x1:x2]\n processed = BlobDetection(_frame_)\n if processed:\n x, y, size, time = processed\n return Pellet(x+x1, y+y1, size, time)\n else:\n return None\n\ndef blobStream():\n global cameraOn\n a, b, c, d = croppingParameters\n while cameraOn:\n if len(cameraStream) > 2:\n image = cameraStream[-1]\n pel = processFrame(frametoProcess=image)\n if pel:\n framesforvideo[-1].pellet = True\n blobs.append(pel)\n if args.showImage:\n cv2.circle(image, (int(pel.x), int(pel.y)), int(pel.size), (0, 0, 255), thickness=2, shift=0)\n if args.showImage:\n cv2.imshow(\"live frame\", image[a:b,c:d])\n cv2.waitKey(1) & 0xFF\n pLog(\"Blob detection off.\")\n\ndef isPellet():\n if len(blobs):\n return True\n else:\n return False\n\ndef getPel(slow=False):\n getPellet()\n goHome(slow)\n time.sleep(0.5)\n if isPellet():\n return True\n else:\n return False\n\ndef addFrames():\n global cameraOn\n while cameraOn:\n frametoProcess = Cam.FrameGenerator()\n if args.flipped:\n frametoProcess.frame = cv2.flip(frametoProcess.frame, 1)\n cameraStream.append(frametoProcess.frame)\n framesforvideo.append(frametoProcess)\n pLog(\"No longer adding frames.\")\n\ndef monitorPellet():\n global activeTimer\n global motorSlow\n first = time.time()\n while isPellet() and activeTimer:\n blobs.pop()\n second = time.time()\n diff = second - first\n if diff > waitTime:\n pLog(\"Trial timed out.\")\n return False\n if not blobs:\n pLog(\"Pellet no longer present.\")\n f_f_v = list(framesforvideo)\n pelletTruth = [x.pellet for x in f_f_v]\n number = sum(pelletTruth)\n pLog(\"Number of pellets in the video: {}/350\".format(number))\n if args.videoSave:\n pLog(\"Video now saving...\")\n if number > 20:\n time.sleep(1)\n vidSaveT = threading.Thread(target=videoProcess, args=(list(framesforvideo), ))\n vidSaveT.start()\n #videoProcess(_frames=toSave)\n #else:\n # pLog(\"There were only {} of pellets in this video and it's likely to be a dispense error.\".format(number))\n return True\n time.sleep(0.1)\n\ndef activateTrial():\n pLog(\"Trial active.\")\n if isPellet():\n if monitorPellet():\n return True\n else:\n return False\n else:\n pLog(\"Pellet not placed\")\n return False\n\ndef timer():\n global activeTimer\n counter = 0\n while activeTimer:\n counter += 1\n time.sleep(1)\n if counter > overallTime:\n activeTimer = False\n stopCamera()\n cv2.destroyAllWindows()\n pLog(\"Session ended after {} minute(s).\".format(args.timeTrial))\n break\n pLog(\"Timer terminated.\")\n\ndef stopTimer():\n global activeTimer\n activeTimer = False\n\nstart_stream = threading.Thread(target=addFrames)\nstart_stream.start()\n\nblob_stream = threading.Thread(target=blobStream)\nblob_stream.start()\n\ntime_stream = threading.Thread(target=timer)\ntime_stream.start()\n\nif __name__ == '__main__':\n trial = 0\n error = 0\n while activeTimer:\n print(\"ActiveTimer: {}\".format(activeTimer))\n try:\n if trial < int(args.maxTrials):\n pLog(\"Total errors: {}\".format(error))\n if error < 50:\n if motorSlow:\n slow = True\n else:\n slow = False\n if getPel(slow): #gets a pellet from the dispenser, returns true if pellet dispense is successful\n pLog(\"Trial {}\".format(trial))\n motorSlow = False\n if activateTrial():\n trial += 1\n else:\n error += 1\n error = 0\n else:\n pLog(\"No pellet detected.\")\n error += 1\n elif error >= 5:\n pLog(\"Too many failed pellet retrievals\")\n break\n else:\n break\n else:\n pLog(\"Trials ended\")\n break\n\n except KeyboardInterrupt:\n stopCamera()\n stopTimer()\n stopMotors()\n cv2.destroyAllWindows()\n pLog(\"program terminated\")\n break\n\n cv2.destroyAllWindows()\n stopTimer()\n stopMotors()\n stopCamera()\n print(\"All done here\")\n","sub_path":"reachingBot.py","file_name":"reachingBot.py","file_ext":"py","file_size_in_byte":8242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"582843280","text":"import argparse\nimport numpy as np\nimport pandas\n#from svm import weight_vector, find_support, find_slack\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import cross_val_score, GridSearchCV\nfrom data_mgmt import Faces\nfrom sklearn.externals import joblib\n\t\t\ndef mnist_digit_show(flatimage, outname=None):\n\n\timport matplotlib.pyplot as plt\n\n\timage = np.reshape(flatimage, (-1,28))\n\n\tplt.matshow(image, cmap=plt.cm.binary)\n\tplt.xticks([])\n\tplt.yticks([])\n\tif outname:\n\t plt.savefig(outname)\n\telse:\n\t plt.show()\n\ndef linearClassify(train_x, train_y, name):\n crng = np.logspace(-2,10,13)\n param_grid = dict(C=crng)\n grid = GridSearchCV(SVC(kernel=\"linear\"), param_grid=param_grid, cv=2, n_jobs=4, verbose=2)\n grid.fit(train_x, train_y)\n joblib.dump((\"linear\",grid.best_score_, grid.best_params_), \"linear_params_{}.pkl\".format(name))\n\ndef polyClassify(train_x, train_y, name):\n crng = np.logspace(-2,10,13)\n drng = [1,2,3,4]\n coefrng = np.logspace(-2,2,13)\n param_grid = dict(C=crng, degree=drng, coef0=coefrng)\n grid = GridSearchCV(SVC(kernel=\"poly\"), param_grid=param_grid, cv=2, n_jobs=4, verbose=2)\n grid.fit(train_x, train_y)\n joblib.dump((\"poly\",grid.best_score_, grid.best_params_), \"poly_params_{}.pkl\".format(name))\n\ndef rbfClassify(train_x, train_y, name):\n crng = np.logspace(-2,10,13)\n grng = np.logspace(-9,3,13)\n param_grid = dict(C=crng,gamma=grng)\n grid = GridSearchCV(SVC(kernel=\"rbf\"), param_grid=param_grid, cv=2, n_jobs=4, verbose=2)\n grid.fit(train_x, train_y)\n joblib.dump((\"rbf\",grid.best_score_, grid.best_params_), \"rbf_params_{}.pkl\".format(name))\n\ndef sigClassify(train_x, train_y, name):\n crng = np.logspace(-2,10,13)\n grng = np.logspace(-9,3,13)\n coefrng = np.logspace(-2,2,13)\n param_grid = dict(C=crng,gamma=grng,coef0=coefrng)\n grid = GridSearchCV(SVC(kernel=\"sigmoid\"), param_grid=param_grid, cv=2, n_jobs=4, verbose=2)\n grid.fit(train_x, train_y)\n joblib.dump((\"sigmoid\",grid.best_score_, grid.best_params_), \"sig_params_{}.pkl\".format(name))\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='SVM classifier options')\n parser.add_argument('--limit', type=int, default=-1,\n help=\"Restrict training to this many examples\")\n parser.add_argument('--filename', type=str, default=\"data\", help=\"The data file you are using\")\n args = parser.parse_args()\n\n data = Faces(hist_equal = True, filename=args.filename)\n train_x = data.train_x[:args.limit]\n train_y = data.train_y[:args.limit]\n \n linearClassify(train_x, train_y, args.filename)\n polyClassify(train_x, train_y, args.filename)\n rbfClassify(train_x, train_y, args.filename)\n sigClassify(train_x, train_y, args.filename)\n\n # Display in on screen\n #mnist_digit_show(data.train_x[lin_sup_3], \"lin3\")\n #mnist_digit_show(data.train_x[lin_sup_8], \"lin8\")\n\n\t# Plot image to file\n#\tmnist_digit_show(data.train_x[1,:], \"mnistfig.png\")\n\n\n\n\n\n\n\n\n\n","sub_path":"super_gridsearch.py","file_name":"super_gridsearch.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"468062623","text":"# Name: Jacob Wren\n# Course: CPE 101\n# Instructor: Irene Humer\n# Assignment: Problem setc\n# Term: Winter 2020\n\n\ndef reverse_string(chars, index):\n if len(chars) == 0:\n return None\n if index + 1 == len(chars):\n return chars[index]\n index = index + 1\n return reverse_string(chars, index) + chars[index - 1]\n\n\ndef is_palindrome(chars, index):\n if index == len(chars):\n return True\n if chars[index] == chars[1 - index -1]:\n index = index + 1\n return is_palindrome(chars, index)\n else:\n return False\n\n\ndef find_max(ints, index):\n if index == len(ints) - 1:\n return ints[index]\n if find_max(ints, index + 1) > ints[index]:\n return find_max(ints, index + 1)\n else:\n return ints[index]\n\n\ndef mul(x, y):\n if y <= 0:\n return 0\n return x + mul(x, y - 1)\n\n\ndef exp(x, y):\n if y <= 0:\n return 1\n return mul(exp(x, y - 1), x)\n\n\ndef factorial(n):\n if n == 0:\n return 1\n return mul(factorial(n - 1), n)\n\n\ndef fibonacci(n, acc):\n if n == 0:\n return 0\n if n == 1:\n return 1\n return fibonacci(n - 2, acc) + fibonacci(n - 1, acc)\n\n\ndef binary_search(ints, n, start, end):\n avg = (start + end) // 2\n if start == 0 and end == len(ints):\n end = len(ints) - 1\n if ints[avg] == n:\n return avg\n elif start == end:\n return -1\n if n > ints[avg]:\n return binary_search(ints, n, avg + 1, end)\n elif n < ints[avg]:\n return binary_search(ints, n, start, avg)\n","sub_path":"ProblemSets/psetc.py","file_name":"psetc.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"140351915","text":"#!/usr/bin/python\n#Obtains the difference of external data from shift constants. \n#If use_simulation is True, it will output the deltas of the simulation by importing it from a pdb.cs file.\n#If it's false, it will compare them with the data consumed from experimental_data\n#use_simulation is False by default. Switch it to true with -sim parameter.\nimport sys, shift_constants, cs_file\n\ncomparison_basis = shift_constants.base\ncomparison_basis_beforeproline = shift_constants.beforeproline\n\ncapture_residues_start = 1 #the first residue we capture\ncapture_residues_end = 120 #the number after the last residue we capture\n\navg_file_name = './100ns1Z1M.averages.cs'\nexp_file_name = './uhrinova.csv'\nsim_del_file_name = './100ns1Z1M_deltas.csv'\nexp_del_file_name = './uhrinova_deltas.csv'\ncapture_atoms = ['N', 'CA', 'C', 'CB', 'H', 'HA']\n\nuse_simulation = {'-sim'}.issubset(sys.argv)\nwritecs = {'-writecs'}.issubset(sys.argv)\n\nif (use_simulation):\n in_file = avg_file_name\n out_file = sim_del_file_name\nelse:\n in_file = exp_file_name\n out_file = exp_del_file_name\n\nif {'-o'}.issubset(sys.argv):\n out_file = sys.argv[sys.argv.index('-o') + 1]\n\nif {'-i'}.issubset(sys.argv):\n in_file = sys.argv[sys.argv.index('-i') + 1]\n\ndef obtainDeltas():\n deltas = {i: {'RES': '', 'NUM': i} for i in range(capture_residues_start, capture_residues_end)}\n {deltas[k].update({atom: 0 for atom in capture_atoms }) for k in deltas}\n \n comp = cs_file.readCSFile(in_file, 'NUM', 'SHIFT', 'ATOMNAME')\n \n for reskey in deltas:\n if not comp.get(reskey):\n #deltas.pop(reskey)\n continue\n deltas[reskey]['RES'] = comp[reskey]['RES']\n \n #determine if we're before proline and choose our shifts\n if (comp.get(reskey + 1)):\n comp_shift = comparison_basis[comp[reskey]['RES']] if comp[reskey + 1]['RES'] != 'P' else comparison_basis_beforeproline[comp[reskey]['RES']]\n else: \n comp_shift = comparison_basis[comp[reskey]['RES']]\n\n for atomname in capture_atoms:\n if comp[reskey].get(atomname):\n deltas[reskey][atomname] = comp[reskey][atomname] - comp_shift[atomname]\n elif deltas[reskey].get(atomname):\n deltas[reskey].pop(atomname)\n return deltas\n\nif writecs:\n cs_file.writeCSFile(out_file, 'DELTA', 'ATOMNAME', capture_atoms, obtainDeltas())\n","sub_path":"shift_deltas.py","file_name":"shift_deltas.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"146733975","text":"from typing import Optional\nimport os\nfrom nhltv_lib.arguments import get_arguments\n\n\ndef get_download_folder() -> str:\n \"\"\"\n Which folder should we download to?\n \"\"\"\n args = get_arguments()\n\n return args.download_folder or os.getcwd()\n\n\ndef get_retentiondays() -> Optional[int]:\n \"\"\"\n How many days should we retain videos?\n \"\"\"\n args = get_arguments()\n\n if args.retentiondays:\n retentiondays: Optional[int] = int(args.retentiondays)\n else:\n retentiondays = None\n\n return retentiondays\n","sub_path":"nhltv_lib/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"59056037","text":"from rest_framework import serializers\nfrom upload.models import FileUpload\n\n\nclass FileUploadSerializer(serializers.ModelSerializer):\n owner = serializers.Field(source='owner.username')\n\n class Meta:\n model = FileUpload\n fields = (\n 'owner',\n 'label',\n 'file_to_upload',\n )\n","sub_path":"Django/project/upload/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"486951382","text":"import sys\nimport os\nimport argparse\nimport collections\n\n\ndef list_dir(path):\n dir_info = collections.defaultdict(list)\n for current_dir, full_dir, file_names in os.walk(path):\n for file_name in file_names:\n full_path = os.path.join(current_dir, file_name)\n file_size = os.path.getsize(full_path)\n file_info = (file_name, file_size)\n dir_info[file_info].append(full_path)\n return dir_info\n\n\ndef find_duplicates(dir_full_info):\n for duplicate_file, path_of_duplicate in dir_full_info.items():\n if len(path_of_duplicate) > 1:\n print('\\nDuplicate files:')\n for name in path_of_duplicate:\n print('+', name)\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]):\n scan_directory = sys.argv[1]\n else:\n sys.exit('You forget enter path or file does not exist')\n directory_info = list_dir(scan_directory)\n find_duplicates(directory_info)\n","sub_path":"duplicates.py","file_name":"duplicates.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"445331371","text":"\n#Kütüphanelerin Eklendiği kısım\nimport numpy as np\nimport cv2\nimport datetime, time\n\nfrom gtts import gTTS\nimport os\nclass Renk_Tani():\n def konustur(self,metin):\n tts = gTTS(text=metin, lang=\"tr\")\n tts.save(\"metin.mp3\")\n os.system(\"metin.mp3\")\n\n def basla(self):\n metin1 = \"Bu cismin rengi {} dir\"\n\n # Pc nin kamerası ile görüntüyü alıyoruz\n webcam = cv2.VideoCapture(0,\n cv2.CAP_DSHOW) # İlk parametrenin 0 olması pc nin kamerasını kullanacağımız anlamına geliyor\n\n # Canlı bir g��rüntü olduğu için her şey sonsuz bir döngünün içerisinde yer almalı\n while (1):\n # Yakaladığımız görüntüyü burda okutma işlemi yapıyoruz ve bu işlem geriye 2 tane değer dönderiyor\n # bunlardan birisi çok önemli olmadığı için onu bu ' _ ' şekilde yakalıyoruz.\n _, imageFrame = webcam.read()\n\n # imageFrame i dönüştürme işlemi\n # BGR(RGB color space) to\n # HSV(hue-saturation-value)\n # renk uzayı belirleme\n hsvFrame = cv2.cvtColor(imageFrame, cv2.COLOR_BGR2HSV)\n\n # Kırmızı renk için renk aralığı ayarlama ve maske tanımlama\n red_lower = np.array([136, 87, 111], np.uint8)\n red_upper = np.array([180, 255, 255], np.uint8)\n red_mask = cv2.inRange(hsvFrame, red_lower, red_upper)\n\n # Yeşil renk için renk aralığı ayarlama ve maske tanımlama\n green_lower = np.array([25, 52, 72], np.uint8)\n green_upper = np.array([102, 255, 255], np.uint8)\n green_mask = cv2.inRange(hsvFrame, green_lower, green_upper)\n\n # Mavi renk için renk aralığı ayarlama ve maske tanımlama\n blue_lower = np.array([94, 80, 2], np.uint8)\n blue_upper = np.array([120, 255, 255], np.uint8)\n blue_mask = cv2.inRange(hsvFrame, blue_lower, blue_upper)\n\n # Morfolojik Dönüşüm ve Genişleme\n # yalnızca belirli rengi algılamak için\n kernal = np.ones((5, 5), \"uint8\") # np.ones() geriye 5 e 5 bir matris dönderir ve içerisi hep 1 dir\n\n # Kırmızı renk için\n red_mask = cv2.dilate(red_mask,\n kernal) # rengi genişletmek içindir yani red_mask giriyor ve kernal olarak genişliyor\n res_red = cv2.bitwise_and(imageFrame, imageFrame,\n mask=red_mask)\n\n # Yeşil renk için\n green_mask = cv2.dilate(green_mask, kernal)\n res_green = cv2.bitwise_and(imageFrame, imageFrame,\n mask=green_mask)\n\n # Mavi renk için\n blue_mask = cv2.dilate(blue_mask, kernal)\n res_blue = cv2.bitwise_and(imageFrame, imageFrame,\n mask=blue_mask)\n\n # Kırmızı rengi izlemek için kontur oluşturma\n # Konturlar aynı renk ve yoğunluğa sahip olan\n # tüm kesintisiz noktaları sınır boyunca birleştiren bir eğri olarak basitçe açıklanabilir\n \"\"\"\n 1.Birinci argüman kontur bulunacak kaynak görüntüdür.\n 2.İkinci argüman kontur alma modudur. \n 3.Üçüncü argüman ise kontur yaklaşım metodur.\n \"\"\"\n contours, hierarchy = cv2.findContours(red_mask,\n cv2.RETR_TREE,\n cv2.CHAIN_APPROX_SIMPLE)\n\n # Bulunan konturları enumerate işlemi yapılarak her biri tek tek ele alınır\n for pic, contour in enumerate(contours):\n area = cv2.contourArea(contour) # Burda konturların genişliği hesaplanır\n if (area > 300):\n \"\"\"\n bu kontur alanlarını dikdörtgen içine almak istiyoruz. \n Bunun için cv2.boundingRect() metodu ile kontur çerçeve noktalarını hesaplayıp \n cv2.rectangle() metoduyla etraflarına dikdörtgen çizebiliriz.\n \"\"\"\n x, y, w, h = cv2.boundingRect(contour)\n imageFrame = cv2.rectangle(imageFrame, (x, y),\n (x + w, y + h),\n (0, 0, 255), 2)\n\n cv2.putText(imageFrame, \"Kirmizi Renk\", (x, y),\n cv2.FONT_HERSHEY_SIMPLEX, 1.0,\n (0, 0, 255))\n\n #print(\"Kırmızı\")\n metin2 = metin1.format(\"kırmızı\")\n self.konustur(metin2)\n cv2.destroyAllWindows()\n return 1\n\n # Yeşil renk için contour bulma işlemi tekrarlanır\n contours, hierarchy = cv2.findContours(green_mask,\n cv2.RETR_TREE,\n cv2.CHAIN_APPROX_SIMPLE)\n\n for pic, contour in enumerate(contours):\n area = cv2.contourArea(contour)\n if (area > 300):\n x, y, w, h = cv2.boundingRect(contour)\n imageFrame = cv2.rectangle(imageFrame, (x, y),\n (x + w, y + h),\n (0, 255, 0), 2)\n\n cv2.putText(imageFrame, \"Yesil Renk\", (x, y),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1.0, (0, 255, 0))\n\n #print(\"Yeşil\")\n metin2=metin1.format(\"yeşil\")\n self.konustur(metin2)\n cv2.destroyAllWindows()\n return 1\n\n\n # Mavi renk için contour bulma işlemi tekrarlanır\n contours, hierarchy = cv2.findContours(blue_mask,\n cv2.RETR_TREE,\n cv2.CHAIN_APPROX_SIMPLE)\n for pic, contour in enumerate(contours):\n area = cv2.contourArea(contour)\n if (area > 300):\n x, y, w, h = cv2.boundingRect(contour)\n imageFrame = cv2.rectangle(imageFrame, (x, y),\n (x + w, y + h),\n (255, 0, 0), 2)\n\n cv2.putText(imageFrame, \"Mavi Renk\", (x, y),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1.0, (255, 0, 0))\n\n #print(\"Mavi\")\n metin2 = metin1.format(\"mavi\")\n self.konustur(metin2)\n cv2.destroyAllWindows()\n return 1\n\n\n # Program Termination\n cv2.imshow(\"Renk Tanimlama\", imageFrame)\n if cv2.waitKey(10) & 0xFF == ord('q'):\n # cv2.release()\n cv2.destroyAllWindows()\n break\n\n#ornek=Renk_Tani()\n#ornek.basla()\n","sub_path":"renkTanıma.py","file_name":"renkTanıma.py","file_ext":"py","file_size_in_byte":7189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"37013118","text":"# Copyright 2018 Airbus. 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\"\"\"Playground API routes.\n\"\"\"\n\n# utilities\nimport base64\nimport logging\nfrom datetime import datetime\n\n# web framework\nfrom flask import Flask, request, json\n\n# predictor\nfrom predict import Predict, PredictError\n\n\n# constants and global variables\napp = Flask(__name__)\npredictor = Predict(logging)\n\nZOOM_LEVEL = [ 16, 17 ]\n\n\n@app.route('/api/v1/openapi', methods=['GET'])\ndef openapi():\n \"\"\"\n GET /api/v1/openapi\n Return Geo Process API OpenAPI specification.\n \"\"\"\n with open('api_geo_process_v1.0.yaml', 'r') as content_file:\n content = content_file.read()\n \n return content\n\n\n@app.route('/api/v1/describe', methods=['GET'])\ndef describe():\n \"\"\"\n GET /api/v1/describe\n Return process description.\n \"\"\"\n # processing description and parameters\n data = {\n # to be changed by each process implementation\n \"name\": \"eu.gcr.io/playground-doc/tile-object-detection-stub\",\n \"title\": \"Playground tile object detection stub\",\n \"family\": \"\",\n \"version\": \"1.0\",\n \"description\": \"Geo Process API stub for \",\n \"organization\": \"Airbus Defence and Space Intelligence\",\n \"email\": \"playground-stub@airbus.com\",\n \"keywords\": \"TBC\",\n \"resources\": {\n \"cpu\": 1,\n \"ram\": 1048576\n },\n\n # valid values for Playground: tile-object-detection, tile-change-detection\n \"template\": \"tile-object-detection\",\n\n # specific to tile-object-detection\n \"input\": {\n \"$schema\": \"http://json-schema.org/draft-06/schema#\",\n \"title\": \"tile-object-detection-input\",\n \"description\": \"Geo Process API input schema for tile object detection\",\n \"type\" : \"object\",\n \"required\": [\n \"zoom\",\n \"tileFormat\",\n \"tile\"\n ],\n \"properties\": {\n \"zoom\": {\n \"description\": \"Tile zoom level\",\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 20\n },\n \"tileFormat\": {\n \"description\": \"MIME type of tile image format (image/png or image/jpeg)\",\n \"type\": \"string\"\n },\n \"tile\": {\n \"description\": \"The tile image base64 encoded, may be JPEG or PNG format\",\n \"type\": \"string\",\n \"format\": \"base64\"\n },\n \"mask\": {\n \"description\": \"Mask image base64 encoded in 8 bits PNG format\",\n \"type\": \"string\",\n \"format\": \"base64\"\n }\n }\n },\n\n # specific to tile-object-detection\n \"output\": {\n \"description\": \"Tile object detection GeoJSON. Root element has to be a 'FeatureCollection' with one or several 'Feature' objects. Feature geometry is expressed with (0,0) at the top left of the tile image padding included. Feature properties may be 'category' and 'confidence'. The 'category' property is used for tags, labels or classification results. It's value may be a string with several values separated by a comma or an array of strings. The 'confidence' property value is a float between 0. and 1.0.\",\n \"content\": {\n \"application/geo+json\": {}\n }\n },\n \n # specific to tile-object-detection\n \"config\": {\n \"$schema\": \"http://json-schema.org/draft-06/schema#\",\n \"title\": \"tile-object-detection-config\",\n \"description\": \"Geo Process API config schema for tile object detection\",\n \"type\" : \"object\",\n \"required\": [\n \"zoom\",\n \"padding\"\n ],\n \"properties\": {\n \"zoom\": {\n \"description\": \"Zoom levels that can be processed\",\n \"type\" : \"array\",\n \"minItems\": 1,\n \"items\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 17\n }\n },\n \"padding\": {\n \"description\": \"Padding / border needed to process the tile. 0 for no padding.\",\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 256\n }\n }\n },\n\n # Playground do not manage asynchronous processes\n \"asynchronous\": False,\n\n # can be changed by each process implementation\n \"_links\": {\n \"self\": {\n \"href\": \"/api/v1/describe\"\n },\n \"execution\": {\n \"href\": \"/api/jobs\"\n },\n \"config:\": {\n \"href\": \"/api/config\"\n },\n \"version\": {\n \"href\": \"/api/version\"\n }\n }\n }\n\n return json.dumps(data)\n\n\n@app.route('/api/jobs', methods=['POST'])\ndef jobs():\n \"\"\"\n POST /api/jobs\n Return detected objects from the given tile.\n \"\"\"\n try:\n # get input parameter\n correlation_id = request.headers.get('X-Correlation-ID')\n debug = request.headers.get('X-ADS-Debug').lower() in (\"yes\", \"true\", \"t\", \"1\")\n\n # get input data\n data = request.get_json()\n zoom = int(data['zoom'])\n tile_format = data['tileFormat']\n tile = base64.b64decode(data['tile'])\n if 'mask' in data:\n mask = base64.b64decode(data['mask'])\n else:\n mask = None\n\n if zoom not in ZOOM_LEVEL:\n raise Exception('Invalid zoom: ' + str(zoom))\n\n except Exception as error:\n logging.error('requestId: %s error: %s', correlation_id, error.message)\n # return invalid input error\n return '', 400\n\n try:\n # detect objects\n prediction = predictor.process(zoom, tile_format, tile, mask, debug)\n\n # return prediction result\n prediction = json.dumps(prediction)\n logging.debug('Prediction: %s', prediction)\n\n return prediction\n\n except PredictError as error:\n # return error message\n data = {\n \"message\": \"Prediction failed\",\n \"hint\": error.message,\n \"correlationId\": correlation_id,\n \"timestamp\": datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n }\n logging.error(data)\n return json.dumps(data), 500\n\n\n@app.route('/api/config', methods=['GET'])\ndef get_config():\n \"\"\"\n GET /api/config\n Return process configuration.\n \"\"\"\n data = {\n # to be changed by each process implementation\n \"zoom\": ZOOM_LEVEL,\n \"padding\": 20\n }\n\n return json.dumps(data)\n\n\n@app.route('/api/config', methods=['PUT'])\ndef set_config():\n \"\"\"\n PUT /api/config\n Set process configuration.\n \"\"\"\n # do nothing as this process is asynchronous and not statefull\n return '', 200\n\n\n@app.route('/api/version', methods=['GET'])\ndef version():\n \"\"\"\n POST /api/version\n Return internal versions.\n \"\"\"\n # implementation specific (can put VCS version, compiler, build environment ...)\n data = {\n }\n\n return json.dumps(data)\n\n\nif __name__ == '__main__':\n app.debug = False\n app.run(host='0.0.0.0', port=80)\n\n","sub_path":"stub/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":8007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268085576","text":"from foampostproc.dto.dto import CasesDirDTO, PointDTO, SliceDTO, CameraPropsDTO, FoamCaseDTO\nfrom foampostproc.core.model import Point, CameraSlice, CameraProps, FoamCase, CasesDir\n\n\nclass Mapper:\n @classmethod\n def map_foam_case_dto(cls, foam_case: FoamCaseDTO) -> FoamCase:\n cam_props = [cls.map_camera_props_dto(cam_prop) for cam_prop in foam_case.camera_props]\n slices_ = []\n for sl in foam_case.camera_slices:\n t = cls.map_slice_dto(sl)\n slices_.append(t)\n\n return FoamCase(foam_case._id,\n foam_case.name,\n cls.map_foam_cases_path_dto(foam_case.cases_dir),\n cam_props,\n slices_)\n\n @classmethod\n def map_foam_case_to_dto(cls, foam_case: FoamCase) -> FoamCaseDTO:\n cam_prop_dtos = [cls.map_camera_props_to_dto(cam_prop)\n for cam_prop in foam_case.cam_prop_list]\n slice_dtos = []\n for sl in foam_case.slice_list:\n t = cls.map_slice_to_dto(sl)\n slice_dtos.append(t)\n cases_path = cls.map_foam_cases_path_to_dto(foam_case.cases_dir)\n\n return FoamCaseDTO(cases_path,\n cam_prop_dtos,\n slice_dtos,\n foam_case.name,\n _id=foam_case.idn)\n\n @classmethod\n def map_foam_cases_path_dto(cls, foam_cases_path_dto: CasesDirDTO) -> CasesDir:\n return CasesDir(foam_cases_path_dto._id, foam_cases_path_dto.cases_path)\n\n @classmethod\n def map_foam_cases_path_to_dto(cls, foam_cases_path: CasesDir) -> CasesDirDTO:\n return CasesDirDTO(str(foam_cases_path.path), _id=foam_cases_path.idn)\n\n @classmethod\n def map_point_dto(cls, p_dto) -> Point:\n if isinstance(p_dto, PointDTO):\n return Point(p_dto.x, p_dto.y, p_dto.z)\n else:\n return Point(p_dto[\"x\"], p_dto[\"y\"], p_dto[\"z\"])\n\n @classmethod\n def map_point_to_dto(cls, p: Point) -> PointDTO:\n return PointDTO(p.x, p.y, p.z)\n\n @classmethod\n def map_slice_dto(cls, s_dto: SliceDTO) -> CameraSlice:\n sl_x = None if s_dto.sl_x is None else cls.map_point_dto(s_dto.sl_x)\n sl_y = None if s_dto.sl_y is None else cls.map_point_dto(s_dto.sl_y)\n sl_z = None if s_dto.sl_z is None else cls.map_point_dto(s_dto.sl_z)\n return CameraSlice(s_dto._id, s_dto.name, sl_x, sl_y, sl_z)\n\n @classmethod\n def map_slice_to_dto(cls, s: CameraSlice) -> SliceDTO:\n sl_x = None if s.sl_x is None else cls.map_point_to_dto(s.sl_x)\n sl_y = None if s.sl_y is None else cls.map_point_to_dto(s.sl_y)\n sl_z = None if s.sl_z is None else cls.map_point_to_dto(s.sl_z)\n return SliceDTO(s.name, sl_x, sl_y, sl_z, _id=s.idn)\n\n @classmethod\n def map_camera_props_dto(cls, c_dto: CameraPropsDTO) -> CameraProps:\n return CameraProps(c_dto._id,\n c_dto.name,\n cls.map_point_dto(c_dto.focal_point),\n cls.map_point_dto(c_dto.cam_position),\n c_dto.viewangle,\n cls.map_point_dto(c_dto.viewup))\n\n @classmethod\n def map_camera_props_to_dto(cls, c: CameraProps) -> CameraPropsDTO:\n focal_point_dto = cls.map_point_to_dto(c.focal_point)\n cam_position_dto = cls.map_point_to_dto(c.cam_position)\n viewup = cls.map_point_to_dto(c.viewup)\n return CameraPropsDTO(focal_point_dto, cam_position_dto,\n c.viewangle, viewup, c.name, _id=c.idn)\n","sub_path":"foampostproc/dto/modelmapper.py","file_name":"modelmapper.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"369828389","text":"n, numPairs = map(int, input().split())\npairs = []\nfor i in range(numPairs):\n pairs.append(tuple(map(int, input().split())))\n\n\ndef makeAdjArr(n, pairs):\n adj = [[0 for i in range(n)] for j in range(n)]\n for pair in pairs:\n a = pair[0] - 1\n b = pair[1] - 1\n adj[a][b] = 1\n adj[b][a] = 1\n return adj\n\n\nadj = makeAdjArr(n, pairs)\nfor i in range(len(adj)):\n print(*adj[i])\n","sub_path":"AdjacencyArray.py","file_name":"AdjacencyArray.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"229301526","text":"from django.shortcuts import render\n\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponse\nfrom django.template import Template, Context\nfrom django.template.context_processors import csrf\n#from django.views import View\nfrom django.views.generic import View\nfrom django.core import serializers\n\nimport json\n\nfrom opp.models import *\n\n# sympy\nimport sys,os\nimport sympy\nfrom sympy.abc import x,y,z,a,b,c,f,t,k,n\nfrom sympy import Eq, simplify, exp, cos, sin, Ne\n\n# latex2sympy\nsys.path.append('/Users/kvarela/sw/latex2sympy/')\nsys.path.append('C:\\\\Users\\\\felipe\\\\Desktop\\\\Projects and studying\\\\KIB Platform') \nsys.path.append('C:\\\\Users\\\\felipe\\\\Desktop\\\\Projects and studying\\\\KIB Platform\\\\latex2sympy')\n\n\n\nfrom latex2sympy.process_latex import process_sympy\n\ndef index(request):\n\treturn render(request,'index.html')\n\n\n\n#NOTE: Generic views is an option to call the DB form the template.\n\nclass ProblemConstructor:\n def __init__(self, topic_id_in, problem_name_in): \n \t#Call to the db Problem.\n \ttry:\n \t\tself.prob_in = Problem.objects.get(topic_id=topic_id_in,problem_name=problem_name_in)\n \texcept:\n \t\tself.prob_in = 'None'\n #check if the problem exists.\n def ProblemExist(self):\n \tif self.prob_in == 'None':\n \t\treturn HttpResponse('The problem does not exist.')\n \telse:\n \t\treturn self.prob_in\n\nclass StepConstructor:\n def __init__(self, s_name, prob_in):\n \ttry:\n \t\tself.step_base=Step.objects.get(step_name=s_name,problem_id=prob_in)\n \t\tself.data=serializers.serialize(\"json\", [self.step_base])\n \texcept:\n \t\tself.step_base = 'None'\n #check if the step exists.\n def StepExist(self):\n \tif self.step_base == 'None':\n \t\treturn HttpResponse('The step does not exist.')\n \telse:\n \t\treturn self.step_base\n\nclass SubstepConstructor:\n def __init__(self, s_id, sub_name):\n \ttry:\n \t\tself.substep_base=Substep.objects.get(step_id=s_id,substep_name=sub_name)\n \texcept:\n \t\tself.substep_base = 'None'\n #check if the step exists.\n def SubstepExist(self):\n \tif self.substep_base == 'None':\n \t\treturn HttpResponse('The substep does not exist.')\n \telse:\n \t\treturn self.substep_base\n\nclass SymbolConstructor:\n\t#TO DO: Define this automatically from the beginning of the problem.\n\t#Database with symbols based on the problems???\n\tdef __init__(self,symbols):\n\t\tself.symbol = []\n\t\tfor symbol in symbols:\n\t\t\tself.symbol.append(sympy.Symbol(symbol))\n\nclass StudentConstructor:\n\t#Definition of the student id. Temporarily it is a surrogate key.\n\t#TO DO: Define this as a method. This must go on the login part. We could do it as a form meanwhile.\n\tdef __init__(self,student_id_in):\n\t\tself.student_id = student_id_in\n\t\ttry:\n\t\t\tself.student_cons = Student.objects.get(id=self.student_id)\n\t\texcept:\n\t\t\tself.student_cons = 'None'\n\t#check if the user exists.\t\n\tdef StudentExist(self):\n\t\tif self.student_cons == 'None':\n\t\t\treturn HttpResponse('The substep does not exist.')\n\t\telse:\n\t\t\treturn self.student_cons\n\nclass CleanStudentAns:\n\tdef __init__(self,student_ans_in):\n\t\tself.data_st = []\n\t\tfor i in range(len(student_ans_in)):\n\t\t\tstudent_ans_2 = student_ans_in[i].split('=')\n\t\t\tif len(student_ans_2) > 2:\n\t\t\t\tfor i in range(1,len(student_ans_2)):\n\t\t\t\t\tself.data_st.append(student_ans_2[0] + '=' + student_ans_2[i])\n\t\t\telse:\n\t\t\t\tself.data_st=student_ans_in\n\nclass StudentProblemCons:\n\tdef __init__(self,st_id,p_id):\n\t\ttry:\n\t\t\tself.p_student = StudentProblem.objects.get(student_id = st_id,problem_id = p_id)\n\t\t\ttries = self.p_student.succesful_attemps + 1\n\t\t\tStudentProblem.objects.filter(student_id = st_id,problem_id = p_id).update(succesful_attemps=tries)\n\t\texcept:\n\t\t\tStudentProblem.objects.create(\n\t\t\t\tstudent_id = st_id,\n\t\t\t\tproblem_id = p_id,\n\t\t\t)\n\t\t\tself.p_student = StudentProblem.objects.get(student_id = p_student_id,problem_id = p_id)\n\nclass StudentStepCons:\n\tdef __init__(self,p_st_id,step_id_in):\n\t\ttry:\n\t\t\tself.step_st = StudentStep.objects.get(problem_student_id=p_st_id,step_id=step_id_in)\n\t\t\ttries = self.step_st.succesful_attemps + 1\n\t\t\tStudentStep.objects.filter(problem_student_id=p_st_id,step_id=step_id_in).update(succesful_attemps=tries)\n\t\texcept:\n\t\t\tStudentStep.objects.create(\n\t\t\t\tproblem_student_id=p_st_id,\n\t\t\t\tstep_id=step_id_in,\n\t\t\t)\n\t\t\tself.step_st = StudentStep.objects.get(problem_student_id=p_st_id,step_id=step_id_in)\n\nclass TemplateProcess(View):\n\t#TO DO: define __init__.\n\tdef __init__(self,topic_input='EQ-LINE',p_name_input='Oppgave 13'):\n\t\t#This will be read from the URL.\t\t\t\n\t\tself.topic_id_in = topic_input\n\t\tself.problem_name_in = p_name_input\n\t\t#Loading problem using the constructor to call the problem db. \n\t\tself.prob_cons = ProblemConstructor(self.topic_id_in,self.problem_name_in)\n\t\t#This number is read from the count method. Here I just use the Problem db.\n\t\tself.num_steps = self.prob_cons.prob_in.number_of_steps\n\t\t\n\t#This function is the one that loads and fills the problems is incomplete as it does not fill the number of steps and problem text yet see opp13.html# \n\tdef get(self, request, *args, **kwargs): \n\n\t\t\n\t\t#CHECK : What is a???\n\t\tsteps_a=list(range(0,self.num_steps+1))\n\t\texercise_title=self.problem_name_in\t\n\t\t\t\n\t\tc={\"exercise_title\":exercise_title,\"exercise_text\":self.prob_cons.prob_in.text,\"num_steps\":self.num_steps, \"steps_a\":steps_a}\n\t\treturn render(request, 'header.html',c)\n\nclass DataAjax(TemplateProcess):\n\tdef __init__(self):\n\t\tTemplateProcess.__init__(self)\n\t\t#TO DO: All the input from the student will be saved into a .txt file. \n\t\t#Read student answer\n\t\tself.student_cons = StudentConstructor('1')\n\t\t#student problem db.\n\t\tself.student_prob = StudentProblemCons(self.student_cons.student_cons,self.prob_cons.prob_in)\n\n\t#Method to process the ajax. step_ajax!!!\n\t#Why do we need this ajax?? The steps are send randomly!\n\tdef get(self, request, *args, **kwargs):\n\t\t#NOTE: This is sending three numbers!!! I need the actual step!\n\t\t#The step number 4 is not even sended with the ajax. It does not enter this function anymore.\n\t\tstep_number = json.loads(request.GET['step_number'])\n\t\ts_name='Step '+str(step_number)\n\t\t#getting the data from the steps database\n\t\tdatax=StepConstructor(s_name,self.prob_cons.prob_in).data\n\t\tprint(\"procesando el paso\")\n\t\treturn HttpResponse(datax, content_type='application/json')\n\nclass DataProcess(DataAjax):\n\tdef __init__(self):\n\t\tDataAjax.__init__(self)\n\t\tself.data = False\n\t\t\n\n\t#Process method. Here the student answer is processed.\n\tdef post(self, request, *args, **kwargs):\n\t\t#Definition of the symbols to be used within sympy.\n\t\tsymbols = ['theta','x_1','x_2','y_2','y_1']\n\t\tsymbol_output = SymbolConstructor(symbols)\n\t\t\n\t\t#Read student answer\n\t\tstep_number = json.loads(request.POST['step_number'])\n\t\ts_name='Step ' + str(step_number)\n\t\tprint(\"\\n \\n entre aqui2 \\n\\n\")\n\t\t#reading student answer and cleaning it.\n\t\tstudent_ans = CleanStudentAns(json.loads(request.POST['student_answer']))\n\t\t#getting the data from the steps database\n\t\tdatae=StepConstructor(s_name,self.prob_cons.prob_in).step_base\n\t\t\n\t\t#creating the step_student db.\n\t\tstep_student = StudentStepCons(self.student_prob.p_student,datae)\n\t\t\n\t\t#Compare student answer with db answer.\n\t\tfor i in range(0,len(student_ans.data_st)):\n\t\t\tdata_est=student_ans.data_st[i]\n\t\t\tfor j in range(0,datae.number_of_substeps):\n\t\t\t\tsub_name = 'Substep ' + str(j+1)\n\t\t\t\tdata_sol=SubstepConstructor(datae,sub_name)\n\n\t\t\t\tfor s in ['\\\\left','\\\\right']:\n\t\t\t\t\tdata_est_s=data_est.replace(s,'')\n\t\t\t\t\tdata_sol_s=data_sol.substep_base.answer.replace(s,'')\n\n\t\t\t\tdata_est_sympy=process_sympy(data_est_s)\n\t\t\t\tdata_sol_sympy=process_sympy(data_sol_s)\n\n\t\t\t\tdata_sol_sympy=str(data_sol_sympy).replace('{1}','1')\n\t\t\t\tdata_sol_sympy=sympy.simplify(data_sol_sympy.replace('{2}','2'))\n\n\t\t\t\tdata_est_sympy=str(data_est_sympy).replace('{1}','1')\n\t\t\t\tdata_est_sympy=sympy.simplify(data_est_sympy.replace('{2}','2'))\n\n\t\t\t\tdata_sim=sympy.simplify(data_est_sympy-data_sol_sympy)\n\t\t\t\t\n\t\t\t\t#TO DO: Change this so each substep of the student has to be OK.\n\t\t\t\tif data_sim == 0:\n\t\t\t\t\tself.data = True\n\t\t\t\t\tbreak\n\n\t\t\t\tif data_sim != 0:\n\t\t\t\t\tself.data = False\n\t\t\t\t\ti_temp = i + 1\n\t\t\n\t\t\tdatax = json.dumps(self.data)\n\t\t\t\n\t\t\treturn HttpResponse(datax, content_type='application/json');\n\t\telse:\n\t\t\treturn HttpResponse(\"Lo estas llamando malito\");\n\t\t\t\n\n\n\n","sub_path":"opp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"170097379","text":"import random\nimport string\nfrom collections import Counter\n\nfile_name = 'e_many_teams'\nw1 = 0.2\nw2 = 1\nw3 = 0.02\nmax_size = 0\nmax_freq = 0\n\n\n#hello\ndef parser():\n global max_size\n file1 = open(file_name+'.in', 'r')\n data = file1.readlines()\n #info_array = []\n first_line = data[0].split(\" \")\n #print([i.split(\" \") for i in data[1:]])\n info_array = [i[:-1].split(\" \") for i in data[1:]]\n max_size = max([int(i[0]) for i in info_array])\n\n file1.close()\n return [int(i) for i in first_line] , [i[1:] for i in info_array]\n\n\ndef write(final_indexes):\n file2 = open(file_name+'_results.in', 'w')\n file2.write(''.join(i for i in final_indexes))\n file2.close()\n\ndef evaluate(item, population_list):\n frequency = sum([(max_freq-population_list.get(i))/max_freq for i in item])/len(item)\n size = len(item)/max_size\n rand_num = random.random()\n return frequency*w1 + size*w2 + rand_num*w3\n\ndef potatoMain(length, info_array):\n population_list = Counter(row for item in info_array for row in item) \n global max_freq\n max_freq = max(population_list.values())\n score_list = []\n for i in range(0, length[0]):\n score_list.append([evaluate(info_array[i], population_list), i])\n\n score_list.sort(key=lambda pair: pair[0], reverse = True)\n\n result = [0]*length[0]\n for i in range(0, length[0]):\n result[i] = score_list[i][1]\n\n return result\n\ndef create_result(final_indexes, length):\n counter = 0\n result_array = []\n for i in range (0, length[3]):\n if(counter + 3 >= length[0]):\n break\n line = \"4 \" + str(final_indexes[counter]) + \" \" + str(final_indexes[counter+1]) + \" \" + str(final_indexes[counter+2]) + \" \" + str(final_indexes[counter+3]) + \"\\n\"\n result_array.append(line)\n counter = counter + 4\n\n for i in range (0, length[2]):\n if(counter + 2 >= length[0]):\n break\n line = \"3 \" + str(final_indexes[counter]) + \" \" + str(final_indexes[counter+1]) + \" \" + str(final_indexes[counter+2])+ \"\\n\"\n result_array.append(line)\n counter = counter + 3\n\n for i in range (0, length[1]):\n if(counter + 1 >= length[0]):\n break\n line = \"2 \" + str(final_indexes[counter]) + \" \" + str(final_indexes[counter + 1]) + \"\\n\"\n result_array.append(line)\n counter = counter + 2\n\n result_array.insert(0, str(len(result_array)) + \"\\n\")\n return result_array\n\n\ndef score():\n file1 = open(file_name+'_results.in', 'r')\n file2 = open(file_name+'.in', 'r')\n first_line = file1.readline()\n result = []\n for i in range(0 , int (first_line[:-1])):\n token_line = file1.readline()\n result.append(token_line[2:-1].split(\" \"))\n #print(result)\n first_line1 = file2.readline()\n info_array = []\n first_line1 = first_line1[:-1].split(\" \")\n for i in range(0 , int (first_line1[0])):\n token_line = file2.readline()\n info_array.append(token_line[2:-1].split(\" \"))\n\n same_res = 0\n score = [0] * int(first_line[:-1])\n for i in range(0, int(first_line[:-1])):\n addition = len([item for j in result[i] for item in info_array[int(j)]])\n score[i] = len(list(filter(None, set([item for j in result[i] for item in info_array[int(j)]]))))\n same_res = same_res + addition - score[i]\n score[i] = score[i]**2\n \n\n\n file1.close()\n file2.close()\n print(same_res)\n print(sum(score))\n print(max_size)\n return sum(score)\n\ndef automatic():\n max_w1 = 0\n max_score = 0\n global w1\n global w2\n w1 = 0\n w2 = 1\n for i in range(0,10):\n [length, info] = parser()\n final_indexes = potatoMain(length, info)\n write(create_result(final_indexes, length))\n cur_score = score()\n if(cur_score>max_score):\n max_score = cur_score\n max_w1 = w1\n\n w1 += 0.1\n w2 -= 0.1\n return max_score, max_w1\n \n\n\nif __name__ == '__main__':\n [length, info] = parser()\n #print(length)\n #print(info)\n final_indexes = potatoMain(length, info)\n write(create_result(final_indexes, length))\n score()\n #automatic()\n","sub_path":"hashcode2021/practice_round.py","file_name":"practice_round.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"259121992","text":"import sys\nimport os\nimport random\nimport numpy\nimport time\n\nfrom switch import switch\nimport ecl_parameter\nimport ecl_handler\nimport misfit_calculator\n\nclass Box(object):\n pass\n\ndata = Box()\n\ndef timetag():\n return \"[\"+time.strftime(\"%m/%d %H:%M:%S\")+\"]\"\n\n#def environmentSetup():\n# os.environ['F_UFMTENDIAN'] = 'big'\n# os.environ['SLBSLS_LICENCE_FILE'] = '27000@conclave'\n# os.environ['ECLPATH'] = '/home/caranha/ecl'\n\n\ndef loadParameterFile(filename):\n parmfile = open(filename,'r')\n\n# environmentSetup()\n\n data.parameters = []\n data.defaultParameters = []\n data.modeltype = None\n\n for lines in parmfile:\n lines = lines.strip()\n if (len(lines) > 0 and lines[0] != '#'): # ignore comments and blank lines\n tokens = lines.split('=')\n for case in switch(tokens[0].strip()):\n if case(\"ECLNAME\"):\n data.eclname = tokens[1].strip()\n break\n if case('MODELDIR'): \n data.modeldir = tokens[1].strip()\n break\n if case('OBSERVEDFILE'):\n data.observedData = readObservedData(\n data.modeldir+\"/\"+tokens[1].strip()\n )\n calculateObservedVarianceAndStd()\n break\n if case('RESULTINDEX'):\n data.resultIndex = [int (i) for i in tokens[1].strip().split(',')]\n break\n if case('PARAM'):\n params = tokens[1].strip().split(',')\n data.parameters.append(\n ecl_parameter.create(params[0],params[1],\n float(params[2]),float(params[3]),params[5]))\n data.defaultParameters.append(float(params[4]))\n break\n if case('TIMEOUT'):\n data.timeout = int(tokens[1].strip())\n break\n if case('MODELTYPE'):\n data.modeltype = tokens[1].strip()\n break\n if case():\n print(\"I don't understand this parameter: '\"+\n\t\t\t tokens[0].strip()+\"'\")\n\n#############################################################\n## Functions that Calculater parameter values\n# Parameter values from a [0,1] array (or equivalent)\ndef getUnormalizeParameters(weightarray):\n ret = []\n for i,w in zip(data.parameters,weightarray):\n ret.append(ecl_parameter.getRangeValue(i,w))\n return ret\n \n# Default parameter values\ndef getDefaultParameters():\n return data.defaultParameters\n\n# Random Parameter Values\ndef getRandomParameters():\n ret = []\n for i in data.parameters:\n ret.append(ecl_parameter.getRangeValue(i,random.random()))\n return ret\n \n##############################################################\n## Functions for obtained Historical Data\n# Calculates the observed data (used in initialization)\ndef readObservedData(datafile):\n ret = []\n data_file = open(datafile,'r')\n for line in data_file:\n line_split = line.split()\n if (len(line_split) > 0 and __testNumber(line_split[0])):\n row = []\n for i in line_split:\n row.append(float(i))\n ret.append(row)\n return ret\n\ndef calculateObservedVarianceAndStd():\n datavar = []\n for i in range(len(data.observedData[0])):\n datavar.append([])\n for i in data.observedData:\n for x,y in zip(datavar,i):\n x.append(y)\n data.observed_var = []\n data.observed_std = []\n for i in datavar:\n data.observed_var.append(numpy.var(i))\n data.observed_std.append(numpy.std(i))\n\ndef getObservedData():\n return data.observedData\n\n################################################################\n## Helper Functions\ndef __testNumber(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef getParameterLength():\n return len(data.defaultParameters)\n\n###################################################################\n## Functions used by an evolutionary algorithm\n\ndef runSimulation(parameters, verbose = False, normalized = True):\n if (normalized == True):\n param = getUnormalizeParameters(parameters)\n else:\n param = parameters\n result = ecl_handler.launchECL(\n param,\n data.parameters,\n data.eclname,\n data.modeldir,\n data.resultIndex,\n verbose = verbose,\n time_out = data.timeout,\n model_hack=data.modeltype\n )\n data.lastResult = result\n return result\n\n#### Evaluation functions\n# Parameters is a list of real valued parameters in the 0..1 range\ndef evaluateParameters(parameters, verbose = False, normalized = True):\n result = runSimulation(parameters, verbose, normalized)\n parameters.output = result\n parameters.timeout = (result==None)\n if (result != None):\n return (misfit_calculator.basic_MSE(result,getObservedData()),)\n else:\n return (sys.float_info.max/10,) ## maxfloat in python\n\n# Fitness evaluation based on existing papers (comparing only the oil output)\ndef evaluateParametersOilOnly(parameters, verbose = False, normalized = True):\n result = runSimulation(parameters, verbose, normalized)\n parameters.output = result\n parameters.timeout = (result==None)\n if (result != None):\n return (misfit_calculator.oil_variance_MSE(result,getObservedData(),1,divisor=data.observed_std[1]),)\n else:\n return (sys.float_info.max/10,)\n\ndef evaluateParametersVectorMisfit(parameters, verbose = False, normalized = True):\n result = runSimulation(parameters, verbose, normalized)\n parameters.output = result\n parameters.timeout = (result==None)\n if (result != None):\n return (misfit_calculator.vector_MSE(result,getObservedData()),)\n else:\n return (sys.float_info.max/10,) ## maxfloat in python\n\n# Dummy fitness function used for testing the code without calling eclipse\ndef evaluateDummy(parameters):\n parameters.output = \"Dummy\"\n parameters.timeout = False \n data.lastResult = None\n return (hash(tuple(parameters)),)\n\n","sub_path":"Code/simulationModel.py","file_name":"simulationModel.py","file_ext":"py","file_size_in_byte":6234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117723371","text":"from binfieldv2 import *\n\nSbox = bytearray(256*[0])\nInvSbox = bytearray(256*[0])\n\nfor i in range(256):\n Sbox[i] = (BinFieldElement(i, 8, '100011011') ** -1).simplify().value\n\n#print(list(Sbox))\n#print(len(set(Sbox)))\n\ndef cyclic_mul(a, b, m):\n return a * b % m + a * b // m\n\n\ndef cyclic_shift(a, b, m):\n return (a << b) % m + (a << b) // m\n\nb_s = lambda a, b: cyclic_shift(a, b, 256)\nsomeStrangeC = 99\n\n\ndef someStrangeFunc(b):\n global someStrangeC\n return b ^ b_s(b, 1) ^ b_s(b, 2) ^ b_s(b, 3) ^ b_s(b, 4) ^ someStrangeC\n\n\nfor i in range(256):\n Sbox[i] = someStrangeFunc(Sbox[i])\n\n\nfor i in range(256):\n InvSbox[Sbox[i]] = i\n\n\nmul_arr = 15 * [[]]\nfor i in [1, 2, 3, 9, 11, 13, 14]:\n mul_arr[i] = bytearray(256 * [0])\n for j in range(256):\n mul_arr[i][j] = (BinFieldElement(j, 8, '100011011') * BinFieldElement(i, 8, '100011011')).simplify().value\n\n\nRcon = [bytearray(4)]\ncurr = BinFieldElement(1, 8, '100011011')\nstep = BinFieldElement(2, 8, '100011011')\nfor i in range(10):\n Rcon.append(bytearray([curr.simplify().value, 0, 0, 0]))\n curr *= step\n\n\nf = open('Sbox', 'w')\nf.write(str(Sbox))\nf.close()\nf = open('InvSbox', 'w')\nf.write(str(InvSbox))\nf.close()\nf = open('mul_arr', 'w')\nf.write(str(mul_arr))\nf.close()\nf = open('Rcon', 'w')\nf.write(str(Rcon))\nf.close()","sub_path":"sboxgen.py","file_name":"sboxgen.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"118728484","text":"import re\nimport random\nimport matplotlib.pyplot as plt\n#from matplotlib.gridspec import subplot2grid\n#from matplotlib.gridspec import GridSpec\n#import matplotlib.patches as patches\n\ndef add_doc_type(number, doctype):\n\tif re.match('non', doctype):\n\t\tresponsive = 0\n\telse:\n\t\tresponsive = 1\n\n\ttemp_array = []\n\ti = 0\n\twhile i < number:\n\t\ttemp_array.append(responsive)\n\t\ti += 1\n\treturn temp_array\n\ndef create_population(responsive, nonresponsive):\n\ttemp_array = []\n\tfor x in add_doc_type(responsive,'responsive'):\n\t\ttemp_array.append(x)\n\tfor x in add_doc_type(nonresponsive,'nonresponsive'):\n\t\ttemp_array.append(x)\n\treturn temp_array\n\ndef get_sample(pop, sample_sz):\n\tsample = random.sample(pop,sample_sz)\n\n\t#returns number of responsive\n\tx = 0\n\tfor number in sample:\n\t\tif number == 1:\n\t\t\tx += 1\n\treturn x\n\ndef get_many_samples(pop,sample_sz, num_samples):\n\ttemp_array = []\n\tx = 0\n\twhile x < num_samples:\n\t\ta = get_sample(pop,sample_sz)\n\t\ttemp_array.append(1.0*a/sample_sz)\n\t\tx += 1\n\treturn temp_array\n\ndef get_mean(a_list):\n\tmean = sum(a_list)/len(a_list)\n\treturn mean\n\n#def get_RMS():\n#def get_STD():\n\n\npop_resp = 0.0\npop_total = 0.0\nsample_size = 300 #default size is 300\nnumber_samples = 25.0 #default number is 25\n\ndef get_numbers():\n total = float(input('Enter total population size: '))\n resp = float(input('Enter responsive (sub)population size: '))\n size = int(input('Enter the sample size: '))\n number = float(input('Enter the number of samples: '))\n return total, resp, size, number\n\ndef run_samples():\n [pop_total, pop_resp, sample_size, number_samples] = get_numbers()\n population = create_population(pop_resp,(pop_total-pop_resp))\n prevalence = float(pop_resp/pop_total)\n print('actual prevalence: {:.2f}'.format(prevalence))\n fracs = [100.0*pop_resp/pop_total, 100.0*(pop_total-pop_resp)/pop_total]\n avg_responsiveness = 100.0*get_mean(get_many_samples(population, sample_size, number_samples))\n sample_fracs = [avg_responsiveness, 100-avg_responsiveness]\n\n fig1 = plt.figure()\n #ax1 = fig1.add_subplot(121, aspect = 'equal')\n ax1 = plt.subplot2grid((2,6),(0,0), rowspan = 2, colspan = 3, aspect = 'equal')\n labels = ['R ({:.0f})'.format(pop_resp), 'NR ({:.0f})'.format(pop_total-pop_resp)]\n ax1.pie(fracs, labels=labels, colors=['red','blue'], autopct='%.0f%%')\n\n #ax2 = fig1.add_subplot(122, aspect = 'equal')\n ax2 = plt.subplot2grid((2,6),(0,4), aspect = 'equal')\n labels = ['R ({:.0f})'.format(avg_responsiveness*sample_size/100), 'NR ({:.0f})'.format(sample_size-(avg_responsiveness*sample_size/100))]\n ax2.pie(sample_fracs, labels=labels, colors=['red','blue'], autopct='%.0f%%')\n\n plt.tight_layout()\n\n fig1.savefig('sample_charts.png')\n\n \n \n'''\nfig1 = plt.figure()\nax1 = fig1.add_subplot(111,aspect = 'equal')\nax1.add_patch(patches.Rectangle((0.5,0.5), 1, 1))\nplt.axis('equal')\nplt.axis('off')\n#fig1.savefig('rect1.png', dpi= 90, bbox_inches='tight')\n#plt.show()\nfig1.savefig('your_graph.png')\n'''\n'''\nround_one = get_many_samples(population, sample_size, number_samples)\n#print(round_one)\nmean = get_mean(round_one)\ndifference = abs(mean - prevalence)\nprint('{:.3f}'.format(mean))\nprint('{:.3f}'.format(difference))\nprint(' ')\n'''\n'''\nsample_size = 1000\nnumber_samples = 25\nround_two = get_many_samples(population, sample_size, number_samples)\nprint(round_two)\nmean = get_mean(round_two)\ndifference = abs(mean - prevalence)\nprint(mean)\nprint(difference)\n'''\n","sub_path":"create_samples.py","file_name":"create_samples.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"550697616","text":"import pytest\nfrom scripts import rxiv2ja as rj\n\n\ndef test_remove_skipped_vals_no_val():\n val = None\n vals2skip = ['test_tag']\n result = rj.remove_skipped_vals(val, vals2skip)\n assert not result\n\n\ndef test_remove_skipped_vals_string_to_skip():\n val = 'test_tag'\n vals2skip = ['test_tag']\n result = rj.remove_skipped_vals(val, vals2skip)\n assert not result\n\n\ndef test_remove_skipped_vals_string_to_keep_w_no_vals2skip():\n val = 'test_tag'\n vals2skip = None\n result = rj.remove_skipped_vals(val, vals2skip)\n assert result == val\n\n\ndef test_remove_skipped_vals_string_to_keep_w_vals2skip():\n val = 'test_tag'\n vals2skip = ['some_other_val', 'and yet another']\n result = rj.remove_skipped_vals(val, vals2skip)\n assert result == val\n\n\ndef test_remove_skipped_vals_list_to_skip_2_items():\n val = ['test_val1', 'test_val2']\n vals2skip = ['test_val1', 'test_val2']\n result = rj.remove_skipped_vals(val, vals2skip)\n assert not result\n\n\ndef test_remove_skipped_vals_list_to_skip_remove_2_of_3():\n val = ['test_val1', 'test_val2', 'test_val3']\n vals2skip = ['test_val1', 'test_val2']\n result = rj.remove_skipped_vals(val, vals2skip)\n assert len(result) == 1\n assert result[0] == 'test_val3'\n\n\ndef test_remove_skipped_vals_no_vals_to_skip():\n val = ['test_val1', 'test_val2', 'test_val3']\n result = rj.remove_skipped_vals(val)\n assert result == val\n\n\ndef test_remove_skipped_vals_w_good_atids(mocker):\n side_effect = ['uuid1', 'uuid2', 'uuid1', 'uuid2', 'uuid3']\n val = ['id1', 'id2']\n vals2skip = ['id1', 'id2', 'id3']\n mocker.patch('functions.script_utils.get_item_uuid', side_effect=side_effect)\n result = rj.remove_skipped_vals(val, vals2skip)\n assert not result\n\n\ndef test_remove_skipped_vals_w_item_lookup(mocker):\n side_effect = ['uuid1', 'uuid2', 'uuid1']\n val = ['id1', 'id2']\n vals2skip = ['id1']\n mocker.patch('functions.script_utils.get_item_uuid', side_effect=side_effect)\n result = rj.remove_skipped_vals(val, vals2skip)\n assert result[0] == val[1]\n\n\ndef test_remove_skipped_vals_w_item_lookup_and_not_found(mocker):\n side_effect = ['uuid1', None, 'uuid3', 'uuid1', None]\n val = ['id1', 'id2', 'id3']\n vals2skip = ['id3', 'id4']\n mocker.patch('functions.script_utils.get_item_uuid', side_effect=side_effect)\n result = rj.remove_skipped_vals(val, vals2skip)\n assert result[0] == val[0]\n\n\n@pytest.fixture\ndef old_pub():\n return {\n 'title': 'The Title',\n 'authors': ['moe', 'curly'],\n 'ID': 'doi:1234',\n 'date_published': '2018-01-01',\n 'published_by': '4DN',\n 'exp_sets_prod_in_pub': ['4DNES1234567', '4DNES7654321'],\n 'exp_sets_used_in_pub': ['4DNES1111111'],\n 'categories': ['basic biology']\n }\n\n\n@pytest.fixture\ndef new_pub():\n return {\n 'title': 'The Title',\n 'authors': ['moe', 'curly'],\n 'ID': 'PMID:1',\n 'date_published': '2018-12-31',\n }\n\n\n@pytest.fixture\ndef fields2move():\n return [\n 'categories',\n 'exp_sets_prod_in_pub',\n 'exp_sets_used_in_pub',\n 'published_by'\n ]\n\n\ndef test_create_patch_for_new_from_old_patch_all(old_pub, new_pub, fields2move):\n patch, s = rj.create_patch_for_new_from_old(old_pub, new_pub, fields2move)\n for f, v in patch.items():\n assert old_pub[f] == patch[f]\n assert not s\n\n\ndef test_create_patch_for_new_from_old_patch_some(old_pub, new_pub, fields2move):\n dfield = 'exp_sets_used_in_pub'\n del old_pub[dfield]\n patch, s = rj.create_patch_for_new_from_old(old_pub, new_pub, fields2move)\n for f, v in patch.items():\n assert old_pub[f] == patch[f]\n assert dfield not in patch\n assert not s\n\n\ndef test_create_patch_for_new_from_old_patch_none(old_pub, new_pub, fields2move):\n for f in fields2move:\n del old_pub[f]\n patch, s = rj.create_patch_for_new_from_old(old_pub, new_pub, fields2move)\n assert not patch\n assert not s\n\n\ndef test_create_patch_for_new_from_old_patch_w_skipped(old_pub, new_pub, fields2move):\n sfield = 'exp_sets_used_in_pub'\n new_pub[sfield] = 'existing val'\n patch, s = rj.create_patch_for_new_from_old(old_pub, new_pub, fields2move)\n assert sfield not in patch\n assert s[sfield]['old'] == ['4DNES1111111']\n assert s[sfield]['new'] == 'existing val'\n\n\ndef test_create_patch_for_new_from_old_patch_w_val2skip(old_pub, new_pub, fields2move):\n v2s = ['4DNES1111111']\n patch, s = rj.create_patch_for_new_from_old(old_pub, new_pub, fields2move, v2s)\n assert 'exp_sets_used_in_pub' not in patch\n\n\ndef test_create_patch_for_new_from_old_patch_w_val2skip_w_multival(old_pub, new_pub, fields2move):\n v2s = ['4DNES7654321']\n patch, s = rj.create_patch_for_new_from_old(old_pub, new_pub, fields2move, v2s)\n assert len(patch['exp_sets_prod_in_pub']) == 1\n assert patch['exp_sets_prod_in_pub'][0] == '4DNES1234567'\n\n\ndef test_move_old_url_to_new_aka_w_existing_aka(old_pub, new_pub):\n old_pub['url'] = 'oldurl'\n new_pub['aka'] = 'my old name'\n p = {'field': 'value'}\n patch, s = rj.move_old_url_to_new_aka(old_pub, new_pub, p, {})\n assert p == patch\n assert s['aka']['new'] == 'oldurl'\n assert s['aka']['old'] == 'my old name'\n\n\ndef test_move_old_url_to_new_aka_w_no_url(old_pub, new_pub):\n new_pub['aka'] = 'my old name'\n p = {'field': 'value'}\n patch, s = rj.move_old_url_to_new_aka(old_pub, new_pub, p, {})\n assert p == patch\n assert not s\n\n\ndef test_move_old_url_to_new_aka_do_transfer(old_pub, new_pub):\n old_pub['url'] = 'oldurl'\n patch, s = rj.move_old_url_to_new_aka(old_pub, new_pub, {}, {})\n assert 'aka' in patch\n assert patch['aka'] == 'oldurl'\n assert not s\n\n\n@pytest.fixture\ndef pdict():\n return {\n 'exp_sets_prod_in_pub': ['4DNES1111111'],\n 'published_by': '4DN'\n }\n\n\ndef test_patch_and_report_w_dryrun_no_data(capsys, auth):\n result = rj.patch_and_report(auth, None, None, None, True)\n out = capsys.readouterr()[0]\n assert 'DRY RUN - nothing will be patched to database' in out\n assert 'NOTHING TO PATCH - ALL DONE!' in out\n assert result is True\n\n\ndef test_patch_and_report_w_skipped_no_patch(capsys, auth):\n skip = {\n 'published_by': {'old': 'external', 'new': '4DN'},\n 'categories': {'old': ['basic science'], 'new': ['methods']}\n }\n s1 = 'Field: published_by\\tHAS: 4DN\\tNOT ADDED: external'\n s2 = \"Field: categories\\tHAS: ['methods']\\tNOT ADDED: ['basic science']\"\n result = rj.patch_and_report(auth, None, skip, 'test_uuid', False)\n out = capsys.readouterr()[0]\n assert 'WARNING! - SKIPPING for test_uuid' in out\n assert s1 in out\n assert s2 in out\n assert 'NOTHING TO PATCH - ALL DONE!' in out\n assert result is True\n\n\ndef test_patch_and_report_w_patch(capsys, mocker, auth, pdict):\n mocker.patch('scripts.rxiv2ja.patch_metadata', return_value={'status': 'success'})\n result = rj.patch_and_report(auth, pdict, None, 'test_uuid', False)\n out = capsys.readouterr()[0]\n assert 'PATCHING - test_uuid' in out\n for k, v in pdict.items():\n s = '%s \\t %s' % (k, v)\n assert s in out\n assert 'SUCCESS!' in out\n assert result is True\n\n\ndef test_patch_and_report_w_fail(capsys, mocker, auth, pdict):\n mocker.patch('scripts.rxiv2ja.patch_metadata', return_value={'status': 'error', 'description': 'woopsie'})\n result = rj.patch_and_report(auth, pdict, None, 'test_uuid', False)\n out = capsys.readouterr()[0]\n assert 'PATCHING - test_uuid' in out\n for k, v in pdict.items():\n s = '%s \\t %s' % (k, v)\n assert s in out\n assert 'FAILED TO PATCH' in out\n assert 'woopsie' in out\n assert not result\n\n\ndef test_find_and_patch_item_references_no_refs(capsys, mocker, auth):\n old_uuid = 'old_uuid'\n new_uuid = 'new_uuid'\n output = \"No references to %s found.\" % old_uuid\n mocker.patch('scripts.rxiv2ja.scu.get_item_ids_from_args', return_value=[])\n result = rj.find_and_patch_item_references(auth, old_uuid, new_uuid, False)\n out = capsys.readouterr()[0]\n assert output in out\n assert result is True\n\n\ndef test_find_and_patch_item_references_w_refs(mocker, auth):\n old_uuid = 'old_uuid'\n new_uuid = 'new_uuid'\n mocker.patch('scripts.rxiv2ja.scu.get_item_ids_from_args', return_value=['bs_uuid', 'ex_uuid'])\n mocker.patch('scripts.rxiv2ja.patch_and_report', side_effect=[True, True])\n result = rj.find_and_patch_item_references(auth, old_uuid, new_uuid, False)\n assert result is True\n\n\ndef test_find_and_patch_item_references_w_refs_one_fail(mocker, auth):\n old_uuid = 'old_uuid'\n new_uuid = 'new_uuid'\n mocker.patch('scripts.rxiv2ja.scu.get_item_ids_from_args', return_value=['bs_uuid', 'ex_uuid1', 'ex_uuid2'])\n mocker.patch('scripts.rxiv2ja.patch_and_report', side_effect=[True, False, True])\n result = rj.find_and_patch_item_references(auth, old_uuid, new_uuid, False)\n assert not result\n","sub_path":"tests/test_rxiv2ja.py","file_name":"test_rxiv2ja.py","file_ext":"py","file_size_in_byte":8964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"9416076","text":"#!/usr/bin/env python3\n\"\"\"Classes and functions for testing the behavior of DFAs.\"\"\"\n\nimport types\nfrom unittest.mock import patch\n\nimport nose.tools as nose\n\nimport automata.shared.exceptions as exceptions\nimport tests.test_fa as test_fa\nfrom automata.fa.dfa import DFA\nfrom automata.fa.nfa import NFA\n\n\nclass TestDFA(test_fa.TestFA):\n \"\"\"A test class for testing deterministic finite automata.\"\"\"\n\n def test_init_dfa(self):\n \"\"\"Should copy DFA if passed into DFA constructor.\"\"\"\n new_dfa = DFA(self.dfa)\n self.assert_is_copy(new_dfa, self.dfa)\n\n def test_init_dfa_missing_formal_params(self):\n \"\"\"Should raise an error if formal DFA parameters are missing.\"\"\"\n with nose.assert_raises(TypeError):\n DFA(\n states={'q0', 'q1'},\n input_symbols={'0', '1'},\n initial_state='q0',\n final_states={'q1'}\n )\n\n def test_copy_dfa(self):\n \"\"\"Should create exact copy of DFA if copy() method is called.\"\"\"\n new_dfa = self.dfa.copy()\n self.assert_is_copy(new_dfa, self.dfa)\n\n @patch('automata.fa.dfa.DFA.validate_self')\n def test_init_validation(self, validate_self):\n \"\"\"Should validate DFA when initialized.\"\"\"\n DFA(self.dfa)\n validate_self.assert_called_once_with()\n\n def test_dfa_equal(self):\n \"\"\"Should correctly determine if two DFAs are equal.\"\"\"\n new_dfa = self.dfa.copy()\n nose.assert_true(self.dfa == new_dfa, 'DFAs are not equal')\n\n def test_dfa_not_equal(self):\n \"\"\"Should correctly determine if two DFAs are not equal.\"\"\"\n new_dfa = self.dfa.copy()\n new_dfa.final_states.add('q2')\n nose.assert_true(self.dfa != new_dfa, 'DFAs are equal')\n\n def test_validate_self_missing_state(self):\n \"\"\"Should raise error if a state has no transitions defined.\"\"\"\n with nose.assert_raises(exceptions.MissingStateError):\n del self.dfa.transitions['q1']\n self.dfa.validate_self()\n\n def test_validate_self_missing_symbol(self):\n \"\"\"Should raise error if a symbol transition is missing.\"\"\"\n with nose.assert_raises(exceptions.MissingSymbolError):\n del self.dfa.transitions['q1']['1']\n self.dfa.validate_self()\n\n def test_validate_self_invalid_symbol(self):\n \"\"\"Should raise error if a transition references an invalid symbol.\"\"\"\n with nose.assert_raises(exceptions.InvalidSymbolError):\n self.dfa.transitions['q1']['2'] = 'q2'\n self.dfa.validate_self()\n\n def test_validate_self_invalid_state(self):\n \"\"\"Should raise error if a transition references an invalid state.\"\"\"\n with nose.assert_raises(exceptions.InvalidStateError):\n self.dfa.transitions['q1']['1'] = 'q3'\n self.dfa.validate_self()\n\n def test_validate_self_invalid_initial_state(self):\n \"\"\"Should raise error if the initial state is invalid.\"\"\"\n with nose.assert_raises(exceptions.InvalidStateError):\n self.dfa.initial_state = 'q3'\n self.dfa.validate_self()\n\n def test_validate_self_invalid_final_state(self):\n \"\"\"Should raise error if the final state is invalid.\"\"\"\n with nose.assert_raises(exceptions.InvalidStateError):\n self.dfa.final_states = {'q3'}\n self.dfa.validate_self()\n\n def test_validate_input_valid(self):\n \"\"\"Should return correct stop state if valid DFA input is given.\"\"\"\n nose.assert_equal(self.dfa.validate_input('0111'), 'q1')\n\n def test_validate_input_rejection(self):\n \"\"\"Should raise error if the stop state is not a final state.\"\"\"\n with nose.assert_raises(exceptions.RejectionError):\n self.dfa.validate_input('011')\n\n def test_validate_input_rejection_invalid_symbol(self):\n \"\"\"Should raise error if an invalid symbol is read.\"\"\"\n with nose.assert_raises(exceptions.RejectionError):\n self.dfa.validate_input('01112')\n\n def test_validate_input_step(self):\n \"\"\"Should return validation generator if step flag is supplied.\"\"\"\n validation_generator = self.dfa.validate_input('0111', step=True)\n nose.assert_is_instance(validation_generator, types.GeneratorType)\n nose.assert_equal(list(validation_generator), [\n 'q0', 'q0', 'q1', 'q2', 'q1'\n ])\n\n def test_init_nfa_simple(self):\n \"\"\"Should convert to a DFA a simple NFA.\"\"\"\n nfa = NFA(\n states={'q0', 'q1', 'q2'},\n input_symbols={'0', '1'},\n transitions={\n 'q0': {'0': {'q0', 'q1'}},\n 'q1': {'1': {'q2'}},\n 'q2': {}\n },\n initial_state='q0',\n final_states={'q2'}\n )\n dfa = DFA(nfa)\n nose.assert_equal(dfa.states, {'{}', '{q0}', '{q0,q1}', '{q2}'})\n nose.assert_equal(dfa.input_symbols, {'0', '1'})\n nose.assert_equal(dfa.transitions, {\n '{}': {'0': '{}', '1': '{}'},\n '{q0}': {'0': '{q0,q1}', '1': '{}'},\n '{q0,q1}': {'0': '{q0,q1}', '1': '{q2}'},\n '{q2}': {'0': '{}', '1': '{}'}\n })\n nose.assert_equal(dfa.initial_state, '{q0}')\n nose.assert_equal(dfa.final_states, {'{q2}'})\n\n def test_init_nfa_lambda_transition(self):\n \"\"\"Should convert to a DFA an NFA with a lambda transition.\"\"\"\n dfa = DFA(self.nfa)\n nose.assert_equal(dfa.states, {'{}', '{q0}', '{q1,q2}'})\n nose.assert_equal(dfa.input_symbols, {'a', 'b'})\n nose.assert_equal(dfa.transitions, {\n '{}': {'a': '{}', 'b': '{}'},\n '{q0}': {'a': '{q1,q2}', 'b': '{}'},\n '{q1,q2}': {'a': '{q1,q2}', 'b': '{q0}'},\n })\n nose.assert_equal(dfa.initial_state, '{q0}')\n nose.assert_equal(dfa.final_states, {'{q1,q2}'})\n","sub_path":"tests/test_dfa.py","file_name":"test_dfa.py","file_ext":"py","file_size_in_byte":5882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"276627808","text":"import queue\nimport re\nimport copy\nimport math\nimport time\n\n# 设置全局变量\nsdes1 = '123456780'\ndes1 = [1, 2, 3, 4, 5, 6, 7, 8, 0]\nmymap = {}\nchangeId1 = [\n [-1, -1, 3, 1],\n [-1, 0, 4, 2],\n [-1, 1, 5, -1],\n [0, -1, 6, 4],\n [1, 3, 7, 5],\n [2, 4, 8, -1],\n [3, -1, -1, 7],\n [4, 6, -1, 8],\n [5, 7, -1, -1]\n]\nwasd = ['w', 'a', 's', 'd']\n\npos = {\n '1': [1, 1],\n '2': [1, 2],\n '3': [1, 3],\n '4': [2, 1],\n '5': [2, 2],\n '6': [2, 3],\n '7': [3, 1],\n '8': [3, 2],\n '9': [3, 3]\n}\n\nclass node(object):\n def __init__(self, num, step, zeroPos, order, degree):\n self.num = num\n self.step = step\n self.zeroPos = zeroPos\n self.order = order\n self.degree = degree\n self.cost = self.setCost()\n\n def __lt__(self, other):\n return self.cost < other.cost\n\n # 估价函数1,不在位的数\n # def setCost(self):\n # c = 0\n # for i in range(self.degree * self.degree):\n # if self.num[i] != des1[i]:\n # c = c + 1\n # return c + self.step\n\n # 估价函数2,每个块到目标状态的步数差\n def setCost(self):\n c = 0\n for i in range(self.degree * self.degree):\n if self.num[i] != des1[i]:\n temp = copy.deepcopy(self.num[i])\n if temp == 0:\n temp = 9\n x1 = pos[str(temp)][0]\n y1 = pos[str(temp)][1]\n x2 = pos[str(i + 1)][0]\n y2 = pos[str(i + 1)][1]\n res = abs(x1 - x2) + abs(y1 - y2)\n c = c + res\n return c + self.step\n\n# 将状态数组的字符串格式转为数组\ndef string_to_list(k):\n list = re.findall('\\d', k)\n temp = []\n for item in list:\n temp.append(int(item))\n return temp\n\n# 将状态数组转为字符串格式,为了放入字典中\ndef list_to_string(list):\n result = ''\n for item in list:\n result = result + str(item)\n return result\n\ndef bfsHash(start1, zero_row1, zero_column1, degree1):\n start = copy.deepcopy(start1)\n zero_row = copy.deepcopy(zero_row1)\n zero_column = copy.deepcopy(zero_column1)\n degree = copy.deepcopy(degree1)\n print('astart:', start)\n print('astart:', zero_row)\n print('astart:', zero_column)\n print('astart:', degree)\n zeroPos = zero_row * degree + zero_column\n first = node(start, 0, zeroPos, '', degree)\n que = queue.PriorityQueue()\n # 由于设置了全局变量,所以每次调用都要把队列清空,字典清空\n while not que.empty():\n que.get()\n mymap.clear()\n que.put(first)\n print(first.order)\n key = list_to_string(start)\n mymap[key] = 1\n if degree == 3:\n while not que.empty():\n tempN = que.get()\n # print(tempN.order)\n temp = tempN.num\n pos = tempN.zeroPos\n # 上下左右移动\n for i in range(4):\n if changeId1[pos][i] != -1:\n temp[pos], temp[changeId1[pos][i]] = temp[changeId1[pos][i]], temp[pos]\n k = list_to_string(temp)\n # 到达目标状态,返回结果\n if k == sdes1:\n write_order(tempN.order + wasd[i])\n return change(tempN.order + wasd[i])\n if k not in mymap.keys():\n list = string_to_list(k)\n tempM = node(list, tempN.step+1, changeId1[pos][i], tempN.order + wasd[i], degree)\n que.put(tempM)\n mymap[k] = 1\n temp[pos], temp[changeId1[pos][i]] = temp[changeId1[pos][i]], temp[pos]\n# 将AI序列写入txt文件中\ndef write_order(string):\n list = re.findall('[a-z]', string)\n temp = ''\n for i in range(len(list)):\n if list[i] == 'w':\n temp = temp + '第' + str(i + 1) + '步:下' + '\\n'\n elif list[i] == 'a':\n temp = temp + '第' + str(i + 1) + '步:右' + '\\n'\n elif list[i] == 's':\n temp = temp + '第' + str(i + 1) + '步:上' + '\\n'\n else:\n temp = temp + '第' + str(i + 1) + '步:左' + '\\n'\n with open('order.txt', 'a') as file_handle:\n file_handle.truncate(0)\n file_handle.write(temp)\n file_handle.close()\n\n# 改变AI序列字符串形式为数字形式\ndef change(string):\n # 正则匹配\n list = re.findall('[a-z]', string)\n walk = []\n for item in list:\n if item == 'w':\n walk.append(1)\n elif item == 'a':\n walk.append(3)\n elif item == 's':\n walk.append(0)\n else:\n walk.append(2)\n return walk\n\n\n# list = [5, 1, 3, 0, 8, 4, 2, 6, 7]\n# time1 = time.time()\n# walklist = bfsHash(list, 1, 0, 3)\n# time.sleep(1)\n# time2 = time.time()\n# print('time:', time2 - time1)\n# print(walklist)\n# print(len(walklist))\n\n","sub_path":"GUI/Astar.py","file_name":"Astar.py","file_ext":"py","file_size_in_byte":4944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"230557971","text":"from concurrent import futures\nimport logging\nimport typing as ty\nimport itertools\n\nimport strax\nexport, __all__ = strax.exporter()\n\n\n@export\nclass ProcessorComponents(ty.NamedTuple):\n \"\"\"Specification to assemble a processor\"\"\"\n plugins: ty.Dict[str, strax.Plugin]\n loaders: ty.Dict[str, ty.Iterator]\n savers: ty.Dict[str, ty.List[strax.Saver]]\n targets: ty.Tuple[str]\n\n\n@export\nclass ThreadedMailboxProcessor:\n mailboxes: ty.Dict[str, strax.Mailbox]\n\n def __init__(self, components: ProcessorComponents, max_workers=None):\n self.log = logging.getLogger(self.__class__.__name__)\n self.components = components\n self.log.debug(\"Processor components are: \" + str(components))\n plugins = components.plugins\n savers = components.savers\n\n # Executors for parallelization\n process_executor = futures.ProcessPoolExecutor(max_workers=max_workers)\n thread_executor = futures.ThreadPoolExecutor(max_workers=max_workers)\n\n # If possible, combine save and compute operations\n # so they don't have to be scheduled by executor individually.\n # This saves data transfer between cores (NUMA).\n for d, p in plugins.items():\n if not p.rechunk_on_save:\n self.log.debug(f\"Putting savers for {d} in post_compute\")\n for s in savers.get(d, []):\n p.post_compute.append(s.save)\n p.on_close.append(s.close)\n savers[d] = []\n\n # For the same reason, merge simple chains:\n # A -> B => A, with B as post_compute,\n # then put in plugins as B instead of A.\n # TODO: check they agree on paralellization?\n # TODO: allow compute grouping while saver does rechunk\n while True:\n for b, p_b in plugins.items():\n if (p_b.parallel and not p_b.rechunk_on_save\n and len(p_b.depends_on) == 1\n and b not in components.targets):\n a = p_b.depends_on[0]\n if a not in plugins:\n continue\n self.log.debug(f\"Putting {b} in post_compute of {a}\")\n p_a = plugins[a]\n p_a.post_compute.append(plugins[b].do_compute)\n p_a.on_close.extend(p_b.on_close)\n plugins[b] = p_a\n del plugins[a]\n break # Changed plugins while iterating over it\n else:\n break\n\n self.log.debug(\"After optimization: \" + str(components))\n\n self.mailboxes = {\n d: strax.Mailbox(name=d + '_mailbox')\n for d in itertools.chain.from_iterable(components)}\n\n for d, loader in components.loaders.items():\n assert d not in plugins\n self.mailboxes[d].add_sender(loader, name=f'load:{d}')\n\n for d, p in plugins.items():\n\n executor = None\n if p.parallel == 'process':\n executor = process_executor\n elif p.parallel:\n executor = thread_executor\n\n self.mailboxes[d].add_sender(p.iter(\n iters={d: self.mailboxes[d].subscribe()\n for d in p.depends_on},\n executor=executor),\n name=f'build:{d}')\n\n for d, savers in savers.items():\n for s_i, saver in enumerate(savers):\n self.mailboxes[d].add_reader(saver.save_from,\n name=f'save_{s_i}:{d}')\n\n def iter(self):\n target = self.components.targets[0]\n final_generator = self.mailboxes[target].subscribe()\n\n self.log.debug(\"Starting threads\")\n for m in self.mailboxes.values():\n m.start()\n\n self.log.debug(f\"Yielding {target}\")\n try:\n yield from final_generator\n except strax.MailboxKilled as e:\n self.log.debug(f\"Target Mailbox ({target}) killed\")\n for m in self.mailboxes.values():\n if m != target:\n self.log.debug(f\"Killing {m}\")\n m.kill(upstream=True,\n reason=e.args[0])\n\n self.log.debug(\"Closing threads\")\n for m in self.mailboxes.values():\n m.cleanup()\n","sub_path":"strax/processor.py","file_name":"processor.py","file_ext":"py","file_size_in_byte":4340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"257673490","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 23 20:11:02 2020\n\n@author: lizam\n\"\"\"\n\n\n# Homework 3 Problem 3 - ODE package that includes Euler's method, \n# Heun's method, and the explicit RK4 method\n\nimport numpy as np\n# import matplotlib.pyplot as plt\n\n# Defining a function to use for the following ODE package\ndef myfunc(x, y):\n dy = np.zeros((len(y)))\n dy[0] = np.exp(-2*x) - 2*y[0]\n return(dy)\ndef pend(y, t):\n b = 0.25\n c = 5.0\n theta, omega = y\n dydt = [omega, -b*omega - c*np.sin(theta)]\n return(dydt)\n# Function module used to evaluate equations\ndef feval(funcName, *args):\n b = 0.25\n c = 5.0\n return(eval(funcName)(*args))\n\n# Euler's Methods:\n# Forward Euler's Method\ndef forwardE(func, yinit, x_range, h):\n print((x_range[-1] - x_range[0]) / h)\n fnODEs = len(yinit) # Number of ODEs\n fsub_int = int((x_range[-1] - x_range[0]) / h) # Number of sub-intervals\n fsubint = np.vectorize(fsub_int)\n fx = x_range[0] # Initializes variables x\n fy = yinit # Initializes variables y\n # Creates arrays for solutions\n fxsol = [fx]\n fysol = [fy[0]]\n for i in range(fsubint):\n fyp = feval(func, fx, fy) # Evaluates dy/dx\n for j in range(fnODEs):\n fy[j] = fy[j] + h*fyp[j] \n fx += h # Increases the x-step\n fxsol.append(fx) \n for r in range(len(fy)):\n fysol.append(fy[r]) \n return([fxsol, fysol])\n\n# Testing out Forward Euler\n# Setting parameters first, easier this way\n# fh = 0.001\n# fx = [0.0, 2.0]\n# fyinitef = [4.0]\n# [tsef, ysef] = forwardE('myfunc', fyinitef, fx, fh)\n\n\n\n# Backward Euler's Method\n# Defining a vector and multiplying by a scalar\ndef mult(vector, scalar):\n newv = [0]*len(vector)\n for i in range(len(vector)):\n newv[i] = vector[i]*scalar\n return(newv)\n# Backward Euler's\ndef backwardE(func, yinit, x_range):\n h = .001\n bnODEs = len(yinit)\n bsub_int = int((x_range[-1] - x_range[0]) / h)\n bx = x_range[0]\n by = yinit\n bxsol = [bx]\n bysol = [by[0]]\n for i in range(bsub_int):\n bypr = feval(func, bx+h, by)\n byp = mult(bypr, (1 / (1+h)))\n for j in range(bnODEs):\n by[j] = by[j] + h*byp[j]\n bx += h\n bxsol.append(bx)\n for r in range(len(by)):\n bysol.append(by[r]) # Saves all new y's\n return([bxsol, bysol])\n# Testing out Backward Euler\n# bh = 0.001\n# bx = [0.0, 2.0]\n# byiniteb = [4.0]\n# [tseb, yseb] = backwardE('myfunc', byiniteb, bx, bh)\n\n\n\n# Heun's Method\ndef Heuns(func, yinit, x_range):\n h = .001\n hnODEs = len(yinit)\n hsub_int = int((x_range[-1] - x_range[0])/h)\n hx = x_range[0]\n hy = yinit\n hxsol = [hx]\n hysol = [hy[0]]\n for i in range(hsub_int):\n hy0p = feval(func, hx, hy)\n hk1 = mult(hy0p, h)\n hypred = [u + v for u, v in zip(hy, hk1)]\n hy1p = feval(func, hx+h, hypred)\n for j in range(hnODEs):\n hy[j] = hy[j] + (h/2)*hy0p[j] + (h/2)*hy1p[j]\n hx = hx + h\n hxsol.append(hx)\n for r in range(len(hy)):\n hysol.append(hy[r])\n return([hxsol, hysol])\n# Testing out Heun's\n# hh = 0.001\n# hx = [0.0, 2.0]\n# hyinith = [4.0]\n# [tsh, ysh] = Heuns('myfunc', hyinith, hx, hh)\n \n\n\n# RK4 Method\ndef RK4(func, yinit, x_range, h):\n m = len(yinit)\n n = int((x_range[-1] - x_range[0]) / h)\n rx = x_range[0]\n ry = yinit\n rxsol = np.empty(0)\n rxsol = np.append(rxsol, rx)\n rysol = np.empty(0)\n rysol = np.append(rysol, ry)\n # Settng up RK4\n for i in range(n):\n # First RK4 Step\n k1 = feval(func, rx, ry)\n yp2 = ry + k1 * (h/2)\n # Second RK4 Step\n k2 = feval(func, (rx+h)/2, yp2)\n yp3 = ry + k2 * (h/2)\n # Third RK4 Step\n k3 = feval(func, (rx+h)/2, yp3)\n yp4 = ry + k3 * h\n # Fourth RK4 Step\n k4 = feval(func, rx+h, yp4)\n for j in range(m):\n # RK4 Formula\n ry[j] = ry[j] + (h/6)*(k1[j] + 2*k2[j] + 2*k3[j] + k4[j]) \n # Defining an x to later use in function\n rx = rx + h\n rxsol = np.append(rxsol, rx)\n # Corresponding y\n for r in range(len(ry)):\n rysol = np.append(rysol, ry[r])\n rsol = [rxsol, rysol]\n return(rsol)\n# Testing out RK4\n# Setting parameters\n# rh = 0.001\n# rx = np.array([0.0, 2.0])\n# ryinitr = np.array([1.0/10])\n# [tsr, ysr] = RK4('myfunc', ryinitr, rx, rh)\n# print([ts, ys])\n\n\n\n# Plotting to compare\n# plt.plot(tsef, ysef, linestyle='--', c='k', label='Forward Eulers')\n# plt.plot(tseb, yseb, linestyle=':', c='m', label='Backward Eulers')\n# plt.plot(tsr, ysr, c='r', label='RK4')\n# plt.plot(tsh, ysh, linestyle='-.', c='orange', label='Heuns')\n# Exact Solution\n# dt = int((rx[-1]-rx[0])/rh)\n# t = [rx[0]+i*rh for i in range(dt+1)] \n# yexact = []\n# for i in range(dt+1):\n# ye = (1.0/10)*np.exp(-2*t[i]) + t[i]*np.exp(-2*t[i])\n# yexact.append(ye)\n# plt.plot(t, yexact, 'b', label='Exact Solution')\n# Plot Specifics\n# plt.ylim(0, .5)\n# plt.xlim(0, 2)\n# plt.legend()\n# plt.title('ODE Methods')","sub_path":"HW3_MultiwavelengthGalactucStructeII/ASTP720_HW3_P3.py","file_name":"ASTP720_HW3_P3.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"600131756","text":"import machine\n\nrtc = machine.RTC()\n\n\ndef set_awake_time_and_put_to_deepsleep(time_in_s):\n # configure RTC.ALARM0 to be able to wake the device\n rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)\n\n # set RTC.ALARM0 to fire after 10 seconds (waking the device)\n rtc.alarm(rtc.ALARM0, time_in_s * 1000)\n\n # put the device to sleep\n machine.deepsleep()\n","sub_path":"Source/python/deepsleep.py","file_name":"deepsleep.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"396134729","text":"#2018.12.6\r\n\r\nimport subprocess\r\nimport pexpect\r\nimport sys\r\n\r\n\r\ndef AccountList(number):\r\n\tten=[\"root\",\"1.1.1.1\",\"22\"]#用户 ip 端口\r\n\tBAN=[\"root\",\"2.2.2.2\",\"22\"]\r\n\tJANPan=[\"root\",\"3.3.3.3\",\"22\"]\r\n\tAccount=[]\r\n\tif number == '1':\r\n\t\tAccount=ten\r\n\telif number =='2':\r\n\t\tAccount=BAN\r\n\telif number =='3':\r\n\t\tAccount=JANPan\r\n\treturn Account\r\ndef connect(name_ip,port):\r\n\tport=\"-p \"+str(port)\r\n#child = winpexpect.winspawn(\"ssh root@ -p \")\r\n\tchild = subprocess.run([\"ssh\",name_ip,port,])\r\n\t#try:\r\n\t\t#if (child.expect([pexpect.TIMEOUT,'password'])):\r\n\t\t\t#child.sendline('')\r\n\t#except:\r\n\t\t#print(str(child))\r\n\r\ndef main():\r\n\tprint(\"1. 1.1.1.1(腾讯云)\")\r\n\tprint(\"2. 1.1.1.1(搬瓦工)\")\r\n\tprint(\"3. 1.1.1.1(Janpan)\")\r\n\tssh_num = input(\"please choose one:\\n\")\r\n\tAccount=[]\r\n\tAccount=AccountList(ssh_num)\r\n\tname_ip=Account[0]+\"@\"+Account[1]\r\n\tport=Account[2]\r\n\tconnect(name_ip,port)\r\n\r\nmain()\r\n","sub_path":"ssh_manage.py","file_name":"ssh_manage.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"201796371","text":"import numpy as np\n\n\nclass Square:\n\n def __init__(self):\n self.solved = 0\n self.squares = set()\n self.x = np.arange(1, 10, 1).reshape((3, 3))\n self.find()\n\n def shuf(self, arr):\n arr = np.ravel(arr)\n np.random.shuffle(arr)\n arr = arr.reshape((3, 3))\n return arr\n\n def check(self, arr):\n x1 = (sum(arr[0]) == 15)\n x2 = (sum(arr[1]) == 15)\n x3 = (sum(arr[2]) == 15)\n y1 = (sum(arr[:, 0]) == 15)\n y2 = (sum(arr[:, 1]) == 15)\n y3 = (sum(arr[:, 2]) == 15)\n d1 = (sum(arr.diagonal()) == 15)\n d2 = (sum(np.fliplr(arr).diagonal()) == 15)\n c = arr.tobytes() not in self.squares\n\n if all([c, d1, d2, x1, x2, x3, y1, y2, y3]):\n self.squares.add(self.x.tobytes())\n return True\n else:\n return False\n\n def find(self):\n while self.solved < 8:\n self.x = self.shuf(self.x)\n if self.check(self.x):\n self.solved += 1\n print(f'{self.solved}\\n{self.x}\\n')\n\n\nSquare()\n","sub_path":"misc/3x3.py","file_name":"3x3.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"258858828","text":"# import packages\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\nimport cv2\nimport math\nimport os\n\n# define helper functions\ndef grayscale(img):\n \"\"\"Applies the Grayscale transform\n This will return an image with only one color channel\n but NOTE: to see the returned image as grayscale\n you should call plt.imshow(gray, cmap='gray')\"\"\"\n return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # Or use BGR2GRAY if you read an image with cv2.imread()\n # return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\ndef canny(img, low_threshold, high_threshold):\n \"\"\"Applies the Canny transform\"\"\"\n return cv2.Canny(img, low_threshold, high_threshold)\n\ndef gaussian_blur(img, kernel_size):\n \"\"\"Applies a Gaussian Noise kernel\"\"\"\n return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0)\n\ndef region_of_interest(img, vertices):\n \"\"\"\n Applies an image mask.\n\n Only keeps the region of the image defined by the polygon\n formed from `vertices`. The rest of the image is set to black.\n \"\"\"\n # defining a blank mask to start with\n mask = np.zeros_like(img)\n\n # defining a 3 channel or 1 channel color to fill the mask with depending on the input image\n if len(img.shape) > 2:\n channel_count = img.shape[2] # i.e. 3 or 4 depending on your image\n ignore_mask_color = (255,) * channel_count\n else:\n ignore_mask_color = 255\n\n # filling pixels inside the polygon defined by \"vertices\" with the fill color\n cv2.fillPoly(mask, vertices, ignore_mask_color)\n\n # returning the image only where mask pixels are nonzero\n masked_image = cv2.bitwise_and(img, mask)\n return masked_image\n\ndef hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap):\n \"\"\"\n `img` should be the output of a Canny transform.\n\n Returns an image with hough lines drawn.\n \"\"\"\n lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), min_line_len, \\\n max_line_gap)\n # only keep the longest left line and longest right line\n long_lines = longest_lines(lines)\n line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8)\n # extend longest lines\n extend_lines(line_img, long_lines)\n return line_img\n\ndef weighted_img(img, initial_img, α=0.8, β=1., λ=0.):\n \"\"\"\n `img` is the output of the hough_lines(), An image with lines drawn on it.\n Should be a blank image (all black) with lines drawn on it.\n\n `initial_img` should be the image before any processing.\n\n The result image is computed as follows:\n\n initial_img * α + img * β + λ\n NOTE: initial_img and img must be the same shape!\n \"\"\"\n return cv2.addWeighted(initial_img, α, img, β, λ)\n\ndef longest_lines(lines):\n max_len_left=max_len_right = 0\n lx1=ly1=lx2=ly2=rx1=ry1=rx2=ry2= 0\n for line in lines:\n for x1, y1, x2, y2 in line:\n if x1 < 480:\n if (x2-x1)**2 + (y2-y1)**2 > max_len_left:\n max_len_left = (x2 - x1) ** 2 + (y2 - y1) ** 2\n lx1 = x1\n ly1 = y1\n lx2 = x2\n ly2 = y2\n else:\n if (y2-y1)**2 + (x2-x1)**2 > max_len_right:\n max_len_right = (x2 - x1) ** 2 + (y2 - y1) ** 2\n rx1 = x1\n ry1 = y1\n rx2 = x2\n ry2 = y2\n return np.array([[(lx1,ly1,lx2,ly2),(rx1,ry1,rx2,ry2)]], dtype=np.int32)\n\ndef extend_lines(img, lines, color=[255, 0, 0], thickness=5):\n for line in lines:\n for x1, y1, x2, y2 in line:\n if x1 - x2 == 0:\n x_top = x_bottom = x1\n else:\n k = (y2-y1)/(x2-x1)\n b = y1 - k * x1\n x_bottom = int((540-b)/k)\n x_top = int((340-b)/k)\n cv2.line(img, (x_bottom, 540), (x_top, 340), color, thickness)\n\n# set some parameters\nlow_threshold = 50\nhigh_threshold = 150\nvertices = np.array([[(440,340),(100, 540), (910,540), (540, 340)]], dtype=np.int32)\nkernel_size = 3\nrho = 1\ntheta = np.pi/180\nthreshold = 25\nmin_line_len = 17\nmax_line_gap = 3\n\n# load the images in the directory\nimgs = os.listdir('test_images/')\nnum = len(imgs)\nfor i in range(num):\n # ignore '.DS_Store' file\n if imgs[i] != '.DS_Store':\n # read each image\n img = mpimg.imread('test_images/'+imgs[i])\n\n # convert to grayscale\n img_gray = grayscale(img)\n\n # apply gaussian_blur\n gau_gray = gaussian_blur(img_gray, kernel_size)\n\n # apply canny transform\n cann_gray = canny(gau_gray, low_threshold, high_threshold)\n\n # apply mask on image\n mask = region_of_interest(cann_gray, vertices)\n\n # apply hough transform\n lines = hough_lines(mask, rho, theta, threshold, min_line_len, max_line_gap)\n\n # combine image\n combine = weighted_img(lines, img)\n\n # save combined image\n mpimg.imsave('test_images/detected_' +imgs[i], combine)","sub_path":"test_scripts/Project1_image.py","file_name":"Project1_image.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"512568513","text":"#!/usr/bin/python3\n\nimport subprocess\nimport sys\nimport tempfile\nimport requests\n\n__all__ = ['install', 'update']\n\n\ndef install(url: str = None, package: str = None):\n if package:\n try:\n subprocess.run(['dpkg', '-i', package], check=True)\n except subprocess.CalledProcessError as e:\n sys.exit(e)\n return\n\n resp = requests.get(url, headers={'Accept': 'application/octet-stream'})\n with tempfile.NamedTemporaryFile() as f:\n f.write(resp.content)\n f.flush()\n try:\n subprocess.run(['dpkg', '-i', f.name], check=True)\n except subprocess.CalledProcessError as e:\n sys.exit(e)\n\n\ndef update(pkg_info: dict = None, package: str = None) -> bool:\n if package:\n install(package=package)\n return True\n\n ret = subprocess.run(['dpkg-query', '-f', '${Version}', pkg_info['name']])\n current_version = ret.stdout.decode('utf-8').strip()\n if current_version == pkg_info['version']:\n return False\n\n install(url=pkg_info['url'])\n return True\n","sub_path":"lib/deb.py","file_name":"deb.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"15171189","text":"from typing import List\n\nimport torch\nfrom torch import Tensor\nfrom torch.utils.data import Dataset\n\nfrom dsngd.expXYFamily import ExpXYFamily\nfrom dsngd.xGenerator import XCategoricalGenerator, XNormalGenerator, XGenerator\n\n\nclass XYDataset(Dataset):\n \"\"\" Represents a Dataset for an XY exponential family \"\"\"\n\n def __init__(self, nelements: int, xy_family: ExpXYFamily, p_y: Tensor, x_datasets: List[XGenerator], seed: int):\n if seed is not None:\n torch.manual_seed(seed)\n\n self.nelements = nelements\n self.y_card = xy_family.y_card\n self.family = xy_family\n self.p_y = p_y\n self.x_datasets = x_datasets\n self.x_card = len(self.x_datasets)\n\n # Generate ys samples\n self.ys = torch.multinomial(self.p_y, self.nelements, replacement=True)\n\n # Generate xs\n self.xs = torch.empty((self.nelements, self.x_card), dtype=torch.double)\n self.generate_xs()\n\n # Generate tx\n self.txs = torch.stack([self.family.t_plus(x) for x in self.xs])\n\n def generate_xs(self):\n for i, y in enumerate(self.ys):\n self.xs[i, :] = torch.cat([d.get_x(y) for d in self.x_datasets])\n\n def __getitem__(self, index: int):\n if 0 <= index < self.nelements:\n return self.ys[index], self.xs[index], self.txs[index]\n else:\n raise IndexError(\"index out of range\")\n\n def __len__(self):\n return self.nelements\n\n def shuffle(self):\n index = torch.randperm(self.nelements)\n\n self.ys = self.ys[index]\n self.xs = self.xs[index]\n self.txs = self.txs[index]\n\n\nclass XYCategoricalDataset(XYDataset):\n \"\"\" Dataset for the particular case when X ~ Categorical \"\"\"\n\n def __init__(self, length: int, p_y: Tensor, p_xs: Tensor, family: ExpXYFamily, seed: int = None) -> None:\n x_data_sets = [XCategoricalGenerator(p_xs)]\n super().__init__(length, family, p_y, x_data_sets, seed)\n\n\nclass XYNormalDataset(XYDataset):\n \"\"\" Dataset for the particular case when X ~ Normal \"\"\"\n def __init__(self, length, p_y: Tensor, mean: Tensor, std: Tensor, family: ExpXYFamily, seed:int = None):\n x_data_sets = [XNormalGenerator(mean, std)]\n super().__init__(length, family, p_y, x_data_sets, seed)\n\n def get_sta(self):\n\n s_y = torch.zeros(self.y_card)\n mean = torch.zeros(self.y_card)\n variance = torch.zeros(self.y_card)\n\n for y in self.ys:\n s_y[y] += 1\n s_y = s_y / self.nelements\n\n for i in range(self.y_card):\n index = self.ys == i\n mean[i] = self.xs[index].mean()\n variance[i] = self.xs[index].var()\n\n return s_y, mean, variance\n","sub_path":"dsngd/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"178419401","text":"\"\"\"\nWrite paths of annotation folders in a text file\nCreated by: Qian Bai\n on 9 July 2020\n\"\"\"\nimport os\nimport glob\nimport numpy as np\n\nBASE_DIR = 'D:/Documents/Datasets/' # base directory of datasets\nROOT_DIR = os.path.dirname(os.path.abspath(__file__))\nDATA_PATH = os.path.join(BASE_DIR, 'AHN3_as_S3DIS_NRI')\n\nwith open(os.path.join(ROOT_DIR, 'meta/anno_paths.txt'), 'w+') as anno_paths:\n paths = []\n for path in glob.glob(DATA_PATH + '/*/*/Annotations'):\n path = path.replace('\\\\', '/')\n paths.append(path)\n paths = np.array(paths)\n np.savetxt(anno_paths, paths, fmt='%s')\nanno_paths.close()\n","sub_path":"prepare_data/write_anno_paths.py","file_name":"write_anno_paths.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"109154907","text":"\nfrom discord.ext import commands\nimport discord\nimport asyncio\nimport aiohttp\nimport json\nimport random\n\nclass nsfw():\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(brief='Sends some hentai')\n @commands.is_nsfw()\n async def konachan(self, ctx, tag=None):\n \"\"\"Sends some hentai. NOT SAFE FOR WORK! Requires NSFW channel.\"\"\"\n if tag == None:\n tag = 'sex'\n else:\n tag = tag + '%20sex'\n choices = []\n async with self.bot.csess.get(f'https://konachan.com/post.json?tags={tag}') as response:\n data = await response.json(content_type='application/json')\n for I in data:\n choices.append(I['file_url'])\n await ctx.send(embed=discord.Embed(color=0x9013fe).set_image(url=random.choice(choices)))\n\n\n @commands.command(brief='Enables/disables auto-hentai feature')\n @commands.is_nsfw()\n @commands.has_permissions(manage_guild=True)\n async def autohentai(self, ctx, time: int=None):\n \"\"\"Enables/disables the auto-hentai feature! Requires an NSFW channel and the MANAGE_GUILD permissions!\"\"\"\n async with self.bot.pool.acquire() as conn:\n hentime = await conn.fetchval('SELECT hentime FROM guilds WHERE guild = ($1)', ctx.guild.id)\n henchan = ctx.channel.id\n if time is None:\n henchan = 0\n time = 0\n output = 'Auto hentai is now disabled'\n elif time >= 20:\n if hentime is not 0:\n output = f'Auto hentai timer updated! Timer: {time} seconds'\n else:\n output = f'Auto hentai is now enabled! Timer: {time} seconds'\n else:\n time = 0\n henchan = 0\n output = f'Auto hentai timer cannot be set to less than 20 seconds!'\n await conn.execute('UPDATE guilds SET hentime = ($1), henchan = ($2) WHERE guild = ($3)', time, henchan, ctx.guild.id)\n await ctx.send(embed=discord.Embed(title=output, color=0x9013fe))\n\n\ndef setup(bot):\n bot.add_cog(nsfw(bot))\n","sub_path":"src/modules/nsfw.py","file_name":"nsfw.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"342738399","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport sklearn\nimport numpy as np\nimport pandas as pd\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n# In[24]:\n\n\nfeature_text='label, lepton pT, lepton eta, lepton phi, lost energy mag, lost energy phi, jet 1 pt, jet 1 eta, jet 1 phi, jet 1 b-tag, jet 2 pt, jet 2 eta, jet 2 phi, jet 2 b-tag, jet 3 pt, jet 3 eta, jet 3 phi, jet 3 b-tag, jet 4 pt, jet 4 eta, jet 4 phi, jet 4 b-tag, m_jj, m_jjj, m_lv, m_jlv, m_bb, m_wbb, m_wwbb'\nfeatures=[a.strip() for a in feature_text.split(',')]\n\ndataset = pd.read_csv('newhiggs.csv', names=features)\n\n\n# In[25]:\n\n\nfrom sklearn.model_selection import train_test_split\nf = features[1:]\n\nx_train, x_test, y_train, y_test = train_test_split(dataset[f], dataset['label'], stratify=dataset['label'])\n\n\n# In[43]:\n\n\nx_train.plot(kind='density', subplots=True, layout=(4,7), figsize = (30,10), sharex=False)\nplt.show()\n\n\n# In[20]:\n\n\na = ['label','jet 3 b-tag', 'jet 1 b-tag', 'm_lv', 'm_jj', 'm_jjj', 'lost energy phi', 'm_bb']\ncustom_map = {0: 'boson absent', 1: 'boson present'}\ndataset['label'] = dataset['label'].map(custom_map)\n\n#x_train[a]\n\n\n# In[21]:\n\n\ng = sns.pairplot(dataset[a], hue='label')\n\n\n# In[22]:\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV\n\n\n# In[26]:\n\n\nclf = RandomForestClassifier()\nparam_grid = dict(max_depth=[1, 2, 5, 10, 20, 30, 40],\n min_samples_split=[2, 5, 10],\n min_samples_leaf=[2, 3, 5])\nest = GridSearchCV(clf, param_grid=param_grid, n_jobs=8)\n\n\n# In[27]:\n\n\nest.fit(x_train, y_train)\n\n\n# In[28]:\n\n\nscores = pd.DataFrame(est.cv_results_)\nscores.head()\n\n\n# In[29]:\n\n\nsns.factorplot(x='param_max_depth', y='mean_test_score',\n col='param_min_samples_split',\n hue='param_min_samples_leaf',\n data=scores);\n\n\n# In[30]:\n\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import GridSearchCV\n\n\n# In[33]:\n\n\nclf = DecisionTreeClassifier()\nparam_grid = dict(max_depth=[1, 2, 5, 10, 20, 30, 40],\n min_samples_split=[2, 5, 10],\n min_samples_leaf=[2, 3, 5])\n\n\n# In[34]:\n\n\nest = GridSearchCV(clf, param_grid=param_grid, n_jobs=8)\n\n\n# In[35]:\n\n\nest.fit(x_train, y_train)\n\n\n# In[36]:\n\n\nscores = pd.DataFrame(est.cv_results_)\n\n\n# In[37]:\n\n\nsns.factorplot(x='param_max_depth', y='mean_test_score',\n col='param_min_samples_split',\n hue='param_min_samples_leaf',\n data=scores);\n\n\n# In[38]:\n\n\nfrom sklearn.naive_bayes import GaussianNB\n\n\n# In[39]:\n\n\nclf = GaussianNB()\n\n\n# In[40]:\n\n\nget_ipython().run_line_magic('pinfo', 'GaussianNB')\n\n","sub_path":"Features3.py","file_name":"Features3.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"27285997","text":"from __future__ import division\nimport math\n\ntry:\n import numpy as np\nexcept ImportError:\n print('Numpy is required, please make sure it is installed properly')\n\ntry:\n import scipy as sp\nexcept ImportError:\n print('Scipy is required, please make sure it is installed properly')\n\nfrom scipy import *\nimport de_hh\nfrom mock_data import *\nimport scipy.optimize as op\nimport emcee\nimport time\n\nclass task_GoF:\n\n def __init__(self, modelname, dataname, N, Func, init_pos, bnds, Mock=False, method='L-BFGS-B', fitmodel=None, fitmodelrd=None, fitmodelsig8=None):\n\n self.modelname = modelname\n self.dataname = dataname\n self.N = N\n self.Func = Func\n self.init_pos = init_pos\n self.bnds = bnds\n self.fitmodel = fitmodel\n self.fitmodelrd = fitmodelrd\n self.fitmodelsig8 = fitmodelsig8\n \n self.dim = len(init_pos)\n self.pos = np.empty([0, self.dim])\n \n\n if Mock == False:\n self.chi2 = []\n for i in range(self.N):\n self.aa = self.init_pos+0.01*np.random.random(1)*self.init_pos #!!!!!#\n self.result = op.minimize(self.Func, self.aa, method=method, bounds=self.bnds)\n self.pos=np.vstack((self.pos, self.result[\"x\"]))\n #self.chi2.append(self.result[\"fun\"])\n self.chi2.append(np.asscalar(self.Func(self.result[\"x\"])))\n #print(i, self.result[\"fun\"], self.result[\"x\"])\n print(i, self.Func(self.result[\"x\"]), self.result[\"x\"])\n self.chi2=np.array(self.chi2)\n self.ind = np.where(self.chi2==min(self.chi2))\n self.bestfit=self.pos[np.where(self.chi2==min(self.chi2))][0]\n print(np.hstack((min(self.chi2), self.bestfit)))\n np.savetxt('output/bestfit/best_'+modelname+'_'+dataname+'.dat', np.hstack((min(self.chi2), self.bestfit)), fmt='%.6f')\n\n elif Mock == True:\n self.chi2 = []\n for i in range(self.N):\n self.aa = self.init_pos\n data_generate(self.modelname, self.fitmodel, self.fitmodelrd, self.fitmodelsig8)\n self.result = op.minimize(self.Func, self.aa, method=method, bounds=self.bnds)\n self.chi2.append((self.result[\"fun\"]))\n print('Run:', i, self.result[\"fun\"], self.result[\"x\"])\n np.savetxt('output/chi2_test/chi2_test_'+modelname+'_'+dataname+'.dat', self.chi2)\n\n\nclass task_MCMC:\n def __init__(self, modelname, dataname, position, nwalkers, Nstep, Nburnin, logf):\n \n ndim = len(position[0])\n sampler = emcee.EnsembleSampler(nwalkers, ndim, logf)\n \n sampler.run_mcmc(position, Nstep)\n samples = sampler.chain[:, Nburnin:, :].reshape((-1, ndim))\n chi2p = sampler.lnprobability[:, Nburnin:].reshape(-1)\n\n np.savetxt(\"./output/MCMC/\"+modelname+\"_\"+dataname+\".dat\", samples, fmt='%.6e')\n np.savetxt(\"./output/MCMC/\"+modelname+\"_\"+dataname+\"_chi2.dat\", -chi2p, fmt='%.6e')\n\n\n\n\n\n\n\n\n","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"483118667","text":"# o(1)时间删除节点i\n# 数据结构方法,遍历后到下一节点为i时把指针指向i的下下一个节点,,因链表只有指向下一节点的指针o(n)\n# 改进方法,直接将i的下一节点j复制到i,改为删除j\n# 若要删除的节点为尾节点或者只有一个节点(也即为尾节点),另外考虑\n# 1. 不是尾节点\n# else:1.只有一个节点 2。否则\n# 确保要删除的节点在链表中,否则判断的这一过程仍然需要o(n)\nclass ListNode:\n def __init__(self,x):\n self.value = x\n self.next = None\n\n def connectListNode(self,listnode):\n self.next = listnode\n\n def printList(self):\n while self:\n print(self.value)\n self = self.next\n\ndef deleteNode(listHead:ListNode,nodeToBeDeleted:ListNode):\n if not (listHead and nodeToBeDeleted):\n return\n # 要删除的不是尾节点\n if nodeToBeDeleted.next:\n pnext = nodeToBeDeleted.next\n nodeToBeDeleted.value = pnext.value\n nodeToBeDeleted.next = pnext.next\n pnext.value = None\n pnext.next = None\n # 只有一个节点\n elif listHead == nodeToBeDeleted:\n listHead.value = None\n nodeToBeDeleted.value = None\n # 删除尾节点,遍历\n else:\n pnode = listHead\n while pnode.next != nodeToBeDeleted:\n pnode = pnode.next\n pnode.next = None\n nodeToBeDeleted.value = None\n nodeToBeDeleted.next = None\n\ndef Test(pListHead,pNode):\n if not pListHead:\n print(\"empty\")\n return\n print(\"original list:\")\n pListHead.printList()\n print(\"the node to be deleted:\")\n print(pNode.value)\n deleteNode(pListHead,pNode)\n print(\"the result:\")\n pListHead.printList()\n\n# 多个节点,删除中间节点\ndef Test1():\n print(\"111111begin\")\n node1 = ListNode(1)\n node2 = ListNode(2)\n node3 = ListNode(3)\n node4 = ListNode(4)\n node5 = ListNode(5)\n node1.connectListNode(node2)\n node2.connectListNode(node3)\n node3.connectListNode(node4)\n node4.connectListNode(node5)\n Test(node1,node3)\n\n# 多个节点,删除尾节点\ndef Test2():\n print(\"222222begin\")\n node1 = ListNode(1)\n node2 = ListNode(2)\n node3 = ListNode(3)\n node4 = ListNode(4)\n node5 = ListNode(5)\n node1.connectListNode(node2)\n node2.connectListNode(node3)\n node3.connectListNode(node4)\n node4.connectListNode(node5)\n Test(node1,node5)\n\n# 多个节点,删除头节点\ndef Test3():\n print(\"33333begin\")\n\n node1 = ListNode(1)\n node2 = ListNode(2)\n node3 = ListNode(3)\n node4 = ListNode(4)\n node5 = ListNode(5)\n node1.connectListNode(node2)\n node2.connectListNode(node3)\n node3.connectListNode(node4)\n node4.connectListNode(node5)\n Test(node1,node1)\n\n#一个节点,删除头节点\ndef Test4():\n print(\"44444begin\")\n\n node1 = ListNode(1)\n\n Test(node1,node1)\n\ndef Test5():\n print(\"55555begin\")\n\n Test(None,None)\n\nif __name__ == '__main__':\n Test1()\n Test2()\n Test3()\n Test4()\n Test5()\n\n\n\n\n\n","sub_path":"code-offer/no18deleteNode.py","file_name":"no18deleteNode.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"401280051","text":"#環境変数:export GOOGLE_APPLICATION_CREDENTIALS=\"/Users/Hiroki/Downloads/cloud vision sample-2a137975417a.json\"\nimport cv2\nimport io\nimport socket\nimport wikipedia\nimport time\nimport os\nimport concurrent.futures\nfrom google.cloud import vision\nfrom google.cloud.vision import types\nfrom natto import MeCab\nfrom google_image_processing import google_search\n\nHOST = \"127.0.0.1\"\nPORT = 50007\n\nport1 = 10001\nport2 = 10002\nshowImage = \"0\"\n\nhost = \"10.32.130.11\"\nimg = \"photo.jpg\"\n\nwikipedia.set_lang(\"ja\")\nsocket_client1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsocket_client1.connect((host, port1))\nsocket_client2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsocket_client2.connect((host, port2))\n\nbook_tracker = cv2.TrackerKCF_create()\ncap = cv2.VideoCapture(0) #デバイスの指定(0:PCwebカメラ,1:USB接続webカメラ)\nsize = (800, 600)\nclient = vision.ImageAnnotatorClient()\n\n\n#テキストを画像ファイルから検出し,text_annotationsを返す\ndef detect_text(path):\n\n with io.open(path, 'rb') as image_file:\n content = image_file.read()\n\n image = types.Image(content=content)\n response = client.text_detection(image=image)\n texts = response.text_annotations\n\n return texts\n\n\n#text_annotationsから名詞を抽出し,配列に格納して返す\ndef noun_extraction(text_annotations):\n words = []\n with MeCab('-F%m,%f[0],%h') as nm:\n try:\n for n in nm.parse(texts[0].description, as_nodes=True):\n node = n.feature.split(',');\n if len(node) != 3:\n continue\n if node[1] == '名詞' and len(node[0]) > 1:\n words.append(node[0])\n except IndexError:\n print(\"IndexError from noun_extraction\")\n return words\n\n\n#文字領域を追跡\ndef calibration():\n cv2.destroyAllWindows()\n while True:\n time.sleep(2)\n ret, frame = cap.read()\n if not ret:\n continue\n frame = cv2.resize(frame, size)\n\n bbox2 = (0,0,10,10)\n bbox2 = cv2.selectROI(frame, False)\n ok2 = book_tracker.init(frame, bbox2)\n\n cv2.destroyAllWindows()\n break\n\n\ncalibration()\nwhile True:\n\n ret, frame = cap.read()\n frame = cv2.resize(frame, size)\n if not ret:\n k = cv2.waitKey(1)\n if k == 27 :\n break\n continue\n timer = cv2.getTickCount()\n\n # トラッカーをアップデートする\n book_track, bbox2 = book_tracker.update(frame)\n\n if book_track:\n # Tracking success\n p3 = (int(bbox2[0]), int(bbox2[1]))\n p4 = (int(bbox2[0] + bbox2[2]), int(bbox2[1] + bbox2[3]))\n cv2.rectangle(frame, p3, p4, (0,255,0), 2, 1)\n tx = (p3[0] - 130) * 1.8\n ty = (p3[1] - 130) * 1.8\n\n coordinate = str(tx) + '\\n' + str(ty)\n\n else :\n # トラッキングが外れたら警告を表示する\n cv2.putText(frame, \"book detection faild\", (10,50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1, cv2.LINE_AA);\n\n cv2.imshow(\"Tracking\", frame)\n\n k = cv2.waitKey(1)\n if k == ord('s'):\n cv2.imwrite(img, frame) #画像を保存\n texts = detect_text(img)\n words = noun_extraction(texts)\n i = 0\n nouns = \"\"\n for word in words:\n i += 1\n nouns += \"[\" + word + \"] \" + '\\n'\n if(words == None):\n socket_client1.send(\"None\".encode('utf-8'))\n else:\n socket_client1.send(nouns.encode('utf-8'))\n while True:\n mode = int(input(\"wikipedia:1\" + '\\n' + \"google image:2\" + '\\n'))\n # index = int(input(\"index:\")) - 1\n if(mode == 1): #wikipediaモード\n\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, PORT))\n s.listen(1)\n conn, addr = s.accept()\n with conn:\n print('Connected by', addr)\n while True:\n data = conn.recv(1024)\n if not data: break\n data = data.decode(\"utf-8\")\n index = int(data)\n print(index)\n break\n\n try:\n result = wikipedia.summary(words[index], sentences=1)\n message = words[index] + \"\\n\" + result\n socket_client2.send(message.encode('utf-8'))\n\n break\n except wikipedia.exceptions.DisambiguationError as error:\n title = \"曖昧さ回避:\" + error.args[1][0]\n result = wikipedia.summary(error.args[1][0], sentences=1)\n message = title + \"\\n\" + result\n socket_client2.send(message.encode('utf-8'))\n break\n except wikipedia.exceptions.PageError:\n message = \"ページが存在しません.\"\n socket_client2.send(message.encode('utf-8'))\n break\n elif(mode == 2): #画像検索モード\n try:\n google_search(words[index])\n socket_client1.send(\" \".encode('utf-8'))\n showImage = \"1\"\n\n break\n except IndexError:\n message= \"画像が存在しません.\"\n socket_client1.send(message.encode('utf-8'))\n break\n\n if k == ord('c'):\n calibration()\n\n if k == ord('r'):\n showImage = \"0\"\n socket_client3.send(showImage.encode('utf-8'))\n\n if k == 27:\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"prototype2.py","file_name":"prototype2.py","file_ext":"py","file_size_in_byte":5929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"651385648","text":"#!/usr/bin/env python\n\n\n## This script writes out a single conformer of some mol from\n## an SDF file having multiple molecules, and multiple conformers\n## of each molecule. This can be used, for example, to isolate\n## specific conformers that lead to a high RMSD energy value \n## for a particular molecule.\n\n## Usage: python writeOneConf.py -f inputfile.sdf -t molName -s sdtag -v tagvalue -x filesuffix\n\nimport os, sys\nimport openeye.oechem as oechem\nimport argparse\n\n\n### ------------------- Script -------------------\n\ndef main(**kwargs):\n outfn = os.path.splitext(opt['infn'])[0]+'_'+opt['suffix']+'.mol2'\n success = False\n \n ### Read in .sdf file and distinguish each molecule's conformers\n ifs = oechem.oemolistream()\n ifs.SetConfTest( oechem.OEAbsoluteConfTest() )\n if not ifs.open(opt['infn']):\n oechem.OEThrow.Warning(\"Unable to open %s for reading\" % opt['infn'])\n return\n \n for mol in ifs.GetOEMols():\n if mol.GetTitle() == opt['title']:\n for i, conf in enumerate( mol.GetConfs()):\n if oechem.OEGetSDData(conf, opt['sdtag']) == opt['value']:\n #print oechem.OEGetSDData(conf, opt['sdtag'])\n #print opt['value']\n ofs = oechem.oemolostream()\n #if os.path.exists(outfn):\n # print \"Output .sdf file already exists. Exiting.\\n\"\n # return\n if not ofs.open(outfn):\n oechem.OEThrow.Fatal(\"Unable to open %s for writing\" % outfn)\n oechem.OEWriteConstMolecule(ofs, conf)\n ofs.close()\n success = True\n if not success:\n print(\"\\n** Found no confs matching your criteria. **\")\n ifs.close()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"-f\", \"--infn\",\n help=\"Name of input SDF file from which to write out the conformer.\")\n parser.add_argument(\"-t\", \"--title\",\n help=\"Molecule name in the file.\")\n parser.add_argument(\"-s\", \"--sdtag\",\n help=\"SD tag to search for conformer.\")\n parser.add_argument(\"-v\", \"--value\",\n help=\"Value of the SD tag to write out that conformer.\")\n parser.add_argument(\"-x\", \"--suffix\",\n help=\"Suffix appened to input fn when writing out this conf.\")\n\n args = parser.parse_args()\n opt = vars(args)\n\n ### Check that input file exists.\n if not os.path.exists(opt['infn']):\n raise parser.error(\"Input file %s does not exist. Try again.\" % opt['infn'])\n\n main(**opt)\n\n","sub_path":"writeOneConf.py","file_name":"writeOneConf.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"272869857","text":"import boto3\nimport zipfile, os\nimport glob\n\ndirectory_in_str = \"/numbers\"\n\nclient = boto3.client('cloudformation')\ns3 = boto3.resource('s3')\n\n\ndef create_stack(stack_name, template_url, source):\n response = client.create_stack(\n StackName=stack_name,\n TemplateURL=template_url,\n Capabilities=[\n 'CAPABILITY_NAMED_IAM'],\n Parameters = [\n {\n 'ParameterKey': \"SourceBucket\",\n 'ParameterValue': source\n }]\n )\n\n\ndef update_stack(stack_name, template_url, source):\n try:\n response = client.update_stack(\n StackName=stack_name,\n TemplateURL=template_url,\n Capabilities=['CAPABILITY_NAMED_IAM'],\n Parameters=[\n {\n 'ParameterKey': \"SourceBucket\",\n 'ParameterValue': source\n }\n ]\n )\n except Exception:\n print(\"No update To Perform\")\n\n\ndef stack_status(stack_name):\n try:\n stack = client.describe_stacks(StackName=stack_name)\n status = stack['Stacks'][0]['StackStatus']\n return status\n except Exception:\n return \"NO_STACK\"\n\n\ndef delete_object(bucket_name):\n try:\n bucket = s3.Bucket(bucket_name)\n bucket.objects.all().delete()\n except Exception:\n print(\"Bucket Not Present\")\n\ndef upload_object(bucket_name, filename, location):\n s3.Object(bucket_name, location).upload_file(Filename=filename)\n\n\ndef upload_objects(bucket_name, foldername):\n a=os.listdir(foldername)\n for file in a:\n #print(file)\n #print(foldername+'/'+file)\n s3.Object(bucket_name,file).upload_file(Filename=foldername+'/'+file)\n\n\n\n\ndef upload_zip_object(bucket_name, input_filename, output_filename, location):\n zip = zipfile.ZipFile(output_filename, \"w\")\n zip.write(input_filename, os.path.basename(input_filename))\n zip.close()\n upload_object(bucket_name, output_filename, location)\n os.remove(output_filename)","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"99756002","text":"import re\n\n\ndef find_div(code):\n # .匹配除\\n\\r外的任意字符\n # 要匹配\\n使用[\\s\\S]\n pattern = r'(

[\\s\\S]*?
)'\n pattern = re.compile(pattern)\n return re.sub(pattern, lambda p: div_formatter(p.group(1)), code)\n\n\ndef div_formatter(div_code):\n div_code = div_code.strip()\n pattern = r'()'\n return re.sub(pattern, '', div_code).replace('\\n', '')\n\n\nif __name__ == '__main__':\n code = \"\"\"...\"\"\"\n print(find_div(code))\n","sub_path":"Details-In-Python/blog utils/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"425371217","text":"from django.urls import path,include,re_path\nfrom . import views\n\napp_name = \"business\"\n\n\nurlpatterns = [\n path('limited_offer_coupons/',views.coupon_upload,name='coupon_upload'),\n path('collaberate/',views.collaberate_home,name='collaberate'),\n path('perminent_coupons/',views.perminent_coupons,name='add_coupon'),\n # path('video_upload/',views.video_check),\n path('video_view/',views.video_view),\n # path('fun/',views.Fun_View.as_view(),name='fun'),\n path('fun/',views.fun,name='fun'),\n path('stats/',views.stats,name='stats'),\n path('tnc/',views.tnc,name='tnc'),\n\n\n]\n","sub_path":"business/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"457462821","text":"import os\nfrom os import path\n\nimport PIL\nimport cv2\nimport mahotas\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torchvision as tv\nfrom matplotlib import pyplot as plt\nfrom scipy import io as sio\nfrom sklearn.preprocessing import LabelEncoder\n\nstat = \"[STATUS]\"\nwarn = \"[WARNING]\"\n\n\nclass WaifuDataLoader(object):\n \"\"\"\n This class represents a simple interface of image data loaders with different data pre-processing,\n e.g. feature extractions with different algorithms or using different packages\n \"\"\"\n\n def __init__(self, data_path, pic_size):\n self.data_path = data_path\n self.pic_size = pic_size\n\n def load_image(self):\n raise NotImplementedError(\"No implementation for WaifuDataLoader.load_image()\")\n\n\nclass FeatureExtractionDataLoader(WaifuDataLoader):\n \"\"\"\n This class load and apply a feature extraction process on images as data pre-processing.\n \"\"\"\n\n def __init__(self, data_path=path.join('data_set', 'modeling_data'), pic_size=(224, 224), bins=8):\n \"\"\"\n\n Parameters\n ----------\n data_path: str\n pic_size: tuple\n shape of resized images, defaulted to (224, 224)\n bins: int\n number of bins in color histogram\n \"\"\"\n super().__init__(data_path=data_path, pic_size=pic_size)\n self.bins = bins\n\n def hu_moments(self, image):\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n return cv2.HuMoments(cv2.moments(gray)).flatten()\n\n def haralick_textures(self, image):\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n return mahotas.features.haralick(gray).mean(axis=0)\n\n def color_histo(self, image):\n hist = cv2.calcHist([image], [0, 1, 2], None, [self.bins, self.bins, self.bins], [0, 256, 0, 256, 0, 256])\n cv2.normalize(hist, hist)\n return hist.flatten()\n\n def extract_single_image(self, pic_dir, hu_moments=True, haralick=True, histogram=True):\n \"\"\"\n Extract features from a single image given its path.\n\n Parameters\n ----------\n pic_dir: str\n path of the image file\n hu_moments: bool\n whether to apply Hu moments on image\n haralick: bool\n whether to apply Haralick feature extraction on image\n histogram: bool\n whether to apply a color histogram on image\n\n Returns\n -------\n numpy.array\n feature data extracted from image\n \"\"\"\n if not (hu_moments or haralick or histogram):\n raise ValueError(\"{} Must choose at lease one image model!\".format(warn))\n else:\n image = cv2.imread(pic_dir)\n image = cv2.resize(image, self.pic_size)\n image_features = np.array([])\n if hu_moments:\n image_features = np.hstack((image_features, self.hu_moments(image)))\n if haralick:\n image_features = np.hstack((image_features, self.haralick_textures(image)))\n if histogram:\n image_features = np.hstack((image_features, self.color_histo(image)))\n return image_features\n\n def single_rgb(self, pic_dir):\n \"\"\"\n Read an image given path, resize it, return in RGB data.\n\n Parameters\n ----------\n pic_dir: str\n path of the image file\n\n Returns\n -------\n numpy.array\n RGB data of resized image\n \"\"\"\n image = cv2.imread(pic_dir)\n image = cv2.resize(image, self.pic_size)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n return np.array(image).flatten()\n\n def load_image(self, hu_moments=True, haralick=True, histogram=True, get_rgb=True):\n \"\"\"\n Load images stored in self.data_path, and apply some initial pre-processing and feature extraction.\n Features extracted from each images will be stored as an element in the list returned.\n\n Parameters\n ----------\n hu_moments: bool\n whether to apply Hu moments on images\n haralick: bool\n whether to apply Haralick feature extraction on images\n histogram: bool\n whether to apply a color histogram on image\n get_rgb: bool\n whether to return the original RGB data as well\n\n Returns\n -------\n images_features: list\n feature data extracted from each image\n images_rgb: list\n original RGB data of each image\n label: list\n label of each image, the actual result of classification\n \"\"\"\n character_labels = os.listdir(self.data_path)\n print(\"{} Characters including {}\".format(stat, character_labels))\n\n images_features = []\n images_rgb = []\n labels = []\n\n # loading images from folders\n for index, training_class in zip(range(len(character_labels)), character_labels):\n image_folder = path.join(self.data_path, training_class)\n pics_name = os.listdir(image_folder)\n print(\"{} {}/{} processing folder: {}\".format(stat, index + 1, len(character_labels), training_class))\n for pic in pics_name:\n pic_dir = path.join(image_folder, pic)\n feature = self.extract_single_image(pic_dir,\n hu_moments=hu_moments,\n haralick=haralick,\n histogram=histogram)\n labels.append(training_class)\n images_features.append(feature)\n if get_rgb:\n rgb = self.single_rgb(pic_dir)\n images_rgb.append(rgb)\n\n print(\"{} completed Feature Extraction.\".format(stat))\n print(\"{} feature vector shape: {}\".format(stat, np.array(images_features).shape))\n print(\"{} rgb vector shape: {}\".format(stat, np.array(images_rgb).shape))\n print(\"{} label vector shape: {}\".format(stat, np.array(labels).shape))\n return images_features, images_rgb, labels\n\n def write_data(self, file_name='img_feature.mat', hu_moments=True, haralick=True, histogram=True, rgb=False):\n \"\"\"\n Store the result of FeatureExtractionDataLoader.load_image() as a MATLAB file.\n\n Parameters\n ----------\n file_name: str\n file name that data will be stored into\n hu_moments: bool\n whether to apply Hu moments on images\n haralick: bool\n whether to apply Haralick feature extraction on images\n histogram: bool\n whether to apply a color histogram on image\n rgb: bool\n whether to return the original RGB data as well\n \"\"\"\n img_features, img_rgb, img_labels = self.load_image(hu_moments=hu_moments,\n haralick=haralick,\n histogram=histogram,\n get_rgb=rgb)\n names = np.unique(img_labels)\n encoder = LabelEncoder()\n target = encoder.fit_transform(img_labels)\n print(\"{} training labels encoded.\".format(stat))\n data = {\n 'image_feature': img_features,\n 'image_rgb': img_rgb,\n 'labels': target,\n 'names': names\n }\n sio.savemat(path.join('data_set', file_name), data)\n print(\"{} save to data_set/{}\".format(stat, file_name))\n\n\ndef img_stat(data_dir, num_channels=3):\n \"\"\"\n Calculate the mean and standard deviation of all images given path of their directory.\n\n Parameters\n ----------\n data_dir: str\n path of labeled images\n num_channels: int\n number of channels to be calculated, in case of images stored in format other than RGB\n\n Returns\n -------\n img_mean: numpy.array\n mean of all images on each channel\n img_std: numpy.array\n standard deviation of all images on each channel\n \"\"\"\n cls_dirs = [d for d in os.listdir(data_dir) if path.isdir(path.join(data_dir, d))]\n channel_sum = np.zeros(num_channels)\n channel_sqr_sum = np.zeros(num_channels)\n pixel_num = 0\n\n for i, d in enumerate(cls_dirs):\n img_paths = [path.join(data_dir, d, img_file)\n for img_file in os.listdir(path.join(data_dir, d))]\n print(\"{} Extract img color mean and std {}\".format(stat, d))\n for img_path in img_paths:\n orig_img = cv2.imread(img_path)\n rgb_img = cv2.cvtColor(orig_img, cv2.COLOR_BGR2RGB)\n img = rgb_img / 255.\n pixel_num += (img.size / num_channels)\n channel_sum += np.sum(img, axis=(0, 1))\n channel_sqr_sum += np.sum(np.square(img), axis=(0, 1))\n\n img_mean = channel_sum / pixel_num\n img_std = np.sqrt(channel_sqr_sum / pixel_num - np.square(img_mean))\n\n return img_mean, img_std\n\n\nclass PyTorchDataLoader(WaifuDataLoader):\n \"\"\"\n This class load images by building a torchvision.DataLoader\n and apply a normalization after resizing on images as data pre-processing.\n \"\"\"\n\n def __init__(self, data_path=path.join('data_set', 'modeling_data'), pic_size=(224, 224),\n channel_mean=None, channel_std=None):\n \"\"\"\n\n Parameters\n ----------\n data_path: str\n pic_size: tuple\n shape of resized images, defaulted to (224, 224)\n channel_mean: list or None\n mean of images on each channel, defaulted to [0.485, 0.456, 0.406]\n channel_std: list\n standard deviation of images on each channel, defaulted to [0.229, 0.224, 0.225]\n \"\"\"\n super().__init__(data_path=data_path, pic_size=pic_size)\n if channel_mean is None:\n # use mean from ImageNet\n channel_mean = [0.485, 0.456, 0.406]\n if channel_std is None:\n # use std from ImageNet\n channel_std = [0.229, 0.224, 0.225]\n self.norm_para = {\n 'train': [channel_mean, channel_std],\n 'test': [channel_mean, channel_std]\n }\n\n def load_image(self, data_transforms=None, batch_size=16, num_worker=4, train_proportion=0.8):\n \"\"\"\n Build up a torch.utils.data.DataLoader with transformations.\n\n The default transformation is firstly a crop into a random size and then resize to self.pic_size,\n then a random horizontal flip of image,\n and at last a normalization using mean and standard deviation stored in self.norm_para.\n\n Then the data will be randomly split into a training and a testing set, and\n return a torch.utils.data.DataLoader on each set.\n\n Parameters\n ----------\n data_transforms: object or None\n custom data transformations if the default transformation is not preferred.\n Transformations should be similar or directly using objects from torchvision.transforms.\n batch_size: int\n number of samples per batch to load, directly passed to torch.utils.data.DataLoader\n num_worker: int\n number of sub-processes to use for data loading, directly passed to torch.utils.data.DataLoader\n train_proportion: float\n the proportion between training and testing set\n\n Returns\n -------\n data_loader: dict\n train -> torch.utils.data.DataLoader of training set\n test -> torch.utils.data.DataLoader of testing set\n dataset_sizes: dict\n train -> size of training set\n test -> size of testing set\n character_names: list\n names of image classes\n data_transforms: torchvision.transforms\n the transformation used in returned torch.utils.data.DataLoader\n \"\"\"\n if not data_transforms:\n data_transforms = tv.transforms.Compose([\n tv.transforms.RandomResizedCrop(self.pic_size),\n tv.transforms.RandomHorizontalFlip(),\n tv.transforms.ToTensor(),\n tv.transforms.Normalize(self.norm_para['train'][0], self.norm_para['train'][1])\n ])\n\n anime_data = tv.datasets.ImageFolder(self.data_path, data_transforms)\n if train_proportion < 0.4 or train_proportion >= 1:\n print(\"Training set size not good! Set to default: 0.8\")\n train_proportion = 0.8\n train_size = int(train_proportion * len(anime_data))\n test_size = len(anime_data) - train_size\n train_dataset, test_dataset = torch.utils.data.random_split(anime_data, [train_size, test_size])\n split_dataset = {'train': train_dataset, 'test': test_dataset}\n data_loaders = {\n x: torch.utils.data.DataLoader(split_dataset[x],\n batch_size=batch_size,\n shuffle=True,\n num_workers=num_worker)\n for x in ['train', 'test']\n }\n dataset_sizes = {x: len(split_dataset[x]) for x in ['train', 'test']}\n character_names = anime_data.classes\n print(\"Character names: {}\".format(character_names))\n\n return data_loaders, dataset_sizes, character_names, data_transforms\n\n def loader_display(self, inp, title=None):\n \"\"\"Imshow for Tensor.\"\"\"\n inp = inp.numpy().transpose((1, 2, 0))\n mean = np.array(self.norm_para['train'][0])\n std = np.array(self.norm_para['train'][1])\n inp = std * inp + mean\n inp = np.clip(inp, 0, 1)\n plt.imshow(inp)\n if title is not None:\n plt.title(title)\n plt.pause(0.001)\n\n\nclass ResNetTraditionalModel(WaifuDataLoader):\n \"\"\"\n This class load and apply a feature extraction process using neural networks on images as data pre-processing.\n \"\"\"\n\n def __init__(self, data_path=path.join('data_set', 'modeling_data'), pic_size=(224, 224),\n data_transforms=None, model=tv.models.resnet18(pretrained=True),\n channel_mean=None, channel_std=None):\n \"\"\"\n\n Parameters\n ----------\n data_path: str\n pic_size: tuple\n shape of resized images, defaulted to (224, 224)\n data_transforms: object or None\n custom data transformations if the default transformation is not preferred.\n Transformations should be similar or directly using objects from torchvision.transforms.\n model: torch.nn.Module or None\n neural network works as feature extractor, defaulted to ResNet18 implemented in torchvision.models.resnet\n channel_mean: list or none\n mean of images on each channel, defaulted to the mean of images in data_path\n channel_std: list or none\n standard deviation of images on each channel, defaulted to the standard deviation of images in data_path\n \"\"\"\n super().__init__(data_path, pic_size)\n mean_dataset, std_dataset = img_stat(data_path)\n if channel_mean is None:\n self.mean = mean_dataset\n else:\n self.mean = channel_mean\n\n if channel_std is None:\n self.std = std_dataset\n else:\n self.std = channel_std\n\n if data_transforms is None:\n self.img_transform = tv.transforms.Compose([\n tv.transforms.Resize((224, 224)),\n tv.transforms.ToTensor(),\n tv.transforms.Normalize(self.mean, self.std)\n ])\n else:\n self.img_transform = data_transforms\n self.model = model\n self.device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n self.model.eval()\n self.model.to(self.device)\n print(\"[STATUS] Using device: {}\".format(self.device))\n\n def single_image_to_vec(self, raw_img):\n \"\"\"\n Apply data transforms stored in self.img_transform, and apply the neural network stored in self.model.\n\n Parameters\n ----------\n raw_img: PIL.Image.Image\n\n Returns\n -------\n numpy.array\n \"\"\"\n img = self.img_transform(raw_img)\n img = img.unsqueeze(0)\n if torch.cuda.is_available():\n img = img.cuda()\n outputs = self.model(img).detach().cpu().clone().numpy()[0]\n return outputs\n\n def load_image(self):\n \"\"\"\n Load images stored in self.data_path, and\n apply a neural network model as initial pre-processing and feature extraction.\n Features extracted from each images will be stored as an element in the list returned.\n\n Returns\n -------\n img_data: list\n feature data extracted from each image\n label: list\n label of each image, the actual result of classification\n \"\"\"\n characters_folders = os.listdir(self.data_path)\n\n img_data = []\n labels = []\n\n since = pd.to_datetime('now')\n for i, character in enumerate(characters_folders):\n print('[STATUS] {}/{} Processing {}'.format(i + 1, len(characters_folders), character))\n pic_folder = path.join(self.data_path, character)\n all_pics = os.listdir(pic_folder)\n for pic in all_pics:\n pic_dir = path.join(pic_folder, pic)\n raw_img = PIL.Image.open(pic_dir).convert('RGB')\n output = self.single_image_to_vec(raw_img)\n img_data.append(output)\n labels.append(character)\n time_elapsed = pd.to_datetime('now') - since\n\n print('{} Feature extraction complete in {:.0f}m {:.0f}s'\n .format(stat, time_elapsed.total_seconds() // 60, time_elapsed.total_seconds() % 60))\n print(\"{} feature vector shape: {}\".format(stat, np.array(img_data).shape))\n print(\"{} label vector shape: {}\".format(stat, np.array(labels).shape))\n\n return img_data, labels\n\n def write_data(self, file_name='resnet_img_feature.mat'):\n \"\"\"\n Store the result of ResNetTraditionalModel.load_image() as a MATLAB file.\n\n Parameters\n ----------\n file_name: str\n file name that data will be stored into\n \"\"\"\n img_features, img_labels = self.load_image()\n names = np.unique(img_labels)\n encoder = LabelEncoder()\n target = encoder.fit_transform(img_labels)\n print(\"{} training labels encoded.\".format(stat))\n data = {\n 'resnet_feature': img_features,\n 'labels': target,\n 'names': names\n }\n filename = path.join('data_set', file_name)\n sio.savemat(filename, data)\n print(\"{} save to {}\".format(stat, path.join(filename)))\n\n\nif __name__ == '__main__':\n rn_tr = ResNetTraditionalModel()\n rn_tr.write_data()\n","sub_path":"waifu_project/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":18906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"100356476","text":"# -*- coding: utf-8 -*-\n\"\"\"\n line.client\n ~~~~~~~~~~~\n\n LineClient for sending and receiving message from LINE server.\n\n :copyright: (c) 2014 by Taehoon Kim.\n :license: BSD, see LICENSE for more details.\n\"\"\"\nimport rsa, requests\ntry:\n import simplejson as json\nexcept ImportError:\n import json\n\nfrom thrift.transport import THttpClient\nfrom thrift.protocol import TCompactProtocol\nfrom .lib import *\nfrom .lib.ttypes import *\n\nclass LineAPI(object):\n \"\"\"This class is a wrapper of LINE API\n\n \"\"\"\n LINE_DOMAIN = 'https://gd2.line.naver.jp'\n\n LINE_POLL_QUERY_PATH_FIR = LINE_DOMAIN + \"/P4\"\n LINE_CERTIFICATE_PATH = LINE_DOMAIN + \"/Q\"\n LINE_LOGIN_QUERY_PATH = LINE_DOMAIN + \"/api/v4p/rs\"\n LINE_AUTH_QUERY_PATH = LINE_DOMAIN + \"/api/v4/TalkService.do\"\n \n CERT_FILE = \".line.crt\"\n\n ip = \"127.0.0.1\"\n version = \"8.14.5\"\n user_agent = \"Line/%s\" % (version)\n com_name = \"Line_Carpedm\"\n carrier = '51089, 1-0'\n revision = 0\n system_ver = '13.2.1'\n app_name = \"IOSIPAD\\t%s\\tiPhone_OS\\t%s\" % (version, system_ver)\n certificate = \"\"\n\n _headers = {}\n\n def __init__(self):\n object.__init__(self)\n self._session = requests.session()\n\n def ready(self):\n \"\"\"\n After login, make `client` and `client_in` instance\n to communicate with LINE server\n \"\"\"\n raise Exception(\"Code is removed because of the request of LINE corporation\")\n\n def updateAuthToken(self):\n \"\"\"\n After login, update authToken to avoid expiration of\n authToken. This method skip the PinCode validation step.\n \"\"\"\n if self.certificate:\n self.login(systemName=self.com_name)\n self.tokenLogin()\n return True\n else:\n self.raise_error(\"You need to login first. There is no valid certificate\")\n\n def tokenLogin(self):\n self.transport = THttpClient.THttpClient(self.LINE_AUTH_QUERY_PATH)\n self.transport.setCustomHeaders(self._headers)\n self.protocol = TCompactProtocol.TCompactProtocol(self.transport)\n self._client = TalkService.Client(self.protocol)\n return self._client\n\n def loginRequest(self, type, data):\n lReq = LoginRequest()\n if type == '0':\n lReq.type = LoginType.ID_CREDENTIAL\n lReq.identityProvider = data['identityProvider']\n lReq.identifier = data['identifier']\n lReq.password = data['password']\n lReq.keepLoggedIn = data['keepLoggedIn']\n lReq.accessLocation = data['accessLocation']\n lReq.systemName = data['systemName']\n lReq.certificate = data['certificate']\n lReq.e2eeVersion = data['e2eeVersion']\n elif type == '1':\n lReq.type = LoginType.QRCODE\n lReq.keepLoggedIn = data['keepLoggedIn']\n if 'identityProvider' in data:\n lReq.identityProvider = data['identityProvider']\n if 'accessLocation' in data:\n lReq.accessLocation = data['accessLocation']\n if 'systemName' in data:\n lReq.systemName = data['systemName']\n lReq.verifier = data['verifier']\n lReq.e2eeVersion = data['e2eeVersion']\n else:\n lReq=False\n return lReq\n\n def login(self, keepLoggedIn=True, systemName=com_name):\n \"\"\"Login to LINE server.\"\"\"\n #TalkService\n self.transport = THttpClient.THttpClient(self.LINE_AUTH_QUERY_PATH)\n self.transport.setCustomHeaders(self._headers)\n self.protocol = TCompactProtocol.TCompactProtocol(self.transport)\n self._client = TalkService.Client(self.protocol)\n #AuthService\n self.transport = THttpClient.THttpClient(self.LINE_LOGIN_QUERY_PATH)\n self.transport.setCustomHeaders(self._headers)\n self.protocol = TCompactProtocol.TCompactProtocol(self.transport)\n self._auth = AuthService.Client(self.protocol)\n\n self.provider = IdentityProvider.LINE\n rsaKey = self._client.getRSAKeyInfo(self.provider)\n message = (chr(len(rsaKey.sessionKey)) + rsaKey.sessionKey +\n chr(len(_id)) + _id +\n chr(len(passwd)) + passwd).encode('utf-8')\n pub_key = rsa.PublicKey(int(rsaKey.nvalue, 16), int(rsaKey.evalue, 16))\n crypto = rsa.encrypt(message, pub_key).hex()\n \n try:\n with open(self.CERT_FILE,'r') as f:\n self.certificate = f.read()\n f.close()\n except:\n self.certificate = \"\"\n\n lReq = self.loginRequest('0', {\n 'identityProvider': self.provider,\n 'identifier': rsaKey.keynm,\n 'password': crypto,\n 'keepLoggedIn': keepLoggedIn,\n 'accessLocation': '127.0.0.1',\n 'systemName': systemName,\n 'certificate': self.certificate,\n 'e2eeVersion': 0\n })\n\n result = self._auth.loginZ(lReq)\n\n if result.type == LoginResultType.REQUIRE_DEVICE_CONFIRM:\n if withReturn == False:\n print('Enter Pincode: \"{}\"'.format(result.pinCode))\n self._headers['X-Line-Access'] = result.verifier\n getAccessKey = self.get_json(self.LINE_DOMAIN + '/Q')\n self.verifier = result.verifier\n self.pinCode = result.pinCode\n try:\n lReq = self.loginRequest('1', {\n 'keepLoggedIn': keepLoggedIn,\n 'verifier': getAccessKey['result']['verifier'],\n 'e2eeVersion': 0\n })\n result = self._auth.loginZ(lReq)\n except Exception as e:\n self.raise_error(e)\n\n if result.type == LoginResultType.SUCCESS:\n if result.certificate is not None:\n with open(self.CERT_FILE,'w') as f:\n f.write(result.certificate)\n self.certificate = result.certificate\n if result.authToken is not None:\n self.authToken = self._headers['X-Line-Access'] = result.authToken\n else:\n return False\n else:\n return self.raise_error('Login failed')\n else:\n return (result, 'Enter Pincode: \"{}\"'.format(result.pinCode))\n elif result.type == LoginResultType.REQUIRE_QRCODE:\n self.qrLogin(systemName=self.com_name, APP_NAME=self.app_name)\n pass\n elif result.type == LoginResultType.SUCCESS:\n if result.authToken is not None:\n self.certificate = result.certificate\n self.authToken = self._headers['X-Line-Access'] = result.authToken\n else:\n return False\n else:\n raise Exception('Login Failed')\n\n def qrLogin(self,keepLoggedIn=True, systemName=com_name, APP_NAME=app_name):\n #TalkService\n self.transport = THttpClient.THttpClient(self.LINE_AUTH_QUERY_PATH)\n self.transport.setCustomHeaders(self._headers)\n self.protocol = TCompactProtocol.TCompactProtocol(self.transport)\n self._client = TalkService.Client(self.protocol)\n #AuthService\n self.transport = THttpClient.THttpClient(self.LINE_LOGIN_QUERY_PATH)\n self.transport.setCustomHeaders(self._headers)\n self.protocol = TCompactProtocol.TCompactProtocol(self.transport)\n self._auth = AuthService.Client(self.protocol)\n\n qr = self._client.getAuthQrcode(keepLoggedIn, systemName)\n uri = \"line://au/q/\" + qr.verifier\n print(\"Open this link qr on your LINE for smartphone in 2 minutes\\n{}\".format(uri))\n self._headers = {\n 'User-Agent': self.user_agent,\n 'X-Line-Application': APP_NAME,\n \"x-lal\" : \"in_ID\",\n \"x-lpqs\" : \"/api/v4p/rs\",\n 'X-Line-Access': qr.verifier\n }\n getAccessKey = self.get_json(self.LINE_CERTIFICATE_PATH)\n req = LoginRequest()\n req.type = 1\n req.verifier = qr.verifier\n req.e2eeVersion = 1\n res = self._auth.loginZ(req)\n self.authToken = self._headers['X-Line-Access'] = res.authToken\n return self.tokenLogin()\n\n def get_json(self, url):\n \"\"\"Get josn from given url with saved session and headers\"\"\"\n return json.loads(self._session.get(url, headers=self._headers).text)\n\n def _getProfile(self):\n \"\"\"Get profile information\n\n :returns: Profile object\n - picturePath\n - displayName\n - phone (base64 encoded?)\n - allowSearchByUserid\n - pictureStatus\n - userid\n - mid # used for unique id for account\n - phoneticName\n - regionCode\n - allowSearchByEmail\n - email\n - statusMessage\n \"\"\"\n return self._client.getProfile()\n\n def _getAllContactIds(self):\n \"\"\"Get all contacts of your LINE account\"\"\"\n return self._client.getAllContactIds()\n\n def _getBlockedContactIds(self):\n \"\"\"Get all blocked contacts of your LINE account\"\"\"\n return self._client.getBlockedContactIds()\n\n def _getContacts(self, ids):\n \"\"\"Get contact information list from ids\n\n :returns: List of Contact list\n - status\n - capableVideoCall\n - dispalyName\n - settings\n - pictureStatus\n - capableVoiceCall\n - capableBuddy\n - mid\n - displayNameOverridden\n - relation\n - thumbnailUrl\n - createdTime\n - facoriteTime\n - capableMyhome\n - attributes\n - type\n - phoneticName\n - statusMessage\n \"\"\"\n if type(ids) != list:\n msg = \"argument should be list of contact ids\"\n self.raise_error(msg)\n\n return self._client.getContacts(ids)\n\n def _findAndAddContactsByMid(self, mid, seq=0):\n \"\"\"Find and add contacts by Mid\"\"\"\n return self._client.findAndAddContactsByMid(seq, mid, 0, '')\n\n def _findContactByUserid(self, userid):\n \"\"\"Find contacts by Userid\"\"\"\n return self._client.findContactByUserid(userid)\n\n def _findAndAddContactsByUserid(self, userid, seq=0):\n \"\"\"Find and add contacts by Userid\"\"\"\n return self._client.findAndAddContactsByUserid(seq, userid)\n\n def _findContactsByPhone(self, phones):\n \"\"\"Find contacts by phone\"\"\"\n return self._client.findContactsByPhone(phones)\n\n def _findAndAddContactsByPhone(self, phones, seq=0):\n \"\"\"Find and add contacts by phone\"\"\"\n return self._client.findAndAddContactsByPhone(seq, phones)\n\n def _findContactsByEmail(self, emails):\n \"\"\"Find contacts by email\"\"\"\n return self._client.findContactsByEmail(emails)\n\n def _findAndAddContactsByEmail(self, emails, seq=0):\n \"\"\"Find and add contacts by email\"\"\"\n return self._client.findAndAddContactsByEmail(seq, emails)\n\n def _createRoom(self, ids, seq=0):\n \"\"\"Create a chat room\"\"\"\n return self._client.createRoom(seq, ids)\n\n def _getRoom(self, id):\n \"\"\"Get a chat room\"\"\"\n return self._client.getRoom(id)\n\n def _inviteIntoRoom(self, roomId, contactIds=[]):\n \"\"\"Invite contacts into room\"\"\"\n return self._client.inviteIntoRoom(0, roomId, contactIds)\n\n def _leaveRoom(self, id):\n \"\"\"Leave a chat room\"\"\"\n return self._client.leaveRoom(0, id)\n\n def _createGroup(self, name, ids, seq=0):\n \"\"\"Create a group\"\"\"\n return self._client.createGroup(seq, name, ids)\n\n def _getGroups(self, ids):\n \"\"\"Get a list of group with ids\"\"\"\n if type(ids) != list:\n msg = \"argument should be list of group ids\"\n self.raise_error(msg)\n\n return self._client.getGroups(ids)\n\n def _getGroupIdsJoined(self):\n \"\"\"Get group id that you joined\"\"\"\n return self._client.getGroupIdsJoined()\n\n def _getGroupIdsInvited(self):\n \"\"\"Get group id that you invited\"\"\"\n return self._client.getGroupIdsInvited()\n\n def _acceptGroupInvitation(self, groupId, seq=0):\n \"\"\"Accept a group invitation\"\"\"\n return self._client.acceptGroupInvitation(seq, groupId)\n\n def _kickoutFromGroup(self, groupId, contactIds=[], seq=0):\n \"\"\"Kick a group members\"\"\"\n return self._client.kickoutFromGroup(seq, groupId, contactIds)\n\n def _cancelGroupInvitation(self, groupId, contactIds=[], seq=0):\n \"\"\"Cancel a group invitation\"\"\"\n return self._client.cancelGroupInvitation(seq, groupId, contactIds)\n\n def _inviteIntoGroup(self, groupId, contactIds=[], seq=0):\n \"\"\"Invite contacts into group\"\"\"\n return self._client.inviteIntoGroup(seq, groupId, contactIds)\n\n def _leaveGroup(self, id):\n \"\"\"Leave a group\"\"\"\n return self._client.leaveGroup(0, id)\n\n def _getRecentMessages(self, id, count=1):\n \"\"\"Get recent messages from `id`\"\"\"\n return self._client.getRecentMessages(id, count)\n\n def _sendMessage(self, message, seq=0):\n \"\"\"Send a message to `id`. `id` could be contact id or group id\n\n :param message: `message` instance\n \"\"\"\n return self._client.sendMessage(seq, message)\n\n def _getLastOpRevision(self):\n return self._client.getLastOpRevision()\n\n def _fetchOperations(self, revision, count=50):\n return self._client.fetchOperations(revision, count)\n\n def _getMessageBoxCompactWrapUp(self, id):\n try:\n return self._client.getMessageBoxCompactWrapUp(id)\n except:\n return None\n\n def _getMessageBoxCompactWrapUpList(self, start=1, count=50):\n try:\n return self._client.getMessageBoxCompactWrapUpList(start, count)\n except Exception as e:\n msg = e\n self.raise_error(msg)\n\n def raise_error(self, msg):\n \"\"\"Error format\"\"\"\n raise Exception(\"Error: %s\" % msg)\n\n def _get_json(self, url):\n \"\"\"Get josn from given url with saved session and headers\"\"\"\n return json.loads(self._session.get(url, headers=self._headers).text)\n\n def post_content(self, url, data=None, files=None):\n return self._session.post(url, headers=self._headers, data=data, files=files)\n","sub_path":"line/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":14800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"610005999","text":"\"\"\"\nAuthors: Emily Lepert and Vicky McDermott\n\"\"\"\nfrom interpret import Interpret\nfrom data import Data\nfrom bokeh.io import output_file, show, vform\nfrom bokeh.layouts import widgetbox\nfrom bokeh.models.widgets import RadioGroup, Div, Button\n\nclass Question():\n\t\n\t# placeholder radiogroup variable so it can be modified later\n\tanswer = RadioGroup(labels=['dfd', 'dfd'])\n\n\tdef __init__(self,index, interpret, data_type, data):\n\t\t'''\n\t\tDetermines layout of the question child\n\n\t\tAttributes: data_type, interpret, index, qa, question_typed_out, question\n\t\t'''\n\t\t#differentiates between earthquake and comma\n\t\tself.data_type = data_type\n\t\t#Interpret class reference\n\t\tself.interpret = interpret\n\t\t#question number in either earthquake or comma\n\t\tself.index = index\n\t\t#dictionary of questions and answers from the Interpret class\n\t\tself.qa = self.interpret.dictionary_of_qa()\n\n\t\t# Written out question\n\t\tself.question_typed_out = data.get_question(self.index)\n\n\t\t# Question text div\n\t\tself.question = Div(text=self.question_typed_out)\n\n\tdef get_fig(self):\n\t\t'''\n\t\tCreates the question and answer widget\n\t\t'''\n\n\t\t#creates a radio group with the appropriate answer options\n\t\tlength = len(self.qa[self.index])\n\t\tQuestion.answer = RadioGroup(labels=self.get_list_answers(length))\n\t\tchoices = widgetbox(self.question, Question.answer)\n\t\titems = length\n\n\t\treturn([choices, items])\n\n\tdef get_list_answers(self, items):\n\t\t'''\n\t\tOutputs the list of answers for the question\n\t\t'''\n\t\tlist_answers = []\n\t\tfor i in range(items):\n\t\t\tlist_answers.append(self.interpret.key_formatting(self.qa[self.index][i]))\n\t\treturn(list_answers)\n\n","sub_path":"question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"6561779","text":"from src.custom_kernel import gaussian_kernel, triangular_kernel\nfrom src.b_cov import b_cov\nfrom src.support_bound import support_bound\nimport numpy as np\n\n\ndef lrv_hat_nw_2_of_single_t(sample: np.array, t_par: float) -> float:\n '''\n This function should give the same result as lrv_hat_of_single_t_nw,\n though it does not so far. \n In this connection, we need to look at lag bounds. \n It returns the value for a single t_par. \n Recently renamed. Was lrv_hat_of_t_nw_2.\n Note that here we do nt have the explicit notion of lag. \n '''\n sample_size = len(sample)\n b_cov_value = b_cov(sample_size=sample_size)\n\n nw_hat = 0\n for i, x_i in enumerate(sample, start=1):\n for j, x_j in enumerate(sample, start=1):\n kernel_cov = gaussian_kernel(v=((np.minimum(i, j) / sample_size) -\n t_par) / b_cov_value) * (1 / (\n sample_size * b_cov_value))\n lag = i-j\n kernel_nw = triangular_kernel(v=np.abs(lag) / support_bound(\n sample_size=sample_size))\n nw_hat += kernel_cov * kernel_nw * x_i * x_j\n # print(\"lrv_hat_of_single_t_nw_2 external sum\", len(sample) - i)\n\n return nw_hat\n","sub_path":"project2/src/lrv_hat_nw_2_of_single_t.py","file_name":"lrv_hat_nw_2_of_single_t.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"250248143","text":"class Solution:\n def maxCoins(self, nums: List[int]) -> int:\n n = len(nums)\n nums.insert(0,1)\n nums.append(1)\n dp = [[0 for i in range(n+2)]for j in range(n+2)]\n for i in range(n+1,-1,-1):\n for j in range(i+2,n+2):\n for k in range(i+1,j):\n if dp[i][k]+dp[k][j]+nums[i]*nums[j]*nums[k]>dp[i][j]:\n dp[i][j] = dp[i][k]+dp[k][j]+nums[i]*nums[j]*nums[k]\n return dp[0][n+1]","sub_path":"Codes/Daily-Practice/t312.py","file_name":"t312.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"20694495","text":"# -*- coding: utf-8 -*-\n\nfrom app.constants import S_OK, S_ERR\n\nimport random\nimport math\nimport base64\nimport time\nimport ujson as json\nfrom StringIO import StringIO\n\nimport sys\nimport argparse\nfrom lxml import html\n\nfrom app import cfg\nfrom app import util\n\ndef cron_new_taipei_city():\n while True:\n error_code = _cron_new_taipei_city()\n _sleep()\n pass\n\n\ndef _cron_new_taipei_city():\n params = _get_params()\n (error_code, results) = _crawl_data(params)\n return error_code\n\n\ndef _get_params():\n '''\n 1. lookup the latest data in mongo.\n 2. return the latest params of data.\n '''\n latest_dig = util.get_cache('cron_new_taipei_city_latest_dig')\n return {'latest_dig': latest_dig}\n\n\ndef _crawl_data(params):\n results = _crawl_dig(params['latest_dig'])\n return (S_OK, results)\n\n\ndef _crawl_dig(last_dig):\n the_url = 'http://61.60.124.185/tpctempdig/InfoAllList.asp'\n params = {\n 'sortflag': '',\n 'sorttype': '',\n 'TargetLB': '',\n 'startyear': last_dig.get('start_year', 2000),\n 'startmonth': last_dig.get('start_month', 1),\n 'endyear': last_dig.get('end_year', 2014),\n 'endmonth': last_dig.get('end_month', 12),\n 'endday': last_dig.get('endday', 31)\n }\n\n http_data = util.http_multipost({the_url: params})\n #cfg.logger.debug('http_data: %s', http_data)\n dig_data = _parse_dig(http_data[the_url])\n\n [_put_to_db(each_data) for each_data in dig_data]\n\n\ndef _parse_dig(http_data):\n #cfg.logger.debug('http_data_type: %s', http_data.__class__.__name__)\n http_data_ascii = http_data.encode('iso-8859-1')\n data_utf8 = util.big5_to_utf8(http_data_ascii)\n #cfg.logger.debug('data_utf8: %s', data_utf8)\n\n data_list = _parse_dig_data(data_utf8)\n return data_list\n\n\ndef _parse_dig_data(data):\n doc = html.parse(StringIO(data))\n #cfg.logger.debug('doc: %s', doc)\n\n results = [_parse_element(elem) for elem in doc.iter('tr')]\n results = [result for result in results if result]\n \n return results\n\n\ndef _parse_element(elem):\n text = elem.text_content()\n #cfg.logger.debug('text: %s', text)\n return _parse_text(text)\n\ndef _parse_text(text):\n _columns = [ '', 'OK_UNITpro', 'IDpro', 'APP_NAMEpro', 'LOCATIONpro', 'CB_DATEpro', 'APPROVE_DATEpro']\n\n f = StringIO(text)\n lines = f.readlines()\n n_lines = len(lines)\n if n_lines > 10 or n_lines < 7:\n cfg.logger.error('lines > 10: lines: %s', lines)\n return {}\n\n result = {column: lines[idx].strip() for (idx, column) in enumerate(_columns) if column}\n if not result.get('OK_UNITpro', ''):\n result = {}\n if not result.get('CB_DATEpro', ''):\n result = {}\n\n cfg.logger.debug('result: %s', result)\n \n return result\n\n\ndef _put_to_db(data):\n category = 'new_taipei_city_dig_point'\n the_idx = data['IDpro']\n the_id = category + '_' + the_idx\n the_key = {'the_category': category, 'the_id': the_id, 'the_idx': the_idx}\n util.db_update('roadDB', the_key, data)\n\n\ndef _sleep():\n time_sleep = util._int(cfg.config.get('time_sleep', 3600))\n cfg.logger.debug('to sleep: time_sleep: %s', time_sleep)\n time.sleep(time_sleep)\n\n\ndef parse_args():\n ''' '''\n parser = argparse.ArgumentParser(description='roadpin_backend')\n parser.add_argument('-i', '--ini', type=str, required=True, help=\"ini filename\")\n\n args = parser.parse_args()\n\n return (S_OK, args)\n\n\nif __name__ == '__main__':\n (error_code, args) = parse_args()\n\n cfg.init({\"ini_filename\": args.ini})\n\n cron_new_taipei_city()\n\n","sub_path":"roadpin_backend/app/cron_data/cron_new_taipei_city.py","file_name":"cron_new_taipei_city.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"94001815","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport smart_selects.db_fields\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('tipo_eleccion', '0001_initial'),\n ('estados', '0002_auto_20150129_1844'),\n ('elecciones', '0001_initial'),\n ('categoria_eleccion', '0001_initial'),\n ('municipios', '0002_auto_20150128_1900'),\n ('circuitos', '0002_auto_20150129_1331'),\n ('parroquias', '0002_auto_20150130_1504'),\n ('partidos', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Candidatos',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nombre', models.CharField(max_length=100, verbose_name=b'Nombre del Candidato')),\n ('apellido', models.CharField(max_length=100, verbose_name=b'Apellido del Candidato')),\n ('cedula', models.CharField(unique=True, max_length=8, verbose_name=b'C\\xc3\\xa9dula')),\n ('foto', models.ImageField(upload_to=b'')),\n ('sexo', models.CharField(default=0, max_length=15, choices=[(b'0', b'Femenino'), (b'1', b'Masculino')])),\n ('edad', models.IntegerField()),\n ('twitter', models.CharField(unique=True, max_length=200)),\n ('fecha_create', models.DateTimeField(auto_now_add=True)),\n ('fecha_update', models.DateTimeField(auto_now=True, null=True)),\n ('circuito', models.ForeignKey(to='circuitos.Circuito', null=True)),\n ('eleccion', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, to='elecciones.Eleccion', chained_model_field=b'tipo_eleccion', chained_field=b'tipo_candidatura', null=True)),\n ('estado', models.ForeignKey(to='estados.Estado', null=True)),\n ('municipio', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, to='municipios.Municipio', chained_model_field=b'estado', chained_field=b'estado', null=True)),\n ('parroquia', smart_selects.db_fields.ChainedForeignKey(auto_choose=True, to='parroquias.Parroquia', chained_model_field=b'municipio', chained_field=b'municipio', null=True)),\n ('part_politico', models.ForeignKey(verbose_name=b'Partido Pol\\xc3\\xadtico', to='partidos.Partidos')),\n ('tipo_candidatura', smart_selects.db_fields.ChainedForeignKey(chained_model_field=b'categoria', chained_field=b'tipo_eleccion', auto_choose=True, to='tipo_eleccion.Tipo_eleccion')),\n ('tipo_eleccion', models.ForeignKey(verbose_name=b'Tipo de Elecci\\xc3\\xb3n', to='categoria_eleccion.Categoria')),\n ('user_create', models.ForeignKey(related_name='+', blank=True, to=settings.AUTH_USER_MODEL, null=True)),\n ('user_update', models.ForeignKey(related_name='+', blank=True, to=settings.AUTH_USER_MODEL, null=True)),\n ],\n options={\n 'ordering': ('nombre', 'apellido'),\n },\n bases=(models.Model,),\n ),\n migrations.AlterUniqueTogether(\n name='candidatos',\n unique_together=set([('cedula', 'nombre', 'apellido')]),\n ),\n ]\n","sub_path":"exit_poll/apps/candidatos/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"274407708","text":"import torch\nfrom torch import nn\nfrom torchvision import datasets, transforms\nimport torch.nn.functional as F\n\n### MODEL ###\nclass MLPBlock(nn.Module):\n def __init__(self, inplane, outplane, args):\n super(MLPBlock, self).__init__()\n self.linear = nn.Linear(inplane, outplane)\n \n# w = torch.nn.init.xavier_uniform_(torch.rand(outplane, inplane), gain=1.0)\n# self.linear_weight = nn.Parameter(w)\n# self.linear_bias = nn.Parameter(torch.rand(outplane))\n# self.linear_bias.data.fill_(0.1)\n\n w1 = torch.nn.init.xavier_uniform_(torch.rand(1, inplane), gain=1.0)\n self.linear_w1 = nn.Parameter(w1)\n w2 = torch.nn.init.xavier_uniform_(torch.rand(outplane, 1), gain=1.0)\n self.linear_w2 = nn.Parameter(w2)\n self.linear_bias = nn.Parameter(torch.rand(outplane))\n self.linear_bias.data.fill_(0.1)\n \n w1 = torch.nn.init.xavier_uniform_(torch.rand(1, inplane), gain=1.0)\n self.linear_w1_2 = nn.Parameter(w1)\n w2 = torch.nn.init.xavier_uniform_(torch.rand(outplane, 1), gain=1.0)\n self.linear_w2_2 = nn.Parameter(w2)\n \n self.sign = torch.diag(torch.sign(torch.rand(inplane))).to(\"cuda:{}\".format(args.device))\n \n self.bn = nn.BatchNorm1d(outplane, affine=args.bn_affine)\n self.act = nn.ReLU()\n \n def forward(self, x):\n# Sign weight\n# x = F.linear(x, torch.mm(torch.abs(self.linear_weight), self.sign) , torch.abs(self.linear_bias))\n# two 相乘\n# print(torch.mm(self.linear_w2.view(1,-1), self.linear_w1))\n x = F.linear(x, torch.mm(self.linear_w2, self.linear_w1) + torch.mm(self.linear_w2_2, self.linear_w1_2) , self.linear_bias)\n# original\n# x = F.linear(x, self.linear_weight , self.linear_bias) # epoch 0: 93%\n x = self.act(x)\n x = self.bn(x)\n return x\n \nclass signMLP(nn.Module):\n def __init__(self, args):\n super(signMLP, self).__init__()\n self.bn_affine = True if args.bn_affine == 1 else False\n if args.dataset == \"mnist\":\n self.units = [784, 512, 512, 128]\n self.output_layer = nn.Linear(self.units[-1], 10) \n elif args.dataset == \"cifar\":\n self.units = [3072, 256, 256, 256, 256, 256]\n self.output_layer = nn.Linear(self.units[-1], 10)\n\n self.module_list = nn.ModuleList( [MLPBlock(self.units[i], self.units[i+1], args) for i in range(len(self.units)-1)])\n self.f3 = nn.Dropout(p=0.2)\n self.act2 = nn.ReLU()\n \n def forward(self, data):\n x = data\n output = []\n for module in self.module_list:\n x_ = module(x.detach())\n x = module(x)\n output.append(x_)\n x = self.f3(x)\n x_ = self.act2(self.output_layer(x.detach()))\n x = self.act2(self.output_layer(x))\n output.append(x_)\n return x, output","sub_path":"models/.ipynb_checkpoints/signMLP-checkpoint.py","file_name":"signMLP-checkpoint.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"634471488","text":"# -*- coding:UTF-8 -*-\n\nfrom sqlalchemy import func, and_, or_\nfrom database.models import WorkDailyRecord, FigurePermission, Permission, Menu, Role, UserRole, Status\nimport os\nimport logging\nimport datetime\nimport json\nfrom handlers.util import send_message\n\nasync def getProjectStatus(db):\n status = db.query(Status).filter(Status.code.in_(['04', '05', '06', '07', '08'])).all()\n return status\n\nasync def getProjectInfo(db, page, limit, project_no, project_name, manager_user, charge_user, project_status, user_id):\n sql = \"\"\"\n select distinct pp.id,pp.code project_no,pp.name project_name,pp.t_start_date,\n pu.username charge_user,pu2.username manage_user,(select pps.name from \n pms_project_stage pps\n left join pms_project_dev ppd on ppd.stage_id = pps.id\n left join pms_project pp2 on pp2.pms_dev_id = ppd.id\n where pp2.id = pp.id) project_dev,pralp1.name risk_level,pralp1.name property,ps.name status,\n ( select count(distinct pp.id) \n from pms_project pp2\n left join pms_team pt on pp2.id = pt.project_id\n where pp2.id = pp.id and (pt.user_id = :user_id or pp2.manager_user_id = :user_id or pp2.charge_user_id = :user_id)) is_show\n from pms_project pp\n left join pms_team pt on pp.id = pt.project_id\n left join pms_user pu on pu.id = pp.charge_user_id\n left join pms_user pu2 on pu2.id = pp.manager_user_id\n left join pms_risk_and_level_param pralp1 on pralp1.id = pp.pms_risk_level\n left join pms_risk_and_level_param pralp2 on pralp2.id = pp.pms_level\n left join pms_status ps on ps.id = pp.status where 1=1\n \"\"\"\n pt = db.query(func.count(FigurePermission.id)).join(Permission, Permission.id == FigurePermission.permission_id) \\\n .filter(Permission.name == '查看所有项目').join(Menu, Menu.id == Permission.menu_id).filter(Menu.name == '项目工作报告') \\\n .join(Role, Role.id == FigurePermission.role_id).join(UserRole, UserRole.role_id == Role.id) \\\n .filter(UserRole.user_id == int(user_id)).scalar()\n if pt == 0:\n sql = sql + \" and (pt.user_id = :user_id or pp.manager_user_id = :user_id or pp.charge_user_id = :user_id)\"\n if project_no is not None and project_no != '':\n sql = sql + \" and pp.code = '%s'\" % project_no\n if project_name is not None and project_name != '':\n sql = sql + \" and pp.name = '%s'\" % project_name\n if charge_user is not None and charge_user != '':\n sql = sql + \" and pu.username = '%s'\" % charge_user\n if manager_user is not None and manager_user != '':\n sql = sql + \" and pu2.username = '%s'\" % manager_user\n if project_status is not None and project_status != '':\n sql = sql + \" and pp.status = %d\" % int(project_status)\n sql += \" order by pp.id desc\"\n last_sql = \"\"\"\n select * from (\n select p.*,rownum rn from (\n %s\n ) p where rownum <= %d\n ) q where q.rn > %d\n \"\"\" % (sql, page * limit, page * limit - limit)\n SQL_COUNT = '''select count(0) from (%s)''' % sql\n count = db.execute(SQL_COUNT,{'user_id':int(user_id)}).first()[0]\n lines = db.execute(last_sql,{'user_id':int(user_id)})\n projects = [dict(zip(row.keys(), row)) for row in lines]\n return count, projects\n\nasync def add_work_log(db, pro_id, time_choose, work_log, user_id):\n insert_time = datetime.datetime.strptime(time_choose, '%Y-%m-%d')\n db.add(WorkDailyRecord(inner=work_log,build_time=insert_time,user_id=user_id,pro_id=int(pro_id)))\n return 0, '提交成功'\n\nasync def get_work_log(db, pro_id, watch_time):\n sql = \"\"\"\n select pu.id user_id,pu.userno user_code,pu.username user_name,to_char(pwdr.build_time,'yyyy-mm-dd') build_time,pwdr.inner,\n pwdr.id\n from pms_work_daily_record pwdr\n left join pms_user pu on pu.id = pwdr.pms_user_id\n where pwdr.pms_project_id = :pro_id and to_char(pwdr.build_time,'yyyy-mm-dd') = :time\n \"\"\"\n if watch_time is None or watch_time == \"\":\n build_time = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d')\n else:\n build_time = watch_time\n mid_data = db.execute(sql,{'pro_id':int(pro_id),'time':build_time})\n data = [dict(zip(row.keys(), row)) for row in mid_data]\n return data, build_time\n\nasync def del_work_log(db, log_id):\n work_log = db.query(WorkDailyRecord).filter(WorkDailyRecord.id == int(log_id)).with_for_update().first()\n if work_log is None:\n return 1,该条日志已被删除\n db.delete(work_log)\n return 0 ,'成功删除日志'\n\nasync def get_work_log_inner(db, log_id):\n work_log = db.query(WorkDailyRecord).filter(WorkDailyRecord.id == int(log_id)).first()\n return work_log.inner,datetime.datetime.strftime(work_log.build_time, '%Y-%m-%d')\n\nasync def change_work_log(db, log_id, new_inner):\n work_log = db.query(WorkDailyRecord).filter(WorkDailyRecord.id == int(log_id)).with_for_update().first()\n if work_log is None:\n return 1,该条日志已不存在\n work_log.inner = new_inner\n return 0 ,'修改成功'\n","sub_path":"services/projectManager/projectWorkLog.py","file_name":"projectWorkLog.py","file_ext":"py","file_size_in_byte":5241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"582655467","text":"from django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render\n\n# Create your views here.\nimport json\n\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom book.BookInfoSerializer import BookInfoSerializer\nfrom book.models import BookInfo\n\n\ndef login_required(func_view):\n def wrapper(req, *args, **kwargs):\n if False:\n return func_view(req, *args, **kwargs)\n else:\n return HttpResponse('login ok')\n return wrapper\n\n\ndef index(req):\n if req.method == 'GET':\n return HttpResponse('ok')\n else:\n return HttpResponse('This is post request')\n\n\ndef test_template(req):\n return render(req, 'test_template.html', context={\n 'name': 'TEM'\n })\n\n\ndef get_books(req):\n books = BookInfo.objects.all();\n # books = list(books)\n datas = []\n for book in books:\n datas.append({\n 'name': book.name,\n 'pub_date': book.pub_date\n })\n\n return JsonResponse(data={'data': datas}, safe=False)\n\ndef post_book(req):\n data = json.loads(req.body.decode())\n print('收到数据为')\n print(data)\n # 省略校验逻辑\n book = BookInfo.objects.create(\n name = data.get('name'),\n pub_date = data.get('pubdate')\n )\n return JsonResponse(data={\n 'id': book.id,\n 'name': book.name,\n 'pub_date': book.pub_date,\n 'readcount': book.readcount\n\n }, status='201', safe=False )\n\n\ndef put_book(req, id):\n if req.method == 'PUT':\n try:\n book = BookInfo.objects.get(pk=id)\n except:\n return HttpResponse(status=404)\n data = json.loads(req.body.decode())\n book.name = data.get('name')\n book.pub_date= data.get('pub_date')\n book.save()\n return JsonResponse(data={\n 'id': book.id,\n 'name': book.name,\n 'pub_date': book.pub_date,\n 'readcount': book.readcount\n\n }, status='201', safe=False )\n\n\ndef del_book(req, id):\n if req.method == 'DELETE':\n try:\n book = BookInfo.objects.get(pk=id)\n except BookInfo.DoesNotExist:\n return HttpResponse(status=404)\n book.delete()\n return HttpResponse('ok', status=204)\n\n\n\ndef get_books_rest(req):\n pass\n\ndef get_books_apiviw(req):\n pass\n\n\nclass BookInfoViewSet(ModelViewSet):\n queryset = BookInfo.objects.all()\n serializer_class = BookInfoSerializer\n\n","sub_path":"bookmanager345/book/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"285661351","text":"'''\n896. Monotonic Array\nAn array is monotonic if it is either monotone increasing or monotone decreasing.\n\nAn array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].\n\nGiven an integer array nums, return true if the given array is monotonic, or false otherwise.\n\n \n\nExample 1:\n\nInput: nums = [1,2,2,3]\nOutput: true\nExample 2:\n\nInput: nums = [6,5,4,4]\nOutput: true\nExample 3:\n\nInput: nums = [1,3,2]\nOutput: false\nExample 4:\n\nInput: nums = [1,2,4,5]\nOutput: true\nExample 5:\n\nInput: nums = [1,1,1]\nOutput: true\n \n\nConstraints:\n\n1 <= nums.length <= 105\n-105 <= nums[i] <= 105\n'''\nclass Solution(object):\n def isMonotonic(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n increasing = True\n decreasing = True\n\n for index in range(len(nums) - 1):\n \tif nums[index] > nums[index + 1]:\n \t\tincreasing = False\n \tif nums[index] < nums[index + 1]:\n \t\tdecreasing = False\n\n return increasing or decreasing","sub_path":"MonotonicArray.py","file_name":"MonotonicArray.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"374256893","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 30 09:58:22 2018\n\n@author: Mir, A.\n\"\"\"\n\n\"\"\"\nIn this module, KNNs will be computed for weight calcalution.\nTwo KNN algorithms:\n 1- Full search algorithm (FSA)\n 2- LDMDBA algorithm\n\"\"\"\n\nfrom scipy.spatial.distance import pdist, squareform\nfrom sklearn.model_selection import train_test_split\nfrom dataproc import read_data\nimport numpy as np\n# C++ extension module for LDMDBA algorithm\n#import ldmdba\nimport imp_ldmdba\nimport time\n\n\ndef index_find(data_sample, data_label):\n \n \"\"\"\n Returns index of class 1 and class -1\n \"\"\"\n \n s_class1 = np.where(data_label == 1)[0] # Indices of class +1\n s_class_1 = np.where(data_label == -1)[0] # Indies of class -1\n \n return s_class1, s_class_1\n\n\ndef knn_sample(data, dist_matrix, k):\n \n \"\"\"\n Returns k-nearest neighbors of a sample\n \"\"\"\n \n # Store index of knn samples\n index_knn = np.zeros((data.shape[0], k), dtype=np.int)\n \n for sample_index in range(data.shape[0]):\n \n # distance of that sample to other samples\n dist = dist_matrix[sample_index, :]\n \n # Get index of sorted distances\n dist_sample = np.argsort(dist)[1:]\n \n # Get index of k nearest neighbor of a sample\n knn_sample = dist_sample[:k]\n \n # Get index\n for i in range(knn_sample.shape[0]):\n \n index_knn[sample_index, i] = knn_sample[i]\n \n return index_knn\n\n\ndef weight_dist_fsa(data_dist, index_knn):\n \n \"\"\"\n Computes weight matrix with respect to distance.\n KNNs were found using FSA algorithm\n \"\"\"\n \n # Define weight matrix\n weight_matrix = np.zeros((data_dist.shape[0], data_dist.shape[0]))\n \n for i in range(weight_matrix.shape[0]):\n \n # i = j -> A sample is nearest neighbor of itself!\n weight_matrix[i, i] = 1\n \n for j in index_knn[i]:\n \n if data_dist[i, index_knn[i][-1]] != data_dist[i, index_knn[i][0]]:\n \n weight_matrix[i, j] = (data_dist[i, index_knn[i][-1]] - \\\n data_dist[i, j]) / (data_dist[i, index_knn[i][-1]] - \\\n data_dist[i, index_knn[i][0]])\n \n else:\n \n weight_matrix[i, j] = 1\n \n \n return weight_matrix \n\n \ndef weight_dist_ldmdba(index_knn):\n \n \"\"\"\n Computes weight matrix with respect to distance.\n KNNs were found using LDMDBA algorithm\n \"\"\"\n \n # Number of samples\n num_s = len(index_knn)\n \n # Number of KNNs\n num_k = len(index_knn[0])\n \n # Define weight matrix\n weight_matrix = np.zeros((num_s, num_s))\n \n for i in range(num_s):\n \n # i = j -> A sample is nearest neighbor of itself!\n weight_matrix[i, i] = 1\n \n for j in range(num_k):\n \n if index_knn[i][j][0] != index_knn[i][-1][0]:\n \n weight_matrix[i, index_knn[i][j][1]] = (index_knn[i][-1][0] - \\\n index_knn[i][j][0]) / (index_knn[i][-1][0] - \\\n index_knn[i][0][0])\n \n else:\n \n weight_matrix[i, index_knn[i][j][1]] = 1\n \n \n return weight_matrix \n\n\ndef weight_sample(within_class_g):\n \n \"\"\"\n Computes within-class graph for a class.\n Returns weight of each sample.\n \"\"\"\n \n # Within class graph\n weight_mat = np.zeros((within_class_g.shape[0], 1))\n \n for j in range(within_class_g.shape[0]):\n \n weight_mat[j, 0] = np.sum(within_class_g[:, j])\n \n return weight_mat\n \n\ndef bc_weight(weight, class_index, mat_type=np.int):\n \n \"\"\"\n Returns between-class graph\n \"\"\"\n \n # Define between-class weight\n bc_weight_mat = np.zeros((class_index[0].shape[0], class_index[1].shape[0]), dtype=mat_type)\n \n for i in range(bc_weight_mat.shape[0]):\n \n # get real index of that sample in the entire dataset\n index_c1 = class_index[0][i] # class 1\n \n bc_weight_mat[i, :] = weight[index_c1, class_index[1]]\n \n return bc_weight_mat\n\n\ndef margin_points(between_c_w):\n \n \"\"\"\n Returns margin points\n \"\"\"\n \n margin_weight = np.zeros((between_c_w.shape[1], 1), dtype=np.int)\n \n for i in range(margin_weight.shape[0]):\n \n if np.count_nonzero(between_c_w[:, i]) > 0:\n \n margin_weight[i, 0] = 1\n \n else:\n \n margin_weight[i, 0] = 0\n \n return margin_weight\n\n\ndef weight_matrices(train_data, data_label, k, method='FSA'):\n\n \"\"\"\n Computes within-class graph and between-class grpah (margin points)\n Weights are given with respect to distance between pair of neighbors\n Using either or FSA or LDMDBA algorithm\n \"\"\"\n \n # find index of samples of class 1 and -1\n class_idx = index_find(train_data, data_label)\n \n if method == 'FSA':\n \n # The following computation is for the entire dataset\n # FSA algorithm\n distance_mat = squareform(pdist(train_data, 'euclidean'))\n k_sample = knn_sample(train_data, distance_mat, k)\n weight_m = weight_dist_fsa(distance_mat, k_sample)\n \n else:\n \n # Extended LDMDBA for KNN fidning- Implemented in C++\n #k_sample = ldmdba.ext_ldmdba(train_data, k)\n k_sample = imp_ldmdba.ext_ldmdba(train_data, k) # Optimized version\n weight_m = weight_dist_ldmdba(k_sample)\n \n # Class 1\n # Within class graph- It's sub-graph of weight\n wc_weight_c1 = weight_m[class_idx[0][:, None], class_idx[0]]\n # Compute weight each sample\n weight_s_c1 = weight_sample(wc_weight_c1)\n # Between class-graph\n bc_weight_c1 = bc_weight(weight_m, class_idx, np.float) # Pass float!\n # Compute margin points for class -1\n margin_p_c1 = margin_points(bc_weight_c1).reshape(bc_weight_c1.shape[1],)\n \n # Class 2\n wc_weight_c2 = weight_m[class_idx[1][:, None], class_idx[1]]\n weight_s_c2 = weight_sample(wc_weight_c2)\n # Between class-graph\n bc_weight_c2 = bc_weight(weight_m, (class_idx[1], class_idx[0]), np.float)\n # Compute margin points for class +1\n margin_p_c2 = margin_points(bc_weight_c2).reshape(bc_weight_c2.shape[1],)\n \n return weight_s_c1, margin_p_c1, weight_s_c2, margin_p_c2\n\n\nif __name__ == '__main__':\n \n train_samples, lables, file_name = read_data('../dataset/pima-indian.csv')\n \n X_train, X_test, y_train, y_test = train_test_split(train_samples, lables, \\\n test_size=0.2, random_state=42)\n \n start_time = time.time()\n \n test = weight_matrices(X_train, y_train, 5, 'ld')\n \n print(\"Finished: %.2f ms\" % ((time.time() - start_time) * 1000))\n","sub_path":"src/KNN_Weight.py","file_name":"KNN_Weight.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"416045966","text":"import math\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom root.code.cnn import check\n\n\nclass Image:\n\n def __init__(self, path, size, model):\n self.model = model\n self.size = size\n self.img_size = (20, 20)\n self.path = path\n self.img = ''\n self.read_image()\n self.im_crop()\n self.im_contrast()\n self.im_threshold(130)\n self.im_blur(4)\n self.im_threshold(175)\n self.im_blur(4)\n self.im_threshold(160)\n self.rgb_2_gray()\n self.detect_objects()\n\n def read_image(self):\n self.img = cv2.imread(self.path, 1)\n\n def im_show(self):\n plt.figure(figsize=self.img_size)\n plt.imshow(self.img, cmap='gray')\n plt.show()\n\n def im_crop(self):\n self.img = self.img[180:557, 417:795]\n self.img = cv2.resize(self.img, (500, 500), interpolation=cv2.INTER_AREA)\n #self.im_show()\n\n def im_contrast(self):\n alpha = 2 # Contrast control (1.0-3.0)\n beta = 50 # Brightness control (0-100)\n self.img = cv2.convertScaleAbs(self.img, alpha=alpha, beta=beta)\n #self.im_show()\n\n def im_threshold(self, limit):\n # Threshold on the crop and contrast image\n _, self.img = cv2.threshold(self.img, limit, 255, cv2.THRESH_BINARY)\n #self.im_show()\n\n def im_blur(self, size):\n self.img = cv2.blur(self.img, (size, size))\n #self.im_show()\n\n def rgb_2_gray(self):\n self.img = cv2.cvtColor(self.img, cv2.COLOR_BGR2GRAY)\n\n def detect_objects(self):\n contours, hierarchy = cv2.findContours(self.img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:]\n cnt = contours[0]\n x, y, w, h = cv2.boundingRect(cnt)\n self.img = cv2.rectangle(self.img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n coeff = 1.53506295623346405\n contours, _ = cv2.findContours(self.img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2:]\n self.img = cv2.cvtColor(self.img, cv2.COLOR_GRAY2RGB)\n\n path = r'C:\\Users\\SHYROKOA\\Desktop\\test'\n dest = r'C:\\Users\\SHYROKOA\\Desktop\\blur'\n\n for i, contour in enumerate(contours):\n if i != len(contours) - 1: # we don't need the last contour\n x, y, w, h = cv2.boundingRect(contour)\n aspect_ratio = w/h\n crop_img = self.img[y:y+h, x:x+w]\n\n # calculate the ox and oy\n ox = x + w/2\n oy = y + h/2\n\n # calculate the black pixels number\n black = count_black(crop_img)\n\n # calculate the white pixels number\n white = black / coeff\n\n # total box pixels\n total = white + black\n\n b = int(round(math.sqrt(total / aspect_ratio)))\n a = int(round(aspect_ratio * b))\n\n # new coordinates\n x = int(round(ox - a/2))\n y = int(round(oy - b/2))\n w = a\n h = b\n\n crop_img = cv2.resize(crop_img, (50, 50))\n crop_img = cv2.blur(crop_img, (3, 3))\n _, crop_img = cv2.threshold(crop_img, 160, 255, cv2.THRESH_BINARY)\n crop_img = cv2.cvtColor(crop_img, cv2.COLOR_RGB2GRAY)\n qw = check(crop_img, self.size, self.model)\n\n if qw == 'circle':\n cv2.rectangle(self.img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n if x < 250:\n cv2.putText(self.img, f'Circle Detected {i} -> X: {(x + w) / 2}, y: {(y + h) / 2}',\n (x + w + 10, y + h - 5), 0, 0.26, (192, 52, 52))\n else:\n cv2.putText(self.img, f'Circle Detected {i} -> X: {(x + w) / 2}, y: {(y + h) / 2}',\n (x + w + 10 - 200, y + h - 5), 0, 0.26, (192, 52, 52))\n else:\n cv2.rectangle(self.img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n if x < 250:\n cv2.putText(self.img, f'Not circle Detected {i} -> X: {(x + w) / 2}, y: {(y + h) / 2}',\n (x + w + 10, y + h - 5), 0, 0.26, (192, 52, 52))\n else:\n cv2.putText(self.img, f'Not circle Detected {i} -> X: {(x + w) / 2}, y: {(y + h) / 2}',\n (x + w + 10 - 200, y + h - 5), 0, 0.26, (192, 52, 52))\n self.im_show()\n\n\ndef count_black(img):\n cnt = ''\n colors, counts = np.unique(img.reshape(-1, 1), axis=0, return_counts=True)\n for color, count in zip(colors, counts):\n if color[0] == 0:\n cnt = count\n return cnt\n\n\n","sub_path":"root/code/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"281955914","text":"import os\n\nfrom ConfigParser import RawConfigParser\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nPROJECT_DIR = os.path.dirname(__file__)\nCONF_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n\nhere = lambda x: os.path.join(os.path.abspath(os.path.dirname(__file__)), x)\n\n# you will need to copy the example and make custom\n# settings for the environment\nconfig = RawConfigParser()\n\n#place in a dir that is not managed in the code base\n# print 'config dir: {0}/conf/gitpatron_settings.ini'.format(CONF_DIR)\nconfig.read('{0}/conf/callpug.ini'.format(CONF_DIR))\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = config.get('secrets','DJANGO_SECRET_KEY')\n\nCALLPUG_SECRET_KEY = config.get('secrets','CALLPUG_SECRET_KEY')\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = config.get('debug','DEBUG') in ['true']\nTEMPLATE_DEBUG = config.get('debug','TEMPLATE_DEBUG') in ['true']\n\nALLOWED_HOSTS = config.get('debug','ALLOWED_HOSTS').split(\",\")\n\n# Application definition\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.humanize',\n 'timezone_field',\n 'notifications',\n 'app',\n 'cpadmin',\n 'app.templatetags'\n)\n\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\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n #timezone\n # 'app.middleware.common.CommonMiddleware',\n 'app.util.timezone.TimezoneMiddleware'\n\n\n)\n\nROOT_URLCONF = 'callpug.urls'\n\nWSGI_APPLICATION = 'callpug.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\n# if config.get('callpug_app','CALLPUG_APP_ENV') == 'DEV':\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.sqlite3',\n# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n# }\n# }\n#\n# else:\n\nDATABASES = {\n 'default': {\n 'ENGINE': config.get('database','DATABASE_ENGINE'), # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'callpug', # Or path to database file if using sqlite3.\n # The following settings are not used with sqlite3:\n 'USER': config.get('database','DATABASE_USER'),\n 'PASSWORD': config.get('database','DATABASE_PASSWORD'),\n 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\n 'PORT': '', # Set to empty string for default.\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n\n# STATIC_ROOT = os.path.join(PROJECT_DIR, '../', 'static/')\n# print 'static root:{0}'.format(STATIC_ROOT)\n\nADMIN_MEDIA_PREFIX = '/static/admin/'\n\n#STATIC_ROOT = os.path.join(BASE_DIR, '', 'static/')\n# print 'static dir {0}'.format(STATIC_ROOT)\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n # os.path.join(BASE_DIR, '/static/'),\n # '/Users/claytongraham/data/github/callpug/static',\n os.path.join(BASE_DIR, '', 'static/'),\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# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\nFILE_UPLOAD_HANDLERS = (\"django.core.files.uploadhandler.MemoryFileUploadHandler\",\n \"django.core.files.uploadhandler.TemporaryFileUploadHandler\",)\n\nTEMPLATE_DIRS = (\n os.path.join(BASE_DIR, 'app/templates'),\n)\n\nSESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n \"django.core.context_processors.static\",\n \"django.core.context_processors.tz\",\n 'django.core.context_processors.request',\n 'django.contrib.messages.context_processors.messages',\n)\n\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nAUTH_USER_MODEL = 'app.CallpugUser'\n\nLOGIN_URL = '/login/'\nLOGIN_REDIRECT_URL = '/home.html'\nLOGIN_ERROR_URL = '/login-error/'\n\n\nURL_PATH = ''\n\n# SOCIAL_AUTH_STRATEGY = 'social.strategies.django_strategy.DjangoStrategy'\n# SOCIAL_AUTH_STORAGE = 'social.apps.django_app.default.models.DjangoStorage'\n# SOCIAL_AUTH_GOOGLE_OAUTH_SCOPE = [\n# 'https://www.googleapis.com/auth/drive',\n# 'https://www.googleapis.com/auth/userinfo.profile'\n# ]\n# # SOCIAL_AUTH_EMAIL_FORM_URL = '/signup-email'\n# SOCIAL_AUTH_EMAIL_FORM_HTML = 'email_signup.html'\n# SOCIAL_AUTH_EMAIL_VALIDATION_FUNCTION = 'app.mail.send_validation'\n# SOCIAL_AUTH_EMAIL_VALIDATION_URL = '/email-sent/'\n# # SOCIAL_AUTH_USERNAME_FORM_URL = '/signup-username'\n# SOCIAL_AUTH_USERNAME_FORM_HTML = 'username_signup.html'\n#\n#\n# SOCIAL_AUTH_PIPELINE = (\n# 'social.pipeline.social_auth.social_details',\n# 'social.pipeline.social_auth.social_uid',\n# 'social.pipeline.social_auth.auth_allowed',\n# 'social.pipeline.social_auth.social_user',\n# 'social.pipeline.user.get_username',\n# 'app.pipeline.require_email',\n# 'social.pipeline.mail.mail_validation',\n# 'social.pipeline.user.create_user',\n# 'social.pipeline.social_auth.associate_user',\n# 'social.pipeline.debug.debug',\n# 'social.pipeline.social_auth.load_extra_data',\n# 'social.pipeline.user.user_details',\n# 'social.pipeline.debug.debug'\n# )\n\n\n#------------- callpug\nCALLPUG_APP_URL=config.get('callpug_app','CALLPUG_APP_URL')\nCALLPUG_PAGESIZE = 20\nCALLPUG_CALL_PRICE = float(config.get('callpug_app','CALLPUG_CALL_PRICE'))\nCALLPUG_DEFAULT_TZ='US/Pacific'\nCALLPUG_APP_ENV=config.get('callpug_app','CALLPUG_APP_ENV')\nCALLPUG_VERSION=config.get('callpug_app','CALLPUG_VERSION')\nCALLPUG_STATE=config.get('callpug_app','CALLPUG_STATE')\n\n#------------- github\nGITHUB_API_KEY=config.get('github','GITHUB_API_KEY')\n\n#------------- twilio\nTWILIO_ACCOUNT_SID = config.get('twilio','TWILIO_ACCOUNT_SID')\nTWILIO_AUTH_TOKEN = config.get('twilio','TWILIO_AUTH_TOKEN')\nTWILIO_ORIGINATING_NO = config.get('twilio','TWILIO_ORIGINATING_NO')\n\n#------------- mixpanel\nMIXPANEL_TOKEN = config.get('mixpanel','MIXPANEL_TOKEN')\n\n#------------- pushover\nPUSHOVER_APP_TOKEN = config.get('pushover','PUSHOVER_APP_TOKEN')\nPUSHOVER_USER = config.get('pushover','PUSHOVER_USER')\n\n#is this used?\nTWILIO_APP_SID = config.get('twilio','TWILIO_APP_SID')\n\n#is this used?\nTWILIO_APP_NAME = config.get('twilio','TWILIO_APP_NAME')\n\nMAILCHIMP_CLIENT_ID = config.get('mailchimp','MAILCHIMP_CLIENT_ID')\nMAILCHIMP_CLIENT_SECRET = config.get('mailchimp','MAILCHIMP_CLIENT_SECRET')\nMAILCHIMP_REDIRECT_URI = config.get('mailchimp','MAILCHIMP_REDIRECT_URI')\nMAILCHIMP_API_KEY = config.get('mailchimp','MAILCHIMP_API_KEY')\nMAILCHIMP_LIST_100_FRIENDS = config.get('mailchimp','MAILCHIMP_LIST_100_FRIENDS')\nMAILCHIMP_CLIENT_DC = config.get('mailchimp','MAILCHIMP_CLIENT_DC')\nMAILCHIMP_CALLPUG_UID = config.get('mailchimp','MAILCHIMP_CALLPUG_UID')\nMAILCHIMP_LIST_WEBSUBSCRIBE = config.get('mailchimp','MAILCHIMP_LIST_WEBSUBSCRIBE')","sub_path":"callpug/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":8638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"602343691","text":"# Copyright 2020 The DDSP Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint as: python3\n\"\"\"Library of performance metrics relevant to DDSP training.\"\"\"\n\nfrom absl import logging\nimport ddsp\nimport librosa\nimport numpy as np\nimport tensorflow.compat.v2 as tf\n\n# Global values for evaluation.\nMIN_F0_CONFIDENCE = 0.85\nOUTLIER_MIDI_THRESH = 12\n\n\n\n# ---------------------- Helper Functions --------------------------------------\ndef squeeze(input_vector):\n \"\"\"Ensure vector only has one axis of dimensionality.\"\"\"\n if input_vector.ndim > 1:\n return np.squeeze(input_vector)\n else:\n return input_vector\n\n\ndef l1_distance(prediction, ground_truth):\n \"\"\"Average L1 distance difference between two 1-D vectors.\"\"\"\n prediction, ground_truth = np.squeeze(prediction), np.squeeze(ground_truth)\n min_length = min(prediction.size, ground_truth.size)\n diff = prediction[:min_length] - ground_truth[:min_length]\n return np.abs(diff)\n\n\ndef is_outlier(ground_truth_f0_conf):\n \"\"\"Determine if ground truth f0 for audio sample is an outlier.\"\"\"\n ground_truth_f0_conf = squeeze(ground_truth_f0_conf)\n return np.max(ground_truth_f0_conf) < MIN_F0_CONFIDENCE\n\n\ndef compute_audio_features(audio,\n n_fft=2048,\n sample_rate=16000,\n frame_rate=250):\n \"\"\"Compute features from audio.\"\"\"\n audio_feats = {'audio': audio}\n audio = squeeze(audio)\n\n audio_feats['loudness_db'] = ddsp.spectral_ops.compute_loudness(\n audio, sample_rate, frame_rate, n_fft)\n\n audio_feats['f0_hz'], audio_feats['f0_confidence'] = (\n ddsp.spectral_ops.compute_f0(audio, sample_rate, frame_rate))\n\n return audio_feats\n\n\ndef f0_dist_conf_thresh(f0_hz,\n f0_hz_gen,\n f0_confidence,\n f0_confidence_thresh=MIN_F0_CONFIDENCE):\n \"\"\"Compute L1 between gen audio and ground truth audio.\n\n Calculating F0 distance is more complicated than calculating loudness\n distance because of inherent inaccuracies in pitch tracking.\n\n We take the following steps:\n - Define a `keep_mask` that only select f0 values above when f0_confidence in\n the GENERATED AUDIO (not ground truth) exceeds a minimum threshold.\n Experimentation by jessengel@ and hanoih@ found this to be optimal way to\n filter out bad f0 pitch tracking.\n - Compute `delta_f0` between generated audio and ground truth audio.\n - Only select values in `delta_f0` based on this `keep_mask`\n - Compute mean on this selection\n - At the start of training, audio samples will sound bad and thus have no\n pitch content. If the `f0_confidence` is all below the threshold, we keep a\n count of it. A better performing model will have a smaller count of\n \"untrackable pitch\" samples.\n\n Args:\n f0_hz: Ground truth audio f0 in hertz [MB,:].\n f0_hz_gen: Generated audio f0 in hertz [MB,:].\n f0_confidence: Ground truth audio f0 confidence [MB,:]\n f0_confidence_thresh: Confidence threshold above which f0 metrics will be\n computed\n\n Returns:\n delta_f0_mean: Float or None if entire generated sample had\n f0_confidence below threshold. In units of MIDI (logarithmic frequency).\n \"\"\"\n if len(f0_hz.shape) > 2:\n f0_hz = f0_hz[:, :, 0]\n if len(f0_hz_gen.shape) > 2:\n f0_hz_gen = f0_hz_gen[:, :, 0]\n if len(f0_confidence.shape) > 2:\n f0_confidence = f0_confidence[:, :, 0]\n\n if np.max(f0_confidence) < f0_confidence_thresh:\n # Generated audio is not good enough for reliable pitch tracking.\n return None\n else:\n keep_mask = f0_confidence >= f0_confidence_thresh\n\n # Report mean error in midi space for easier interpretation.\n f0_midi = librosa.core.hz_to_midi(f0_hz)\n f0_midi_gen = librosa.core.hz_to_midi(f0_hz_gen)\n # Set -infs introduced by hz_to_midi to 0.\n f0_midi[f0_midi == -np.inf] = 0\n f0_midi_gen[f0_midi_gen == -np.inf] = 0\n\n delta_f0_midi = l1_distance(f0_midi, f0_midi_gen)\n delta_f0_midi_filt = delta_f0_midi[keep_mask]\n return np.mean(delta_f0_midi_filt)\n\n\n# ---------------------- Metrics -----------------------------------------------\nclass F0LoudnessMetrics(object):\n \"\"\"Helper object for computing f0 and loudness metrics.\"\"\"\n\n def __init__(self, sample_rate):\n self.metrics = {\n 'loudness_db': tf.keras.metrics.Mean('loudness_db'),\n 'f0_encoder': tf.keras.metrics.Mean('f0_encoder'),\n 'f0_crepe': tf.keras.metrics.Mean('f0_crepe'),\n 'f0_crepe_outlier_ratio':\n tf.keras.metrics.Accuracy('f0_crepe_outlier_ratio'),\n }\n self._sample_rate = sample_rate\n\n def update_state(self, batch, audio_gen, f0_hz_predict):\n \"\"\"Update metrics based on a batch of audio.\n\n Args:\n batch: Dictionary of input features.\n audio_gen: Batch of generated audio.\n f0_hz_predict: Batch of encoded f0, same as input f0 if no f0 encoder.\n \"\"\"\n batch_size = int(audio_gen.shape[0])\n # Compute metrics per sample. No batch operations possible.\n for i in range(batch_size):\n # Extract features from generated audio example.\n keys = ['loudness_db', 'f0_hz', 'f0_confidence']\n feats = {k: v[i] for k, v in batch.items() if k in keys}\n feats_gen = compute_audio_features(\n audio_gen[i], sample_rate=self._sample_rate)\n\n # Loudness metric.\n ld_dist = np.mean(l1_distance(feats['loudness_db'],\n feats_gen['loudness_db']))\n self.metrics['loudness_db'].update_state(ld_dist)\n\n # F0 metric.\n if is_outlier(feats['f0_confidence']):\n # Ground truth f0 was unreliable to begin with. Discard.\n f0_crepe_dist = None\n else:\n # Gound truth f0 was reliable, compute f0 distance with generated audio\n f0_crepe_dist = f0_dist_conf_thresh(feats['f0_hz'],\n feats_gen['f0_hz'],\n feats['f0_confidence'])\n\n # Compute distance original f0_hz labels and f0 encoder values.\n # Resample if f0 encoder has different number of time steps.\n f0_encoder = f0_hz_predict[i]\n f0_original = feats['f0_hz']\n if f0_encoder.shape[0] != f0_original.shape[0]:\n f0_encoder = ddsp.core.resample(f0_encoder, f0_original.shape[0])\n f0_encoder_dist = f0_dist_conf_thresh(f0_original,\n f0_encoder,\n feats['f0_confidence'])\n self.metrics['f0_encoder'].update_state(f0_encoder_dist)\n\n if f0_crepe_dist is None or f0_crepe_dist > OUTLIER_MIDI_THRESH:\n # Generated audio had untrackable pitch content or is an outlier.\n self.metrics['f0_crepe_outlier_ratio'].update_state(True, True)\n logging.info('Sample %d has untrackable pitch content', i)\n else:\n # Generated audio had trackable pitch content and is within tolerance\n self.metrics['f0_crepe'].update_state(f0_crepe_dist)\n self.metrics['f0_crepe_outlier_ratio'].update_state(True, False)\n logging.info(\n 'sample {} | ld_dist(db): {:.3f} | f0_crepe_dist(midi): {:.3f} | '\n 'f0_encoder_dist(midi): {:.3f}'.format(\n i, ld_dist, f0_crepe_dist, f0_encoder_dist))\n\n def flush(self, step):\n \"\"\"Add summaries for each metric and reset the state.\"\"\"\n # Start by logging the metrics result.\n logging.info('COMPUTING METRICS COMPLETE. FLUSHING ALL METRICS')\n metrics_str = ' | '.join(\n '{}: {:0.3f}'.format(k, v.result()) for k, v in self.metrics.items())\n logging.info(metrics_str)\n\n for name, metric in self.metrics.items():\n tf.summary.scalar('metrics/{}'.format(name), metric.result(), step)\n metric.reset_states()\n\n ddsp.spectral_ops.reset_crepe() # Reset CREPE global state\n","sub_path":"ddsp/training/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":8321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"344988102","text":"from .simsiam import SimSiam\n# from .simsiam_hua import SimSiam as Simsiamhua\n# from .byol import BYOL\n# from .simclr import SimCLR\nfrom torchvision.models import resnet50, resnet18\nimport torch\nfrom .backbones import *\n\ndef get_backbone(backbone, castrate=True):\n backbone = eval(f\"{backbone}()\")\n\n if castrate:\n backbone.output_dim = backbone.fc.in_features\n backbone.fc = torch.nn.Identity()\n\n return backbone\n\n\ndef get_model(name, backbone, is_cifar=False):\n if name == 'simsiam':\n model = SimSiam(get_backbone(backbone, castrate=False), is_cifar=is_cifar)\n elif name == 'simsiamhua':\n model = Simsiamhua(get_backbone(backbone))\n if is_cifar:\n model.projector.set_layers(2)\n\n else:\n raise NotImplementedError\n return model\n\n\n\n\n\n\n","sub_path":"models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"89926078","text":"## prediction function for the NN based modelimport os\nimport sys\nimport timeit\n\nimport numpy as np\nimport wordToVecConvertor as word2vec\nimport time\n\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\nimport theano\nimport theano.tensor as T\nfrom FFNN import *\n\n# function for the prediction using NN model\ndef predict(classifier, test_x):\n # assuming that classifier object is alreay instantiated with optimal params\n test_model = theano.function(\n inputs=[index],\n outputs=classifier.y_pred(inputs),\n givens={\n x: test_x,\n }\n )\n y_predict = np.zeros([n_out,len(test_x)])\n y_predict[i] = [test_model(i) for i in range(test_x)]\n return y_predict\n \n# function to get the \ndef dummifier(vector):\n return list(vector).index(1)\n \nif __name__ == '__main__':\n n_pos=45 # dimension of POS embeddings\n n_in=551 + n_pos\n n_out = 27\n \n # assuming that the input data is already vectorized word embeddings\n Xt = pickle.load(open('../data/test_data.pkl','rb'))\n Yt = pickle.load(open('../data/test_label.pkl','rb'))\n params = pickle.load(open('../data/optim_params.pkl','rb'))\n \n classifier = FFNN(\n input=params,\n n_in=n_in,\n n_hidden=n_hidden,\n n_out=n_out\n )\n \n Yt_hat = predict(classifier, Xt, paramas)\n \n\n ","sub_path":"src/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"547755773","text":"\n\nN = int(input())\nscores = list(map(int, input().split()))\nanswer, cnt = 0, 0\n\nfor i in range(len(scores)):\n if scores[i] == 1:\n cnt += 1\n answer += cnt\n else: cnt = 0\n\nprint(answer)\n","sub_path":"인프런/q19_점수계산/q19_점수계산.py","file_name":"q19_점수계산.py","file_ext":"py","file_size_in_byte":204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"285542694","text":"\nimport gensim\nimport cPickle\nimport numpy as np\nfrom gensim.scripts.glove2word2vec import glove2word2vec\n\n\n\ndef load_embedding_vectors_glove_gensim(vocabulary, filename):\n '''\n\n :param vocabulary:\n :param filename:\n :return:\n '''\n print(\"loading embedding\")\n\n model = gensim.models.KeyedVectors.load_word2vec_format(filename)\n\n vector_size = model.vector_size\n embedding_vectors = np.random.uniform(-0.25, 0.25, (len(vocabulary), vector_size))\n glove_vocab = list(model.vocab.keys())\n count = 0\n mis_count = 0\n\n\n for word in vocabulary.keys():\n idx = vocabulary.get(word)\n if word in glove_vocab:\n embedding_vectors[idx] = model.wv[word]\n\n count += 1\n else:\n mis_count += 1\n print(\"num of vocab in glove: {}\".format(count))\n print(\"num of vocab not in glove: {}\".format(mis_count))\n return embedding_vectors\n\nif __name__ == '__main__':\n\n # path for tweets preprocessed previously\n loadpath = \"./data/tweet_cleaned.p\"\n\n # path for saving glove file\n embpath = \"./data/tweet_cleaned_200d_glove.p\"\n\n # extract all data from pickle file\n x = cPickle.load(open(loadpath, \"rb\"))\n train, val, test = x[0], x[1], x[2]\n train_lab, val_lab, test_lab = x[6], x[7], x[8]\n wordtoix, ixtoword = x[9], x[10]\n\n #wordtoix, ixtoword = x[6], x[7]\n\n print(\"load data finished\")\n\n # if the glove has not been transformed into word2vec file, please comment out three lines below\n # glove_file = './data/glove_twitter_27B_200d.txt'\n # tmp_file = './data/word2vec_twitter_27B_200d.txt'\n # _ = glove2word2vec(glove_file, tmp_file)\n\n y = load_embedding_vectors_glove_gensim(wordtoix,'./data/word2vec_twitter_27B_200d.txt' )\n cPickle.dump([y.astype(np.float32)], open(embpath, 'wb'))\n\n","sub_path":"glove_generate.py","file_name":"glove_generate.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"178002246","text":"from Indicators.CCI import CCI\nfrom Indicators.Average_Movement import Average_Movement\nfrom Indicators.MA import MA\nfrom Indicators.BB import BB\nfrom Indicators.MAX import High\nfrom Indicators.MIN import Low\n\ndef Feature_Calculate(data,point):\n \"\"\"\n\n :param data:\n :param point:\n :return:\n \"\"\"\n data = MA(data, 5, 0)\n data = MA(data, 5, 1)\n data = MA(data, 10, 0)\n data = MA(data, 10, 1)\n data = MA(data, 20, 0)\n data = MA(data, 20, 1)\n data = MA(data, 50, 0)\n data = MA(data, 50, 1)\n data = MA(data, 100, 0)\n data = MA(data, 100, 1)\n data = CCI(data, 5, 0)\n data = CCI(data, 5, 1)\n data = CCI(data, 10, 0)\n data = CCI(data, 10, 1)\n data = CCI(data, 20, 0)\n data = CCI(data, 20, 1)\n data = CCI(data, 50, 0)\n data = CCI(data, 50, 1)\n data = CCI(data, 100, 0)\n data = CCI(data, 100, 1)\n data=High(data,10)\n data=Low(data,10)\n data=High(data,20)\n data=Low(data,20)\n data=High(data,50)\n data=Low(data,50)\n data=High(data,100)\n data=Low(data,100)\n data=BB(data,10,0)\n data=BB(data,20,0)\n data=BB(data,50,0)\n data=BB(data,100,0)\n data = Average_Movement(data, 1, 0, point)\n data = Average_Movement(data, 3, 0, point)\n data = Average_Movement(data, 5, 0, point)\n data = Average_Movement(data, 10, 0, point)\n data = Average_Movement(data, 50, 0, point)\n data = Average_Movement(data, 100, 0, point)\n return data\n # data.to_csv('D:\\CSV_Data\\EURUSD_1H_FEATURE.CSV', index=None, float_format='%.5f')\n","sub_path":"Feature_Calculate/Feature_Calculate.py","file_name":"Feature_Calculate.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"576647924","text":"from PIL import ImageOps,Image,ImageDraw\n\ndef read_image(filepath):\n return Image.open(filepath)\n\ndef mask_img(img, regions):\n '''\n @param img:\n @param regions: [xq,y2,x2,y2....]\n @return:\n '''\n mask = Image.new('L', (img.size), 0)\n draw = ImageDraw.Draw(mask)\n for region in regions:\n draw.polygon(regions, outline=\"red\", fill='white')\n output = ImageOps.fit(img, img.size, centering=(0, 0))\n output.putalpha(mask)\n output.convert('RGBA')\n top = Image.new(\"RGBA\", img.size)\n top.paste(output, (0, 0))\n result = Image.alpha_composite(mask.convert('RGBA'), top)\n return result\n\n\ndef draw_polygon(image, points):\n '''\n @param image: Image 图片实例\n @param points: [x1,y1,x2,y2....]\n @return:\n '''\n draw_img = ImageDraw.Draw(image)\n draw_img.polygon(points, outline=\"red\")\n\n\ndef draw_polygon(image, points):\n '''\n @param image: Image 图片实例\n @param points: [x1,y1,x2,y2....]\n @return:\n '''\n draw_img = ImageDraw.Draw(image)\n draw_img.rectangle(points, outline=\"red\")","sub_path":"my_image_tools.py","file_name":"my_image_tools.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"414851559","text":"class Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n adjacencyList = defaultdict(list)\n nodeInDegree = {}\n totalEdges = 0\n for destination, source in prerequisites:\n adjacencyList[source].append(destination)\n nodeInDegree[destination] = nodeInDegree.get(destination, 0) + 1\n totalEdges += 1\n zeroInDegreeQueue = deque([node for node in range(numCourses) if node not in nodeInDegree])\n edgesTraversed = 0\n while zeroInDegreeQueue:\n node = zeroInDegreeQueue.popleft()\n for neighbour in adjacencyList[node]:\n nodeInDegree[neighbour] -= 1\n edgesTraversed += 1\n if nodeInDegree[neighbour] == 0:\n zeroInDegreeQueue.append(neighbour)\n return edgesTraversed == totalEdges","sub_path":"LeetCode/Course Schedule.py","file_name":"Course Schedule.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"545853217","text":"import json\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom dash.exceptions import PreventUpdate\nfrom dash.dependencies import Input, Output, State\nfrom ... import app\nfrom ... import database as db\nfrom ...utils import stl_toast\n\n\ndef load_db_json(key, filename='./db.json'):\n '''Read and load databases configuration from JSON file.'''\n with open(filename, 'r') as f:\n text = json.load(f)\n\n return text[key]\n\n\ndef update_db_json(key, dic, filename='./db.json'):\n '''Update db.json file.'''\n\n try: \n with open(filename, 'r') as f:\n text = json.load(f)\n\n # Update dic\n text[key] = dic\n\n # Save file\n with open(filename, 'w') as f:\n json.dump(text, f, indent=4)\n \n return True\n\n except: return False\n\n\ndef db_options(db_dic):\n return html.Div([\n\n dbc.Row([\n\n dbc.Col(dbc.InputGroup([\n dbc.InputGroupAddon(\n 'Host', addon_type='prepend', \n className='input-group-prepend-110'\n ),\n\n dbc.Input(\n value=db_dic['host'], id='config-db-item-host'\n )\n ]), xs=12, sm=12, md=6, lg=6, xl=6),\n\n dbc.Col(dbc.InputGroup([\n dbc.InputGroupAddon(\n 'Schema', addon_type='prepend', \n className='input-group-prepend-110'\n ),\n\n dbc.Input(\n value=db_dic['schema'], id='config-db-item-schema'\n )\n ]), className='breakColLine', xs=12, sm=12, md=6, lg=6, xl=6),\n\n ], className='breakRowLine'),\n\n dbc.Row([\n\n dbc.Col(dbc.InputGroup([\n dbc.InputGroupAddon(\n 'Usuário', addon_type='prepend', \n className='input-group-prepend-110'\n ),\n\n dbc.Input(\n value=db_dic['user'], id='config-db-item-user'\n )\n ]), xs=12, sm=12, md=6, lg=6, xl=6),\n\n dbc.Col(dbc.InputGroup([\n dbc.InputGroupAddon(\n 'Senha', addon_type='prepend', \n className='input-group-prepend-110'\n ),\n\n dbc.Input(\n id='config-db-item-pw',\n value=db_dic['pw'], type='password', \n )\n ]), className='breakColLine', xs=12, sm=12, md=6, lg=6, xl=6),\n\n ], className='breakRowLine'),\n\n dbc.Row([\n\n dbc.Col(dbc.InputGroup([\n dbc.InputGroupAddon(\n 'Engine', addon_type='prepend', \n className='input-group-prepend-110'\n ),\n\n dbc.Select(\n id='config-db-item-engine', value=db_dic['engine'], \n options=[\n dict(label='MySQL', value='MySQL'), \n dict(label='PostgreSQL', value='PostgreSQL')\n ]\n )\n ]), xs=12, sm=12, md=6, lg=6, xl=6)\n ], className='breakRowLine'),\n ])\n\n\nlayout = html.Div([\n # Header\n html.H4('Configurações > Banco de dados'),\n html.Hr(),\n \n # Select options\n dbc.InputGroup([\n dbc.InputGroupAddon(\n \"Banco de dados\", addon_type=\"prepend\"\n ),\n\n dbc.Select(\n id='config-db-drop',\n options=[\n dict(label='Correlacional', value='correlacional'), \n dict(label='Scatex', value='scatex'), \n dict(label='Rádios', value='radios'), \n ]\n ),\n ]),\n html.Hr(),\n \n # Content\n html.Div(id='config-db-content'),\n\n # Buttons\n dbc.Button(\n id='config-db-bt-sav', n_clicks=0, \n className='fas fa-save',\n ),\n dbc.Button(\n id='config-db-bt-exp', n_clicks=0, \n className='fas fa-download', \n disabled=True\n ),\n\n # Buttons tooltips\n dbc.Tooltip(\n 'Exportar backup do banco de dados.', \n target='config-db-bt-exp'\n ),\n dbc.Tooltip(\n 'Salvar alterações.', \n target='config-db-bt-sav'\n ),\n\n # Toast\n dbc.Toast(\n id=\"config-db-toast-sav\", header=\"Banco de dados\",\n is_open=False, dismissable=True,\n children='Atualizado com sucesso!',\n icon='success', duration=3000, \n style=stl_toast,\n ),\n dbc.Toast(\n id=\"config-db-toast-exp\", header=\"Banco de dados\",\n is_open=False, dismissable=True,\n duration=3000, style=stl_toast,\n ),\n])\n\n\n@app.callback(\n Output('config-db-content', 'children'), [\n Input('config-db-drop', 'value')]\n)\ndef show_databases_children(key):\n\n if key is None:\n raise PreventUpdate\n\n return db_options(load_db_json(key))\n\n\n@app.callback(\n Output('config-db-toast-sav', 'is_open'), [\n Input('config-db-bt-sav', 'n_clicks')], [\n State('config-db-drop', 'value'),\n State('config-db-item-user', 'value'),\n State('config-db-item-host', 'value'),\n State('config-db-item-schema', 'value'),\n State('config-db-item-engine', 'value'),\n State('config-db-item-pw', 'value')])\ndef update_macros(n_clicks, key, user, host, schema, engine, pw):\n '''Update db.json file.'''\n\n if n_clicks == 0 or key is None:\n raise PreventUpdate\n \n dic = dict(\n engine=engine, host=host,\n user=user, schema=schema, \n pw=pw\n )\n return update_db_json(key, dic)\n\n\n@app.callback([\n Output('config-db-toast-exp', 'icon'),\n Output('config-db-toast-exp', 'is_open'),\n Output('config-db-toast-exp', 'children')], [\n Input('config-db-bt-exp', 'n_clicks')])\ndef update_macros(n_clicks):\n '''Export database backup file.'''\n\n if n_clicks == 0:\n raise PreventUpdate\n \n return 'danger', True, 'Função ainda não habilitada!'\n","sub_path":"app/layout/config/databases.py","file_name":"databases.py","file_ext":"py","file_size_in_byte":6021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"611203948","text":"################################################################\n# Author : yiorgosynkl (find me in Github: https://github.com/yiorgosynkl)\n# Date created : 20200505\n# Problem link : https://leetcode.com/problems/first-unique-character-in-a-string/\n################################################################\n\nclass Solution: \n def firstUniqChar(self, s: str) -> int:\n unique = {}\n multi = set()\n for idx, ch in enumerate(s):\n if ch not in multi:\n if ch not in unique.keys():\n unique[ch] = idx\n else:\n del unique[ch]\n multi.add(ch)\n return min(unique.values()) if unique else -1\n \n # one liner\n # def firstUniqChar(self, s: str) -> int:\n # return min([s.find(c) for c in string.ascii_lowercase if s.count(c)==1] or [-1])\n \n # quick solution\n# def firstUniqChar(self, s: str) -> int:\n# unique = set([])\n# multi = set([])\n# for ch in s:\n# if ch not in multi:\n# if ch in unique:\n# unique.remove(ch)\n# multi.add(ch)\n# else:\n# unique.add(ch)\n# # print(multi)\n# # print(unique)\n# for idx, ch in enumerate(s):\n# if ch in unique:\n# return idx\n# return -1\n \n ","sub_path":"30_day_challenge_2020_May/387_first_unique_char_day05.py","file_name":"387_first_unique_char_day05.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"28280126","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api\nimport datetime\nfrom odoo.exceptions import UserError, ValidationError\n\nclass SalesReturn(models.TransientModel):\n _name = 'sales.return'\n _description = u'建立退款單'\n\n refund = fields.Selection(selection=[('1', '1.退款金額95%'), ('2', '2.退款金額90%'), ('3', '3.退款金額50%'), ('4', '4.退款金額1/3')], string='退款比例')\n refund_product = fields.Many2many(comodel_name='product.product', string='退費課程')\n specialist = fields.Many2one(comodel_name='res.users', string='承辦專員', default=lambda self: self.env.uid, readonly = True)\n refund_date = fields.Date(string='退款日期')\n remarks = fields.Text(string='退款原因')\n\n def sales_return(self):\n active_ids = self.env.context.get('active_ids')\n order_id = self.env['sale.order'].search([('id', '=', active_ids)])\n r = []\n for line in self.refund_product:\n for row in order_id.order_line:\n if row.product_id.id == line.id:\n row.refund = self.refund\n r.append([0, 0, {\n 'product_id': line.id,\n 'product_price': int(row.price_subtotal),\n 'quantity':int(row.product_uom_qty),\n 'tax_ids':[(6, 0, row.tax_id.ids)],\n 'order_id': order_id.id,\n 'refund': self.refund,\n 'company_id': order_id.company_id.id,\n }])\n self.env['sales.refund'].create({\n 'company_id':order_id.company_id.id,\n 'name':str(datetime.date.today().year) + str(datetime.date.today().month).zfill(2) + str(self.id),\n 'refund':self.refund,\n 'partner_id':order_id.partner_id.id,\n 'order_id': order_id.id,\n 'refund_date':self.refund_date,\n 'remarks':self.remarks,\n 'specialist':self.specialist.id,\n 'state': '1',\n 'refund_product': r\n })\n return {'type': 'ir.actions.act_window_close'}\n\n @api.onchange('refund')\n def onchange_promotions(self):\n list = []\n result = {}\n active_ids = self.env.context.get('active_ids')\n order_id = self.env['sale.order'].search([('id', '=', active_ids)])\n for line in order_id.order_line:\n if not line.refund:\n list.append(line.product_id.id)\n for line in self.refund_product:\n if line.id in list:\n list.remove(line.id)\n result['domain'] = {'refund_product': [('id', 'in', list)]}\n return result","sub_path":"addons_jptip/sale_order_to_invoice/wizard/sales_return.py","file_name":"sales_return.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"383065689","text":"import urllib.request\n\n\ndef downloadhtml(url, user_agent=\"Mozilla/5.0\", trytimes=3):\n\tprint(\"Downloading!\")\n\theaders = {\"User-agent\": user_agent, 'Accept': 'application/json'}\n\trequest = urllib.request.Request(url, headers=headers)\n\ttry:\n\t\thtml = urllib.request.urlopen(request).read()\n\t\thtml = html.decode(\"utf-8\")\n\texcept urllib.request.URLError as e:\n\t\tprint(e.reason)\n\t\thtml = None\n\t\tif trytimes > 0:\n\t\t\tif hasattr(e, 'code') and 500 <= e.code < 600:\n\t\t\t\tdownloadhtml(request, trytimes-1)\n\treturn html\n\n\"\"\"https://www.jianshu.com/search?q=软件工程&page=1&type=note\"\"\"\ndata = bytes(urllib.parse.urlencode({'q': '软件工程', 'page': '1', 'type': 'note', 'order_by': 'default'}), encoding='utf8')\n\nwith open(\"1.html\", \"w\", encoding=\"utf-8\") as file:\n\tprint(downloadhtml(\"https://so.csdn.net/so/search/s.do?q=%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E8%AF%AD%E8%A8%80%E7%9A%84%E5%88%86%E7%B1%BB&t=&o=&s=&l=\"),file=file)","sub_path":"Demo/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"73014170","text":"class Pessoa:\n\n def __init__(self, codigo=12345, nome='Bob Jack', idade='29'):\n print('Construtor Padrão!')\n self.__codigo = codigo\n self.__nome = nome\n self.__idade = idade\n\n\n def exibe(self, imprimir):\n if imprimir == 1:\n print(f'idade: {self.__idade}')\n else:\n print(f'codigo: {self.__codigo} nome: {self.__nome}')\n\n\n\nclass TestaPessoa:\n\n def __init__(self):\n self.__cadastro = Pessoa()\n\n Pessoa.exibe(self.__cadastro, 1)\n\n Pessoa.exibe(self.__cadastro, 2)\n\n\n\nTestaPessoa()\n","sub_path":"Section17_Heranca_e_Polimorfismo/sobrecarga/desafio.py","file_name":"desafio.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"368567376","text":"from infra.system.helpers.artefact_schema_validator import ArtefactSchemaValidator\nimport logging\nfrom infra.system.artefacts.artefacts import (\n\tARTEFACT_GOLANG_PROJECT_DISTRIBUTION_PACKAGES,\n\tARTEFACT_GOLANG_PROJECT_DISTRIBUTION_EXPORTED_API\n)\nfrom infra.system.plugins.gosymbolsextractor.fake_extractor import FakeGoSymbolExtractor\n\n\nclass FakeDistributionGoSymbolExtractor(FakeGoSymbolExtractor):\n\n\tdef __init__(self):\n\t\tself.product = \"\"\n\t\tself.distribution = \"\"\n\t\tself.rpm = \"\"\n\t\tself.build = \"\"\n\t\tFakeGoSymbolExtractor.__init__(self)\n\n\tdef setData(self, data):\n\t\tself.product = \"Fedora\"\n\t\tself.distribution = \"f23\"\n\t\tself.build = \"example-2.2.4-1.fc24\"\n\t\tself.rpm = \"example-devel-2.2.4-1.fc24.noarch.rpm\"\n\t\treturn FakeGoSymbolExtractor.setData(self, data)\n\n\tdef getData(self):\n\t\tif not self.input_validated:\n\t\t\treturn []\n\n\t\tdata = []\n\n\t\tdata.append(self._generateGolangProjectDistributionPackagesArtefact())\n\t\tvalidator = ArtefactSchemaValidator(ARTEFACT_GOLANG_PROJECT_DISTRIBUTION_PACKAGES)\n\t\tif not validator.validate(data[0]):\n\t\t\tlogging.error(\"%s is not valid\" % ARTEFACT_GOLANG_PROJECT_DISTRIBUTION_PACKAGES)\n\t\t\treturn {}\n\n\t\tdata.append(self._generateGolangProjectDistributionExportedAPI())\n\t\tvalidator = ArtefactSchemaValidator(ARTEFACT_GOLANG_PROJECT_DISTRIBUTION_EXPORTED_API)\n\t\tif not validator.validate(data[1]):\n\t\t\tlogging.error(\"%s is not valid\" % ARTEFACT_GOLANG_PROJECT_DISTRIBUTION_EXPORTED_API)\n\t\t\treturn {}\n\n\t\treturn data\n\n\n\tdef _generateGolangProjectDistributionPackagesArtefact(self):\n\t\tartefact = FakeGoSymbolExtractor._generateGolangProjectPackagesArtefact(self)\n\n\t\tartefact[\"product\"] = self.distribution\n\t\tartefact[\"distribution\"] = self.product\n\t\tartefact[\"rpm\"] = self.rpm\n\t\tartefact[\"build\"] = self.build\n\n\t\treturn artefact\n\n\tdef _generateGolangProjectDistributionExportedAPI(self):\n\t\tartefact = FakeGoSymbolExtractor._generateGolangProjectExportedAPI(self)\n\n\t\tartefact[\"product\"] = self.distribution\n\t\tartefact[\"distribution\"] = self.product\n\t\tartefact[\"rpm\"] = self.rpm\n\t\tartefact[\"build\"] = self.build\n\n\t\treturn artefact\n\n\tdef execute(self):\n\t\treturn FakeGoSymbolExtractor.execute(self)\n","sub_path":"system/plugins/distributiongosymbolsextractor/fake_extractor.py","file_name":"fake_extractor.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"346829920","text":"from CvPythonExtensions import *\nimport CvUtil\nimport ScreenInput\nimport CvScreenEnums\ngc = CyGlobalContext()\n\nclass CvPediaTerrain:\n\tdef __init__(self, main):\n\t\tself.iTerrain = -1\n\t\tself.top = main\n\n\tdef interfaceScreen(self, iTerrain):\n\t\tself.iTerrain = iTerrain\n\t\tself.top.deleteAllWidgets()\t\t\t\n\t\tscreen = self.top.getScreen()\n\t\tif not screen.isActive():\n\t\t\tself.top.setPediaCommonWidgets()\n\n\t\tself.H_ICON = 150\n\t\tself.W_MAIN_PANE = (self.top.W_ITEMS_PANE - self.top.W_BORDER)/2\n\t\tself.H_MAIN_PANE = 210\n\t\tself.X_ICON = self.top.X_ITEMS_PANE + 30\n\t\tself.Y_ICON = (self.H_MAIN_PANE - self.H_ICON)/2 + self.top.Y_ITEMS_PANE\n\t\t\n\t\tself.X_STATS_PANE = self.X_ICON + self.H_ICON\n\t\tself.Y_STATS_PANE = self.Y_ICON + self.H_ICON /4\n\t\tself.W_STATS_PANE = self.W_MAIN_PANE - self.H_ICON - self.top.W_BORDER * 2\n\t\tself.H_STATS_PANE = self.H_MAIN_PANE - self.Y_STATS_PANE + self.top.Y_ITEMS_PANE\n\t\t\n\t\tself.X_SPECIAL = self.top.X_ITEMS_PANE + self.W_MAIN_PANE + self.top.W_BORDER\n\t\tself.Y_SPECIAL = self.top.Y_ITEMS_PANE - 20\n\t\tself.H_SPECIAL = self.H_MAIN_PANE + 20\n\t\tself.Y_IMPROVEMENT = self.top.Y_ITEMS_PANE + self.H_MAIN_PANE + 10\n\t\tself.X_FEATURE = self.top.X_ITEMS_PANE + self.W_MAIN_PANE + self.top.W_BORDER\n\t\tself.H_FEATURE = 110\n\t\tself.Y_BONUS = self.Y_IMPROVEMENT + self.H_FEATURE + 10\n\t\tself.Y_HISTORY_PANE = self.Y_BONUS + self.H_FEATURE + 10\n\t\tself.H_HISTORY_PANE = screen.getYResolution() - self.Y_HISTORY_PANE - self.top.Y_ITEMS_PANE\n\n\t\tszHeader = gc.getTerrainInfo(self.iTerrain).getDescription().upper()\n\t\tszHeader = u\"\" + self.top.color4 + CyTranslator().getText(self.top.sTerrainIcon, ()) + szHeader + \" \" + CyTranslator().getText(self.top.sTerrainIcon, ()) + \"\"\n\t\tscreen.setLabel(self.top.getNextWidgetName(), \"Background\", szHeader, CvUtil.FONT_CENTER_JUSTIFY, screen.getXResolution()/2, self.top.Y_TITLE, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)\n\t\t\n\t\tscreen.setText(self.top.getNextWidgetName(), \"Background\", self.top.MENU_TEXT, CvUtil.FONT_CENTER_JUSTIFY, screen.getXResolution()/2, screen.getYResolution() - 42, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_PEDIA_MAIN, self.top.PLATYPEDIA_TERRAIN, -1)\n\t\tscreen.addPanel( self.top.getNextWidgetName(), \"\", \"\", False, False, self.top.X_ITEMS_PANE, self.top.Y_ITEMS_PANE, self.W_MAIN_PANE, self.H_MAIN_PANE, PanelStyles.PANEL_STYLE_BLUE50)\n\t\tscreen.addPanel(self.top.getNextWidgetName(), \"\", \"\", false, false, self.X_ICON, self.Y_ICON, self.H_ICON, self.H_ICON, PanelStyles.PANEL_STYLE_MAIN)\n\t\tscreen.addDDSGFC(self.top.getNextWidgetName(), gc.getTerrainInfo(self.iTerrain).getButton(), self.X_ICON + self.H_ICON/2 - 64/2, self.Y_ICON + self.H_ICON/2 - 64/2, 64, 64, WidgetTypes.WIDGET_GENERAL, -1, -1 )\n\n\t\tself.placeStats()\n\t\tself.placeSpecial()\n\t\tself.placeFeatures()\n\t\tself.placeBonus()\n\t\tself.placeImprovements()\n\t\tself.placeHistory()\n\t\tself.placeLinks(self.top.iLastScreen == CvScreenEnums.PEDIA_UNIT and screen.isActive())\n\t\tself.top.iLastScreen = CvScreenEnums.PEDIA_TERRAIN\n\n\tdef placeHistory(self):\n\t\tscreen = self.top.getScreen()\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addPanel(panelName, CyTranslator().getText(\"TXT_KEY_CIVILOPEDIA_HISTORY\", ()), \"\", True, True, self.top.X_ITEMS_PANE, self.Y_HISTORY_PANE, self.top.W_ITEMS_PANE, self.H_HISTORY_PANE, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\tszText = \"\"\n\t\tsStrategy = gc.getTerrainInfo(self.iTerrain).getStrategy()\n\t\tif len(sStrategy) and sStrategy.find(\"TXT_KEY\") == -1:\n\t\t\tszText += CyTranslator().getText(\"TXT_KEY_CIVILOPEDIA_STRATEGY\", ())\n\t\t\tszText += sStrategy + \"\\n\\n\"\n\t\t\tszText += CyTranslator().getText(\"TXT_KEY_CIVILOPEDIA_BACKGROUND\", ())\n\t\tsPedia = gc.getTerrainInfo(self.iTerrain).getCivilopedia()\n\t\tif sPedia.find(\"TXT_KEY\") == -1:\n\t\t\tszText += sPedia\n\t\tscreen.addMultilineText(self.top.getNextWidgetName(), szText, self.top.X_ITEMS_PANE + 10, self.Y_HISTORY_PANE + 30, self.top.W_ITEMS_PANE - 20, self.H_HISTORY_PANE - 30, WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)\n\n\tdef placeStats(self):\n\t\tscreen = self.top.getScreen()\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addListBoxGFC(panelName, \"\", self.X_STATS_PANE, self.Y_STATS_PANE, self.W_STATS_PANE, self.H_STATS_PANE, TableStyles.TABLE_STYLE_EMPTY)\n\t\tscreen.enableSelect(panelName, False)\n\n\t\tsText = \"\"\n\t\tfor k in xrange(YieldTypes.NUM_YIELD_TYPES):\n\t\t\tiYieldChange = gc.getTerrainInfo(self.iTerrain).getYield(k)\n\t\t\tif iYieldChange != 0:\n\t\t\t\tsText += u\"%+d%c\" % (iYieldChange, gc.getYieldInfo(k).getChar())\n\t\tif len(sText):\n\t\t\tscreen.appendListBoxString(panelName, \"\" + CyTranslator().getText(\"TXT_KEY_PEDIA_YIELDS\", ()) + \": \", WidgetTypes.WIDGET_GENERAL, 0, 0, CvUtil.FONT_LEFT_JUSTIFY)\n\t\t\tscreen.appendListBoxString(panelName, \"\" + sText + \"\", WidgetTypes.WIDGET_GENERAL, 0, 0, CvUtil.FONT_LEFT_JUSTIFY)\n\t\t\n\tdef placeSpecial(self):\n\t\tscreen = self.top.getScreen()\n\t\tscreen.addPanel(self.top.getNextWidgetName(), CyTranslator().getText(\"TXT_KEY_PEDIA_SPECIAL_ABILITIES\", ()), \"\", true, false, self.X_SPECIAL, self.Y_SPECIAL, self.W_MAIN_PANE, self.H_SPECIAL, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\tszSpecialText = CyGameTextMgr().getTerrainHelp(self.iTerrain, True)[1:]\n\t\tscreen.addMultilineText(self.top.getNextWidgetName(), szSpecialText, self.X_SPECIAL +5, self.Y_SPECIAL + 30, self.W_MAIN_PANE - 10, self.H_SPECIAL - 55, WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)\n\n\tdef placeFeatures(self):\n\t\tscreen = self.top.getScreen()\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addPanel( panelName, CyTranslator().getText(\"TXT_KEY_PEDIA_CATEGORY_FEATURE\", ()), \"\", false, true, self.X_FEATURE, self.Y_IMPROVEMENT, self.W_MAIN_PANE, self.H_FEATURE, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\tfor iFeature in xrange(gc.getNumFeatureInfos()):\n\t\t\tFeatureInfo = gc.getFeatureInfo(iFeature)\n\t\t\tif FeatureInfo.isTerrain(self.iTerrain):\n\t\t\t\tscreen.attachImageButton( panelName, \"\", FeatureInfo.getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_FEATURE, iFeature, 1, False )\n\t\t\n\tdef placeBonus(self):\n\t\tscreen = self.top.getScreen()\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addPanel( panelName, CyTranslator().getText(\"TXT_KEY_PEDIA_CATEGORY_BONUS\", ()), \"\", false, true, self.top.X_ITEMS_PANE, self.Y_BONUS, self.top.W_ITEMS_PANE, self.H_FEATURE, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\tfor iBonus in xrange(gc.getNumBonusInfos()):\n\t\t\tBonusInfo = gc.getBonusInfo(iBonus)\n\t\t\tif BonusInfo.isTerrain(self.iTerrain):\n\t\t\t\tscreen.attachImageButton( panelName, \"\", BonusInfo.getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_BONUS, iBonus, 1, False )\n\n\tdef placeImprovements(self):\n\t\tscreen = self.top.getScreen()\n\t\tpanelName = self.top.getNextWidgetName()\n\t\tscreen.addPanel( panelName, CyTranslator().getText(\"TXT_KEY_PEDIA_CATEGORY_IMPROVEMENT\", ()), \"\", false, true, self.top.X_ITEMS_PANE, self.Y_IMPROVEMENT, self.W_MAIN_PANE, self.H_FEATURE, PanelStyles.PANEL_STYLE_BLUE50 )\n\t\tfor iImprovement in xrange(gc.getNumImprovementInfos()):\n\t\t\tImprovementInfo = gc.getImprovementInfo(iImprovement)\n\t\t\tif ImprovementInfo.getTerrainMakesValid(self.iTerrain):\n\t\t\t\tscreen.attachImageButton( panelName, \"\", ImprovementInfo.getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_IMPROVEMENT, iImprovement, 1, False )\n\n\tdef placeLinks(self, bRedraw):\n\t\tscreen = self.top.getScreen()\n\t\tif bRedraw:\n\t\t\tscreen.show(\"PlatyTable\")\n\t\t\treturn\n\t\tscreen.addTableControlGFC(\"PlatyTable\", 1, self.top.X_PANEL, 55, self.top.W_PANEL, screen.getYResolution() - 110, False, False, 24, 24, TableStyles.TABLE_STYLE_STANDARD);\n\t\tscreen.enableSelect(\"PlatyTable\", True)\n\t\tscreen.setTableColumnHeader(\"PlatyTable\", 0, \"\", self.top.W_PANEL)\n\t\tlistSorted = self.top.sortTerrains(self.top.iSortTerrains)\n\t\tself.top.placePediaLinks(listSorted, CyTranslator().getText(self.top.sTerrainIcon, ()), self.iTerrain, WidgetTypes.WIDGET_PEDIA_JUMP_TO_TERRAIN, -1)\n\n\tdef handleInput (self, inputClass):\n\t\treturn 0","sub_path":"Assets/Python/Screens/PlatyPedia/PlatyPediaTerrain.py","file_name":"PlatyPediaTerrain.py","file_ext":"py","file_size_in_byte":7971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607026141","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n__author__ = 'MFC'\n__time__ = '2019-04-14 23:42'\n\nfrom random import random\nfrom time import perf_counter\n\n# 当前抛洒点的总数量\nDARTS = 1000 * 1000\n\n# 在圆内部的点的总数量\nhits = 0.0\n\nstart = perf_counter()\n\n# 对所有点进行抛洒\nfor i in range(1, DARTS+1):\n x,y = random(), random()\n # 看这个点到圆心的距离是否等于1,以此判断点是否落在圆内\n dist = pow(x**2+y**2, 0.5) # 开方\n if dist <= 1.0:\n hits += 1\n\npi = 4 * (hits/DARTS)\nprint(\"圆周率近似值是:{}\".format(pi))\nprint(\"运行时间是: {:.5f}s\".format(perf_counter()-start))","sub_path":"mooc_python/programming/CalPi_v2.py","file_name":"CalPi_v2.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"14714835","text":"\n\n#calss header\nclass _SUCCESSION():\n\tdef __init__(self,): \n\t\tself.name = \"SUCCESSION\"\n\t\tself.definitions = [u'a number of similar events or people that happen, exist, etc. after each other: ', u'happening one after another: ', u'a process in which someone automatically takes an official position or job after someone else: ']\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/_succession.py","file_name":"_succession.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"541778361","text":"\"\"\"\n冒泡排序改进,如果一次循环内没有发生交换,则表示已经排序完成\n\"\"\"\n\n\ndef bubblesort_1(x):\n for i in range(len(x) - 1):\n flag = False\n for j in range(len(x) - i - 1):\n if x[j] > x[j + 1]:\n x[j], x[j + 1] = x[j + 1], x[j]\n flag = True\n if not flag:\n return x\n return x\n\n\nx = [1, 4, 7, 10, 6]\nprint(bubblesort_1(x))","sub_path":"Sorting/d_BubbleSort_1.py","file_name":"d_BubbleSort_1.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"340279301","text":"import os\nimport sys\n\nimport pandas as pd\nfrom d3m import container, utils as d3m_utils\nfrom d3m.exceptions import PrimitiveNotFittedError\nfrom d3m.metadata import params\nfrom d3m.metadata import base as metadata_base, hyperparams\nfrom d3m.primitive_interfaces import base\nfrom d3m.primitive_interfaces.base import Inputs, CallResult, Outputs, Params\nfrom d3m.primitive_interfaces.supervised_learning import SupervisedLearnerPrimitiveBase\n\nimport esrnn\nfrom esrnn.contrib.ESRNN import ESRNN\n\nInputs = container.DataFrame\nOutputs = container.DataFrame\n\n\nclass Hyperparams(hyperparams.Hyperparams):\n pass\n\n\nclass ForecastingESRNNParams(params.Params):\n is_fitted: bool\n\n\nclass ForecastingESRNNHyperparams(hyperparams.Hyperparams):\n max_epochs = hyperparams.UniformInt(\n default=50,\n lower=0,\n upper=sys.maxsize,\n description=\"epochs to do on fit process\",\n semantic_types=[\"http://schema.org/Boolean\",\n \"https://metadata.datadrivendiscovery.org/types/ControlParameter\", ]\n )\n batch_size = hyperparams.UniformInt(\n default=8,\n lower=1,\n upper=10000,\n description=\"The batch size for RNN training\",\n semantic_types=[\"https://metadata.datadrivendiscovery.org/types/ControlParameter\", ]\n )\n learning_rate = hyperparams.Hyperparameter[float](\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n default=1e-3,\n description='Learning rate used during training (fit).'\n )\n seasonality = hyperparams.UniformInt(\n default=30,\n lower=1,\n upper=10000,\n description=\"\", # TODO\n semantic_types=[\"https://metadata.datadrivendiscovery.org/types/ControlParameter\", ]\n )\n input_size = hyperparams.UniformInt(\n default=30,\n lower=1,\n upper=10000,\n description=\"\", # TODO\n semantic_types=[\"https://metadata.datadrivendiscovery.org/types/ControlParameter\", ]\n )\n output_size = hyperparams.UniformInt(\n default=60,\n lower=1,\n upper=10000,\n description=\"\", # TODO\n semantic_types=[\"https://metadata.datadrivendiscovery.org/types/ControlParameter\", ]\n )\n\n\nclass ForecastingESRNNPrimitive(SupervisedLearnerPrimitiveBase[Inputs, Outputs, ForecastingESRNNParams,\n ForecastingESRNNHyperparams]):\n \"\"\"\n Hybrid ES-RNN models for time series forecasting\n \"\"\"\n metadata = metadata_base.PrimitiveMetadata(\n {\n 'id': '098afc89-da5f-4bf4-9298-dcd39406354c',\n 'version': '0.1.0',\n \"name\": \"Hybrid ES-RNN models for time series forecasting\",\n 'description': \"Hybrid ES-RNN models for time series forecasting\",\n 'python_path': 'd3m.primitives.time_series_forecasting.esrnn.RNN',\n 'source': {\n 'name': esrnn.__author__,\n 'uris': ['https://github.com/autonlab/esrnn'],\n 'contact': 'mailto:donghanw@cs.cmu.edu'\n },\n 'installation': [{\n 'type': metadata_base.PrimitiveInstallationType.PIP,\n 'package_uri': 'git+https://github.com/autonlab/esrnn.git@{git_commit}#egg=esrnn'.format(\n git_commit=d3m_utils.current_git_commit(os.path.dirname(__file__)),\n ),\n }],\n 'algorithm_types': [\n metadata_base.PrimitiveAlgorithmType.RECURRENT_NEURAL_NETWORK,\n ],\n 'primitive_family': metadata_base.PrimitiveFamily.TIME_SERIES_FORECASTING,\n },\n )\n\n def __init__(self, *, hyperparams: ForecastingESRNNHyperparams, random_seed: int = 0) -> None:\n super().__init__(hyperparams=hyperparams, random_seed=random_seed)\n\n self._is_fitted = False\n # self._esrnn = ESRNN(logger=self.logger)\n self._esrnn = ESRNN(\n max_epochs=hyperparams['max_epochs'],\n batch_size=hyperparams['batch_size'],\n learning_rate=hyperparams['learning_rate'],\n seasonality=hyperparams['seasonality'],\n input_size=hyperparams['input_size'],\n output_size=hyperparams['output_size']\n )\n self._data = None\n self._integer_time = False\n self._year_column = None\n\n def set_training_data(self, *, inputs: Inputs, outputs: Outputs) -> None:\n data = inputs.horizontal_concat(outputs)\n data = data.copy()\n\n # mark datetime column\n times = data.metadata.list_columns_with_semantic_types(\n (\n \"https://metadata.datadrivendiscovery.org/types/Time\",\n \"http://schema.org/DateTime\",\n )\n )\n if len(times) != 1:\n raise ValueError(\n f\"There are {len(times)} indices marked as datetime values. Please only specify one\"\n )\n self._time_column = list(data)[times[0]]\n\n # if datetime columns are integers, parse as # of days\n if (\n \"http://schema.org/Integer\"\n in inputs.metadata.query_column(times[0])[\"semantic_types\"]\n ):\n self._integer_time = True\n data[self._time_column] = pd.to_datetime(\n data[self._time_column] - 1, unit=\"D\"\n )\n else:\n data[self._time_column] = pd.to_datetime(\n data[self._time_column], unit=\"s\"\n )\n\n # sort by time column\n data = data.sort_values(by=[self._time_column])\n\n # mark key and grp variables\n self.key = data.metadata.get_columns_with_semantic_type(\n \"https://metadata.datadrivendiscovery.org/types/PrimaryKey\"\n )\n\n # mark target variables\n self._targets = data.metadata.list_columns_with_semantic_types(\n (\n \"https://metadata.datadrivendiscovery.org/types/SuggestedTarget\",\n \"https://metadata.datadrivendiscovery.org/types/TrueTarget\",\n \"https://metadata.datadrivendiscovery.org/types/Target\",\n )\n )\n self._target_types = [\n \"i\"\n if \"http://schema.org/Integer\"\n in data.metadata.query_column(t)[\"semantic_types\"]\n else \"c\"\n if \"https://metadata.datadrivendiscovery.org/types/CategoricalData\"\n in data.metadata.query_column(t)[\"semantic_types\"]\n else \"f\"\n for t in self._targets\n ]\n self._targets = [list(data)[t] for t in self._targets]\n\n self.target_column = self._targets[0]\n\n # see if 'GroupingKey' has been marked\n # otherwise fall through to use 'SuggestedGroupingKey'\n grouping_keys = data.metadata.get_columns_with_semantic_type(\n \"https://metadata.datadrivendiscovery.org/types/GroupingKey\"\n )\n suggested_grouping_keys = data.metadata.get_columns_with_semantic_type(\n \"https://metadata.datadrivendiscovery.org/types/SuggestedGroupingKey\"\n )\n if len(grouping_keys) == 0:\n grouping_keys = suggested_grouping_keys\n drop_list = []\n else:\n drop_list = suggested_grouping_keys\n\n grouping_keys_counts = [\n data.iloc[:, key_idx].nunique() for key_idx in grouping_keys\n ]\n grouping_keys = [\n group_key\n for count, group_key in sorted(zip(grouping_keys_counts, grouping_keys))\n ]\n self.filter_idxs = [list(data)[key] for key in grouping_keys]\n\n # drop index\n data.drop(\n columns=[list(data)[i] for i in drop_list + self.key], inplace=True\n )\n\n # check whether no grouping keys are labeled\n if len(grouping_keys) == 0:\n # TODO\n pass\n else:\n # create a column for year\n year_column = 'year'\n count = 0\n while year_column in data.columns:\n year_column = 'year_' + str(count)\n count += count\n\n # create year column and add it to the grouping_keys\n data[year_column] = data[self._time_column].dt.year\n self._year_column = year_column\n self.filter_idxs.append(year_column)\n\n # concatenate columns in `grouping_keys` to unique_id column\n concat = data.loc[:, self.filter_idxs].apply(lambda x: '-'.join([str(v) for v in x]), axis=1)\n concat = pd.concat([concat,\n data[year_column].astype(str),\n data[self._time_column],\n data[self.target_column]],\n axis=1)\n concat.columns = ['unique_id', 'x', 'ds', 'y']\n\n # Series must be complete in the frequency\n concat = ForecastingESRNNPrimitive._ffill_missing_dates_per_serie(concat, 'D')\n\n # remove duplicates\n concat = concat[~ concat[['unique_id', 'ds']].duplicated()]\n\n self._data = concat\n\n def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:\n X_train = self._data[['unique_id', 'ds', 'x']]\n y_train = self._data[['unique_id', 'ds', 'y']]\n self._esrnn.fit(X_train, y_train, self.random_seed)\n self._is_fitted = True\n\n return base.CallResult(None)\n\n def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:\n if not self._is_fitted:\n raise PrimitiveNotFittedError(\"Primitive not fitted.\")\n\n inputs_copy = inputs.copy()\n\n # if datetime columns are integers, parse as # of days\n if self._integer_time:\n inputs_copy[self._time_column] = pd.to_datetime(\n inputs_copy[self._time_column] - 1, unit=\"D\"\n )\n else:\n inputs_copy[self._time_column] = pd.to_datetime(\n inputs_copy[self._time_column], unit=\"s\"\n )\n\n # find marked 'GroupingKey' or 'SuggestedGroupingKey'\n grouping_keys = inputs_copy.metadata.get_columns_with_semantic_type(\n \"https://metadata.datadrivendiscovery.org/types/GroupingKey\"\n )\n suggested_grouping_keys = inputs_copy.metadata.get_columns_with_semantic_type(\n \"https://metadata.datadrivendiscovery.org/types/SuggestedGroupingKey\"\n )\n if len(grouping_keys) == 0:\n grouping_keys = suggested_grouping_keys\n else:\n inputs_copy = inputs_copy.drop(columns=[list(inputs_copy)[i] for i in suggested_grouping_keys])\n\n # check whether no grouping keys are labeled\n if len(grouping_keys) == 0:\n # TODO\n pass\n else:\n # create year column and add it to the grouping_keys\n inputs_copy[self._year_column] = inputs_copy[self._time_column].dt.year\n\n # concatenate columns in `grouping_keys` to unique_id column\n concat = inputs_copy.loc[:, self.filter_idxs].apply(lambda x: '-'.join([str(v) for v in x]), axis=1)\n concat = pd.concat([concat, inputs_copy[self._time_column]], axis=1)\n concat.columns = ['unique_id', 'ds']\n\n X_test = concat[['unique_id', 'ds']]\n\n predictions = self._esrnn.predict(X_test)\n predictions = predictions['y_hat']\n output = container.DataFrame(predictions, generate_metadata=True)\n return base.CallResult(output)\n\n def set_params(self, *, params: Params) -> None:\n self._is_fitted = params['is_fitted']\n\n def get_params(self) -> Params:\n return ForecastingESRNNParams(is_fitted=self._is_fitted)\n\n @staticmethod\n def _ffill_missing_dates_particular_serie(serie, min_date, max_date, freq):\n date_range = pd.date_range(start=min_date, end=max_date, freq=freq)\n unique_id = serie['unique_id'].unique()\n df_balanced = pd.DataFrame({'ds': date_range, 'key': [1] * len(date_range), 'unique_id': unique_id[0]})\n\n # Check balance\n check_balance = df_balanced.groupby(['unique_id']).size().reset_index(name='count')\n assert len(set(check_balance['count'].values)) <= 1\n df_balanced = df_balanced.merge(serie, how=\"left\", on=['unique_id', 'ds'])\n\n df_balanced['y'] = df_balanced['y'].fillna(method='ffill')\n df_balanced['x'] = df_balanced['x'].fillna(method='ffill')\n\n return df_balanced\n\n @staticmethod\n def _ffill_missing_dates_per_serie(df, freq=\"D\", fixed_max_date=None):\n \"\"\"Receives a DataFrame with a date column and forward fills the missing gaps in dates, not filling dates before\n the first appearance of a unique key\n\n Parameters\n ----------\n df: DataFrame\n Input DataFrame\n key: str or list\n Name(s) of the column(s) which make a unique time series\n date_col: str\n Name of the column that contains the time column\n freq: str\n Pandas time frequency standard strings, like \"W-THU\" or \"D\" or \"M\"\n numeric_to_fill: str or list\n Name(s) of the columns with numeric values to fill \"fill_value\" with\n \"\"\"\n if fixed_max_date is None:\n df_max_min_dates = df[['unique_id', 'ds']].groupby('unique_id').agg(['min', 'max']).reset_index()\n else:\n df_max_min_dates = df[['unique_id', 'ds']].groupby('unique_id').agg(['min']).reset_index()\n df_max_min_dates['max'] = fixed_max_date\n\n df_max_min_dates.columns = df_max_min_dates.columns.droplevel()\n df_max_min_dates.columns = ['unique_id', 'min_date', 'max_date']\n\n df_list = []\n for index, row in df_max_min_dates.iterrows():\n df_id = df[df['unique_id'] == row['unique_id']]\n df_id = ForecastingESRNNPrimitive._ffill_missing_dates_particular_serie(df_id, row['min_date'],\n row['max_date'], freq)\n df_list.append(df_id)\n\n df_dates = pd.concat(df_list).reset_index(drop=True).drop('key', axis=1)[['unique_id', 'ds', 'y', 'x']]\n\n return df_dates\n","sub_path":"esrnn/forecasting_esrnn.py","file_name":"forecasting_esrnn.py","file_ext":"py","file_size_in_byte":14173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"46743762","text":"l,h=list(map(int,input().split()))\r\nh=h+1\r\nc,f=0,0\r\n\r\n\r\nif l<=1: #prevents 0,1\r\n l=2\r\n\r\n \r\nfor i in range(l,h):\r\n #code to check prime\r\n j=(i//2)+1 #remember this,reduces half of the loops\r\n for j in range(2,j): #for could be used as if\r\n if i%j==0:\r\n break\r\n else:\r\n c+=1\r\n \r\nprint(c) \r\n \r\n \r\n","sub_path":"prime_inter.py","file_name":"prime_inter.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"60470123","text":"import numpy as np\nfrom sigmoid import sigmoid\ndef aeneunet(input,num_layers,num_weights):\n\tnum_biases=num_layers\n\tx=sigmoid(input)\n\tx=np.append(1,x)\n\ttheta=np.zeros(num_weights+1)##intialize all weights to zeros\n\tL1=(x).dot(np.transpose(theta))\n\ta1=np.sigmoid(L1)\n\treturn a1\n\n\n\n\n\n\n","sub_path":"GPU_machine_basic_code/neunet.py","file_name":"neunet.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"594997056","text":"#!/usr/bin/env python\nimport rospy\nimport sys\nimport os\n\nfrom ackermann_msgs.msg import AckermannDriveStamped\nfrom std_msgs.msg import Float32MultiArray, MultiArrayDimension, MultiArrayLayout\nimport numpy as np\nimport math\n\n# TODO: import ROS msg types and libraries\nLOOKAHEAD = 1.2\nWaypoint_CSV_File_Path = '/home/zach/catkin_ws/src/lab6/waypoints/levine-waypoints.csv'\nOdom_Topic = rospy.get_param(\"/pose_topic\")\nCar_Length = 0.32\n\nclass PurePursuit(object):\n def __init__(self):\n global Waypoint_CSV_File_Path\n global LOOKAHEAD\n global Car_Length\n\n self.L = LOOKAHEAD\n self.car_length = Car_Length\n\n np.set_printoptions(threshold=sys.maxsize)\n self.iter = 0\n\n rospy.Subscriber(\"/pure_pursuit\", Float32MultiArray, self.pose_callback, queue_size=1) #TODO\n \n self.drive_pub = rospy.Publisher('drive', AckermannDriveStamped, queue_size=1)\n\n def FindNavIndex(self, distances, L):\n min_index = np.argmin(distances)\n \n differences = np.subtract(distances,L)\n next_differences = np.roll(differences, -1)\n\n i = min_index\n while 1:\n if i > (len(differences)-1):\n i = 0\n\n if np.sign(differences[i]) != np.sign(next_differences[i]):\n return i\n else:\n i += 1\n\n def FindNavPoint(self, goal_index, magnitudes, waypoints, L):\n if goal_index == len(waypoints)-1:\n next_index = 0\n else:\n next_index = goal_index + 1\n\n mi = 0 \n m1 = magnitudes[goal_index] - L\n m2 = magnitudes[next_index] - L\n x1 = waypoints[goal_index][0]\n x2 = waypoints[next_index][0]\n y1 = waypoints[goal_index][1]\n y2 = waypoints[next_index][1]\n\n xi = np.interp(mi, [m1,m2], [x1, x2])\n yi = np.interp(mi, [m1,m2], [y1, y2])\n\n goal_point = np.asarray([xi,yi])\n return goal_point\n\n def pose_callback(self, wp_msg):\n print(self.iter)\n self.iter += 1\n height = wp_msg.layout.dim[0].size\n width = wp_msg.layout.dim[1].size\n data = np.asarray(wp_msg.data)\n\n self.Waypoints_Master = np.reshape(data, (height, width))\n \n L = self.L\n\n car_length = self.car_length\n waypoints = self.Waypoints_Master[0:, 1:]\n\n car_point = self.Waypoints_Master[-1, 1:]\n angle_z = self.Waypoints_Master[0, 0]\n\n magnitudes = np.asarray([np.linalg.norm(waypoint - car_point) for waypoint in waypoints])\n\n goal_index = self.FindGoalIndex(magnitudes, L)\n\n goal_point = self.FindGoalPoint(goal_index, magnitudes, waypoints, L)\n \n x = (goal_point[0] - car_point[0])*math.cos(angle_z) + (goal_point[1] - car_point[1])*math.sin(angle_z)\n y = -(goal_point[0] - car_point[0])*math.sin(angle_z) + (goal_point[1] - car_point[1])*math.cos(angle_z)\n\n goal_for_car = np.asarray([x, y])\n d = np.linalg.norm(goal_for_car)\n\n turn_radius = (d**2)/(2*(goal_for_car[1]))\n\n steering_angle = math.atan(car_length/turn_radius)\n\n if steering_angle > 0.4189:\n steering_angle = 0.4189\n elif steering_angle < -0.4189:\n steering_angle = -0.4189\n \n speed = 4.85 \n\n self.ack = AckermannDriveStamped()\n self.ack.header.frame_id = 'steer'\n self.ack.drive.steering_angle = steering_angle\n self.ack.drive.speed = speed\n self.ack.header.stamp = rospy.Time.now()\n self.drive_pub.publish(self.ack)\n\n \ndef main():\n rospy.init_node('pure_pursuit_node')\n pp = PurePursuit()\n rate = rospy.Rate(7)\n rate.sleep()\n rospy.spin()\n\nif __name__ == '__main__':\n main()\n","sub_path":"RRT/lab7/scripts/pure_pursuit.py","file_name":"pure_pursuit.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"270818633","text":"def min_parent(root, p0, p1):\n res = None\n\n def get_min_parent(root, p0, p1):\n global res\n if root is None:\n return False\n\n f_v = True if p0 == root or p1 == root else False\n\n f_l_v = get_min_parent(root.left, p0, p1)\n if f_v and f_l_v:\n res = root\n return True\n\n if res is not None:\n return True\n\n f_r_v = get_min_parent(root.right, p0, p1)\n if f_v and f_r_v:\n res = root\n return True\n\n if f_l_v and f_r_v:\n # find min root\n res = root\n\n return f_v or f_l_v or f_r_v\n\n get_min_parent(root, p0, p1)\n return res\n\n\ndef find_min_parent(root, p, q):\n if root is None:\n return 0, None\n val = 0\n if root.val == p:\n val = 1\n if root.val == q:\n val = 2\n left_v, left_node = find_min_parent(root.left, p, q)\n if left_v == 3 and left_node:\n return left_v, left_node\n right_v, right_node = find_min_parent(root.right, p, q)\n if right_v == 3 and right_node:\n return right_v, right_node\n\n if val + left_v == 3 or val + right_v == 3 or left_v + right_v == 3:\n return 3, root\n return max(val, left_v, right_v), None\n\n\nclass Node(object):\n def __init__(self, val, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n def __str__(self):\n return 'node val:' + str(self.val)\n\n\n# 1\n# 2 3\n# 5 8\n\nroot = Node(1, Node(2), Node(3, Node(5), Node(8)))\nv, n = find_min_parent(root, 2, 9)\nif n:\n print(n)\n","sub_path":"classic/parent_node.py","file_name":"parent_node.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"427883667","text":"from flask import abort, send_file\nfrom flask_restful import Resource, reqparse\nfrom werkzeug.datastructures import FileStorage\nimport psycopg2\nfrom datetime import datetime\nimport hashlib\nimport os\nfrom threading import Thread\nfrom src.api import internals\nfrom src.utils import db\n\nINDIR = \"input\"\nOUTDIR = \"output\"\nDB = \"profiling\"\ndb.load_database_config()\n\n\ndef create_if_not_exist(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef get_seq_id(file):\n file.seek(0)\n m = hashlib.sha256()\n m.update(file.read())\n return m.hexdigest()\n\n\nclass UploadListAPI(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('batch_id', type=str, required=True, location='form')\n self.reqparse.add_argument('created', type=lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S'),\n required=True, location='form')\n self.reqparse.add_argument('filename', type=str, required=True, location='form')\n self.reqparse.add_argument('file', type=FileStorage, required=True, location='files')\n super(UploadListAPI, self).__init__()\n\n def get(self):\n sql = \"select seq_id, filename from upload;\"\n results = db.sql_query(sql, database=DB).to_dict(orient=\"records\")\n return results\n\n def post(self):\n data = self.reqparse.parse_args()\n input_dir = os.path.join(INDIR, data['batch_id'])\n create_if_not_exist(input_dir)\n data['file'].save(os.path.join(input_dir, data['filename'] + \".fa\"))\n data[\"created\"] = data[\"created\"].strftime('%Y-%m-%d %H:%M:%S')\n data['seq_id'] = get_seq_id(data['file'])\n\n sql = \"INSERT INTO upload (seq_id,batch_id,created,filename,file) VALUES(%s,%s,%s,%s,%s);\"\n args = (data['seq_id'], data['batch_id'], data[\"created\"], data['filename'],\n psycopg2.Binary(data['file'].read()))\n db.to_sql(sql, args, database=DB)\n data.pop('file', None)\n return data, 201\n\n\nclass UploadAPI(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('seq_id', type=str, location='json')\n self.reqparse.add_argument('batch_id', type=str, location='json')\n super(UploadAPI, self).__init__()\n\n def get(self, id):\n sql = None\n if len(id) == 32:\n sql = \"select seq_id, batch_id, filename from upload where batch_id='{}';\".format(id)\n elif len(id) == 64:\n sql = \"select seq_id, batch_id, filename from upload where seq_id='{}';\".format(id)\n else:\n abort(404)\n\n results = db.sql_query(sql, database=DB).to_dict(orient=\"records\")\n if len(results) != 0:\n return results\n else:\n abort(404)\n\n\nclass ProfilingAPI(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('id', type=str, required=True, location='json')\n self.reqparse.add_argument('database', type=str, required=True, location='json')\n self.reqparse.add_argument('occurrence', type=int, required=True, location='json')\n super(ProfilingAPI, self).__init__()\n\n def get(self, id):\n if len(id) != 32:\n abort(404)\n sql = \"select * from upload where batch_id='{}';\".format(id)\n results = db.sql_query(sql, database=DB).to_dict(orient=\"records\")\n if len(results) == 0:\n abort(404)\n Thread(target=internals.profiling_api, args=(id, \"Salmonella_5k\", 95), daemon=True).start()\n return {\"message\": \"Profiling dataset {}\".format(id)}, 200\n\n\nclass ProfileListAPI(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('id', type=str, required=True, location='form')\n self.reqparse.add_argument('database', type=str, required=True, location='form')\n self.reqparse.add_argument('occurrence', type=int, required=True, location='form')\n self.reqparse.add_argument('file', type=str, required=True, location='files')\n super(ProfileListAPI, self).__init__()\n\n def get(self):\n sql = \"select id, occurrence, database from profile;\"\n results = db.sql_query(sql, database=DB).to_dict(orient=\"records\")\n return results\n\n\nclass ProfileAPI(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('id', type=str, required=True, location='json')\n self.reqparse.add_argument('database', type=str, required=True, location='json')\n self.reqparse.add_argument('occurrence', type=int, required=True, location='json')\n self.reqparse.add_argument('file', type=str, required=True, location='files')\n super(ProfileAPI, self).__init__()\n\n def get(self, id):\n if len(id) != 32:\n abort(404)\n sql = \"select file from profile where id='{}';\".format(id)\n filepath = db.sql_query_filepath(sql, database=\"profiling\")\n if not filepath:\n abort(404)\n return send_file(filepath, mimetype=\"text/tab-separated-values\")\n\n\nclass DendrogramListAPI(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('id', type=str, required=True, location='form')\n self.reqparse.add_argument('png_file', type=str, required=True, location='files')\n self.reqparse.add_argument('pdf_file', type=str, required=True, location='files')\n self.reqparse.add_argument('svg_file', type=str, required=True, location='files')\n self.reqparse.add_argument('newick_file', type=str, required=True, location='files')\n super(DendrogramListAPI, self).__init__()\n\n def get(self):\n sql = \"select id from dendrogram;\"\n results = db.sql_query(sql, database=DB).to_dict(orient=\"records\")\n return results\n\n\nclass DendrogramAPI(Resource):\n def __init__(self):\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('id', type=str, required=True, location='json')\n super(DendrogramAPI, self).__init__()\n\n def get(self, filetype, id):\n if len(id) != 32:\n abort(404)\n sql = \"select {} from dendrogram where id='{}';\".format(filetype + \"_file\", id)\n filepath = db.sql_query_filepath(sql, database=\"profiling\")\n if not filepath:\n abort(404)\n return send_file(filepath)\n","sub_path":"src/api/profiling.py","file_name":"profiling.py","file_ext":"py","file_size_in_byte":6501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"468275017","text":"import numpy as np\n\n\n# Определяем функцию активации\ndef activation(x: np.ndarray) -> np.ndarray:\n \"\"\"\n Функция активации\n :param x: значения весов\n :return: результат применения функции активации\n к каждому входному значению нейрона\n \"\"\"\n return (1 / (1 + np.exp(-x)))\n\n\n# Определяем производную от функции активации\ndef sigma_derivative(x: float):\n return (x * (1 - x))\n\n\nX = np.array([\n [0, 0, 1],\n [0.3, 1, 0],\n [1, 0.3, 0],\n [0.6, 0.2, 1],\n [0.6, 0.2, 1]\n])\n\nY = np.array(\n [[0],\n [1],\n [1],\n [0],\n [1]]\n)\n\nnp.random.seed(4)\n\nW_1_2 = 2 * np.random.random((3, 2)) - 1\nW_2_3 = 2 * np.random.random((2, 2)) - 1\nW_3_4 = 2 * np.random.random((2, 1)) - 1\n\nspeed = 1.1 #\n\nfor jj in range(10000):\n\n l1 = X\n l2 = activation(np.dot(l1, W_1_2))\n l3 = activation(np.dot(l2, W_2_3))\n l4 = activation(np.dot(l3, W_3_4))\n l4_error = Y - l4\n\n if (jj % 100) == 0:\n # print(\"Errors: \", l4_error)\n print(\"Error: \", np.mean(np.abs(l4_error)))\n\n l4_sigma = l4_error * sigma_derivative(l4_error)\n # print(l4_sigma)\n\n l3_error = l4_sigma.dot(W_3_4.T)\n l3_sigma = l3_error * sigma_derivative(l3_error)\n\n # l2_error = l3_sigma.dot(W_2_3.T)\n\n l2_error = l3_sigma.dot(W_2_3.T)\n l2_sigma = l2_error * sigma_derivative(l2_error)\n\n W_3_4 = W_3_4 + speed * l3.T.dot(l4_sigma)\n W_2_3 = W_2_3 + speed * l2.T.dot(l3_sigma)\n W_1_2 = W_1_2 + speed * l1.T.dot(l2_sigma)\n\nX_test = np.array(\n [[0, 0, 0],\n [0, 1, 1],\n [1, 0, 1],\n [1, 1, 0],\n [0.5, 0.5, 0],\n [0.5, 0.5, 1]]\n)\n\nl1 = X_test\nl2 = activation(np.dot(l1, W_1_2))\nl3 = activation(np.dot(l2, W_2_3))\nl4 = activation(np.dot(l2, W_3_4))\n\n# Y_test должен получиться [1, 0, 0, 1, 1, 0]\nY_test = l4\nprint(Y_test)\n","sub_path":"lab4_back_forward/lab4_new_model.py","file_name":"lab4_new_model.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"11418560","text":"from tkinter import *\nimport _thread\nimport time\nimport vision_config\nimport logging\nfrom interact_database_v2 import Database\nfrom object_DL import Person\nSTATUS_INACTIVE = 0\nSTATUS_INPROGRESS = 1\nSTATUS_DONE = 2\nSTATUS = STATUS_INACTIVE\nSTATUS_CONFIRM = 3\nresult = None\nmsg_result = None\n\ndb = Database(vision_config.DB_HOST, vision_config.DB_USER, vision_config.DB_PASSWD, vision_config.DB_NAME)\n# db = None\ndef response_idCode_OK(idCode):\n person = db.getPersonByIdCode(idCode)\n if person is None:\n get_information(idCode)\n else:\n show_information(vision_config.TRANSFER_LEARNING_MSG, person)\n # STATUS = STATUS_DONE\n\ndef response_learning_OK(msg, person):\n global STATUS, result, msg_result\n logging.info(\"{} | person {}\".format(msg, person))\n result = person\n msg_result = msg\n STATUS = STATUS_DONE\n\ndef response_cancel():\n global STATUS\n STATUS = STATUS_INACTIVE\n result = None\n\ndef reset():\n global STATUS\n STATUS = STATUS_INACTIVE\n result = None\n\ndef center(win):\n \"\"\"\n centers a tkinter window\n :param win: the root or Toplevel window to center\n \"\"\"\n win.update_idletasks()\n width = win.winfo_width()\n frm_width = win.winfo_rootx() - win.winfo_x()\n win_width = width + 2 * frm_width\n height = win.winfo_height()\n titlebar_height = win.winfo_rooty() - win.winfo_y()\n win_height = height + titlebar_height + frm_width\n x = win.winfo_screenwidth() // 2 - win_width // 2\n y = win.winfo_screenheight() // 2 - win_height // 2\n win.geometry('{}x{}+{}+{}'.format(width, height, x, y))\n win.deiconify()\n\ndef show_information(msg, person):\n name = person.name\n idCode = person.idcode\n age = person.age\n gender = person.gender\n\n global STATUS\n STATUS = STATUS_CONFIRM\n label = None\n root = Tk()\n root.title(\"Information\")\n # root.geometry(\"500x50+100+100\")\n row = Frame(root)\n width_box = int(len(name)) + 10\n notice = Label(row, text=msg, width=width_box, font=(16), anchor='w')\n notice.pack(side=TOP)\n\n idCode_lb = Label(row, text=\"ID Code: {}\".format(idCode), width=width_box, font=(16), anchor='w')\n idCode_lb.pack(side=TOP)\n\n name_lb = Label(row, text=\"Full Name: {}\".format(name), width=width_box, font=(16), anchor=\"w\")\n name_lb.pack(side = TOP)\n \n age_lb = Label(row, text=\"Age: {}\".format(age), width=width_box, font=(16), anchor=\"w\")\n age_lb.pack(side = TOP)\n\n gender_lb = Label(row, text=\"Gender: {}\".format(gender), width=width_box, font=(16), anchor=\"w\")\n gender_lb.pack(side = TOP)\n\n row.pack(side=TOP, fill=X, padx=5, pady=5)\n check = 0\n\n def call_ok(event=None):\n response_learning_OK(msg, person)\n root.quit()\n root.destroy()\n\n def call_cancel(event=None):\n global STATUS\n STATUS = STATUS_INPROGRESS\n root.quit()\n root.destroy()\n btn_ok = Button(root, text=\"Accept\", width=10, command=call_ok)\n btn_ok.pack(side=LEFT, padx=5, pady=5)\n btn_cancel = Button(root, text=\"Cancel\", width=10, command=call_cancel)\n btn_cancel.pack(side=RIGHT, padx=5, pady=5)\n root.bind('', call_ok)\n root.bind('', call_cancel)\n center(root)\n root.mainloop()\n # root.destroy()\ndef get_information(idCode):\n global STATUS\n STATUS = STATUS_INPROGRESS\n label = None\n root = Tk()\n root.title(\"New Person\")\n # root.geometry(\"500x50+100+100\")\n row = Frame(root)\n idCode_lb = Label(row, text=\"ID Code: {}\".format(idCode), width=min(max(10 + len(str(idCode)), 25), 50), font=(16), anchor='w')\n # e1.grid(row=0, column = 1)\n \n idCode_lb.pack(side=TOP)\n\n name_lb = Label(row, text=\"Full Name\", width=12, font=(16), anchor=\"w\")\n name_lb.pack(side = TOP)\n\n name_txt = Entry(row, width=18, font=16)\n name_txt.pack(side=TOP, expand=YES, fill=X)\n name_txt.focus_set()\n\n age_lb = Label(row, text=\"Age\", width=12, font=(16), anchor=\"w\")\n age_lb.pack(side = TOP)\n\n age_txt = Entry(row, width=18, font=16)\n age_txt.pack(side=TOP, expand=YES, fill=X)\n\n gender_lb = Label(row, text=\"Gender\", width=12, font=(16), anchor=\"w\")\n gender_lb.pack(side = TOP)\n\n gender_txt = Entry(row, width=18, font=16)\n gender_txt.pack(side=TOP, expand=YES, fill=X)\n\n \n row.pack(side=TOP, fill=X, padx=5, pady=5)\n check = 0\n\n def call_ok(event=None):\n if STATUS == STATUS_CONFIRM:\n return\n if len(name_txt.get()) == 0:\n name_txt.focus_set()\n return\n if len(age_txt.get()) == 0:\n age_txt.focus_set()\n return\n if len(gender_txt.get()) == 0:\n gender_txt.focus_set()\n return\n new_person = Person(name=name_txt.get(), age= int(age_txt.get()), gender=gender_txt.get(), idcode=idCode)\n # root.quit()\n show_information(vision_config.NEW_LEARNING_MSG, new_person)\n \n if STATUS == STATUS_DONE:\n root.destroy()\n\n def call_cancel(event=None):\n if STATUS == STATUS_CONFIRM:\n return\n response_cancel()\n root.destroy()\n btn_ok = Button(root, text=\"OK\", width=10, command=call_ok)\n btn_ok.pack(side=LEFT, padx=5, pady=5)\n btn_cancel = Button(root, text=\"Cancel\", width=10, command=call_cancel)\n btn_cancel.pack(side=RIGHT, padx=5, pady=5)\n root.bind('', call_ok)\n root.bind('', call_cancel)\n center(root)\n root.mainloop()\n # root.destroy()\n\n\ndef get_idCode(database):\n global STATUS, label, db\n db = database\n STATUS = STATUS_INPROGRESS\n label = None\n root = Tk()\n root.title(\"Log in\")\n # root.geometry(\"500x50+100+100\")\n row = Frame(root)\n idCode_lb = Label(row, text=\"ID Code\", width=12, font=(16), anchor='w')\n idCode_txt = Entry(row, width=18, font=16)\n # e1.grid(row=0, column = 1)\n \n idCode_lb.pack(side=TOP)\n idCode_txt.pack(side=TOP, expand=YES, fill=X)\n idCode_txt.focus_set()\n\n row.pack(side=TOP, fill=X, padx=5, pady=5)\n check = 0\n\n def call_ok(event=None):\n idCode = idCode_txt.get()\n if not str.isdigit(idCode):\n return\n idCode = int(idCode)\n root.destroy()\n response_idCode_OK(idCode)\n \n\n def call_cancel(event=None):\n response_cancel()\n root.destroy()\n btn_ok = Button(root, text=\"OK\", width=10, command=call_ok)\n btn_ok.pack(side=LEFT, padx=5, pady=5)\n btn_cancel = Button(root, text=\"Cancel\", width=10, command=call_cancel)\n btn_cancel.pack(side=RIGHT, padx=5, pady=5)\n root.bind('', call_ok)\n root.bind('', call_cancel)\n center(root)\n root.mainloop()\n # root.destroy()\nif __name__ ==\"__main__\":\n get_idCode(db)\n# layout_text()","sub_path":"interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":6738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"418567777","text":"import logging\nfrom utility.services import Services\nfrom selenium.webdriver.common.keys import Keys\nfrom data.data_for_event import DataForEvent\n\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',\n level=logging.INFO)\n\n\nclass EventPage:\n def __init__(self, driver):\n self.driver = driver\n self.service = Services(self.driver)\n self.url = \"https://www.atg.party/event\"\n self.title_of_event_txtfield = \"id=title\"\n self.event_textarea = \"xpath=//*[@class='fr-element fr-view']\"\n self.contact_name_field = \"id=contact_name\"\n self.contact_number_field = \"id=contact_number\"\n self.email_field = \"id=email_address\"\n self.venue_field = \"id=venue\"\n self.add_cost_btn = \"id=btn_cost\"\n self.cost_free_btn = \"xpath=//*[@class='title']\"\n self.cost_paid_btn = \"xpath=(//*[@class='title'])[2]\"\n self.single_cost_btn = \"xpath=(//*[@class='title'])[3]\"\n self.multi_cost_btn = \"xpath=(//*[@class='title'])[4]\"\n self.online_btn = \"xpath=(//*[@class='title'])[5]\"\n self.next_btn_in_cost = \"id=nextbtn\"\n self.price_field_single_ticket = \"id=cost\"\n self.category_field1_multi = \"xpath=//*[@name='advanced_opt_category[0]']\"\n self.description_field1_multi= \"xpath=//*[@name='advanced_opt_description[0]']\"\n self.price_field1_multi_ticket = \"id=advanced_opt_cost\"\n self.category_field2_multi = \"xpath=//*[@name='advanced_opt_category[2]']\"\n self.description_field2_multi= \"xpath=//*[@name='advanced_opt_description[2]']\"\n self.price_field2_multi_ticket = \"id=advanced_opt_cost2\"\n self.new_ticket_btn_multi = \"id=btAdd\"\n self.cost_done_btn = \"id=nextbtn\"\n self.start_date_field = \"id=start_dt\"\n self.start_time = \"id=start_tm\"\n self.tags_field = \"id=tag-tokenfield\"\n self.group_field = \"xpath=//*[@class='popover-tag-wrapper']\"\n self.onclick_group_python = \"xpath=//li[@data-value='181']\"\n self.post_btn = \"xpath=//button[text()='Post']\"\n\n def click_post(self):\n self.service.click_element(self.post_btn)\n\n def filldata(self):\n self.driver.get(self.url)\n data = DataForEvent()\n title = self.service.find_element(self.title_of_event_txtfield)\n title.send_keys(data.title)\n text = self.service.find_element(self.event_textarea)\n text.send_keys(data.text)\n contact_name = self.service.find_element(self.contact_name_field)\n contact_name.send_keys(data.name)\n contact_number = self.service.find_element(self.contact_number_field)\n contact_number.send_keys(data.number)\n email = self.service.find_element(self.email_field)\n email.send_keys(data.email)\n venue = self.service.find_element(self.venue_field)\n venue.send_keys(data.venue)\n self.service.click_element(self.start_date_field)\n date = self.service.find_element(self.start_date_field)\n date.send_keys(Keys.RETURN)\n self.service.click_element(self.start_time)\n start_time = self.service.find_element(self.start_time)\n start_time.send_keys(Keys.RETURN)\n tags = self.service.find_element(self.tags_field)\n tags.send_keys(data.tags)\n self.service.click_element(self.group_field)\n self.service.click_element(self.onclick_group_python)\n\n def post_as_free(self):\n self.filldata()\n self.service.click_element(self.add_cost_btn)\n self.service.click_element(self.cost_free_btn)\n self.service.click_element(self.cost_done_btn)\n self.click_post()\n\n def post_as_paid_single_ticket(self):\n self.filldata()\n self.service.click_element(self.add_cost_btn)\n self.service.click_element(self.cost_paid_btn)\n self.service.click_element(self.single_cost_btn)\n price = self.service.find_element(self.price_field_single_ticket)\n data = DataForEvent()\n price.send_keys(data.price_for_single_ticket)\n (self.service.find_element(self.online_btn)).click()\n self.service.click_element(self.cost_done_btn)\n self.click_post()\n\n def post_as_paid_multi_ticket(self):\n self.filldata()\n self.service.click_element(self.add_cost_btn)\n self.service.click_element(self.cost_paid_btn)\n self.service.wait_for_element(self.multi_cost_btn)\n self.service.click_element(self.multi_cost_btn)\n data = DataForEvent()\n price1 = self.service.find_element(self.price_field1_multi_ticket)\n price1.send_keys(data.price_category1)\n cat1 = self.service.find_element(self.category_field1_multi)\n cat1.send_keys(data.multi_category1)\n des1 = self.service.find_element(self.description_field1_multi)\n des1.send_keys(data.description_multi_category1)\n self.service.click_element(self.new_ticket_btn_multi)\n price2 = self.service.find_element(self.price_field2_multi_ticket)\n price2.send_keys(data.price_category2)\n cat2 = self.service.find_element(self.category_field2_multi)\n cat2.send_keys(data.multi_category2)\n des2 = self.service.find_element(self.description_field2_multi)\n des2.send_keys(data.description_multi_category2)\n opt_online=self.service.find_element(self.online_btn)\n self.driver.execute_script(\"arguments[0].click();\", opt_online)\n self.service.click_element(self.cost_done_btn)\n self.click_post()","sub_path":"pages/event_page.py","file_name":"event_page.py","file_ext":"py","file_size_in_byte":5533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172545165","text":"from __future__ import absolute_import, division, print_function\n\nfrom glob import glob\nimport os\nimport procrunner\n\ndef test(dials_regression, run_in_tmpdir):\n images = glob(os.path.join(dials_regression, \"centroid_test_data\", \"centroid*.cbf\"))\n\n result = procrunner.run_process([\n \"dials.find_spots\",\n \"output.datablock=datablock.json\",\n \"output.reflections=spotfinder.pickle\",\n \"output.shoeboxes=True\",\n ] + images)\n assert result['exitcode'] == 0\n assert result['stderr'] == ''\n assert os.path.exists(\"datablock.json\")\n assert os.path.exists(\"spotfinder.pickle\")\n\n result = procrunner.run_process([\n \"dials.find_hot_pixels\",\n \"input.datablock=datablock.json\",\n \"input.reflections=spotfinder.pickle\",\n \"output.mask=hot_mask.pickle\"\n ])\n assert result['exitcode'] == 0\n assert result['stderr'] == ''\n assert os.path.exists(\"hot_mask.pickle\")\n assert \"Found 8 hot pixels\" in result['stdout']\n","sub_path":"test/command_line/test_find_hot_pixels.py","file_name":"test_find_hot_pixels.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"416843009","text":"import requests\r\n\r\n\r\ndef get_wind_direction(deg):\r\n l = ['С ', 'СВ', ' В', 'ЮВ', 'Ю ', 'ЮЗ', ' З', 'СЗ']\r\n for i in range(0, 8):\r\n step = 45.\r\n min = i*step - 45/2.\r\n max = i*step + 45/2.\r\n if i == 0 and deg > 360-45/2.:\r\n deg = deg - 360\r\n if deg >= min and deg <= max:\r\n res = l[i]\r\n break\r\n return res\r\n\r\n\r\ndef request_forecast(s_city):\r\n try:\r\n res = requests.get(\"http://api.openweathermap.org/data/2.5/find\",\r\n params={'q': s_city, 'type': 'like', 'units': 'metric', 'APPID': \"your apiid\"})\r\n data = res.json()\r\n cities = [\"{} ({})\".format(d['name'], d['sys']['country'])\r\n for d in data['list']]\r\n print(\"city:\", cities[0])\r\n city_id = data['list'][0]['id']\r\n except Exception as e:\r\n print(\"Exception (find):\", e)\r\n pass \r\n try:\r\n msd = '_'\r\n res = requests.get(\"http://api.openweathermap.org/data/2.5/forecast\",\r\n params={'id': city_id, 'units': 'metric', 'lang': 'ru', 'APPID': \"your apiid\"})\r\n data = res.json()\r\n print('city:', data['city']['name'], data['city']['country'])\r\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\n for i in data['list']:\r\n msd2 = '\\n'+str(i['dt_txt'])[:16] + \\\r\n ' {0:+3.0f}'.format(i['main']['temp']) + \"°C\"\r\n msd1 = '\\n' + str(\"\"+'{0:2.0f}'.format(i['wind']['speed']) + \" м/c \") + '\\n'+str(\r\n get_wind_direction(i['wind']['deg'])) + \"\\n\" + str(i['weather'][0]['description'])\r\n msd = msd + msd2 + msd1 + '\\n' + '---------' + '\\n'\r\n print(msd) \r\n return msd\r\n except Exception as e:\r\n print(\"Exception (forecast):\", e)\r\n\r\n\r\n#++++++++++++++++++++++++++++++++++++\r\ndef weather(name_city, n):\r\n c_city = name_city\r\n s_city = name_city + ', Ru'\r\n city_id = 0\r\n badtypes_of_weather = ['туман', 'снег', 'дождь', 'снег с дождем',\r\n 'ветер', 'облачно', 'град', 'гроза', 'ливень', 'сильный дождь', 'ураган']\r\n try:\r\n res = requests.get(\"http://api.openweathermap.org/data/2.5/find\",\r\n params={'q': s_city, 'type': 'like', 'units': 'metric', 'APPID': \"your apiid\"})\r\n data = res.json()\r\n cities = [\"{} ({})\".format(d['name'], d['sys']['country'])\r\n for d in data['list']]\r\n print(\"city:\", cities[0])\r\n city_id = data['list'][0]['id']\r\n except Exception as e:\r\n print(\"Exception (find):\", e)\r\n pass \r\n if n == 1:\r\n try:\r\n res = requests.get(\"http://api.openweathermap.org/data/2.5/weather\",\r\n params={'id': city_id, 'units': 'metric', 'lang': 'ru', 'APPID': \"your apiid\"})\r\n data = res.json()\r\n weth = ('Погода в ' + str(c_city) + \" \\n Состояние погоды: \" + str(\r\n data['weather'][0]['description']) + \"\\n Температура(°C): \" + str(data['main']['temp']))\r\n weth1 = ('\\n Скорость ветра(м/с): ' + str(data['wind']['speed']) + '\\n Влажность(%):' + str(\r\n data['main']['humidity']) + '\\n Давление(мм. рт. ст.):' + str(data['main']['pressure']))\r\n w = weth + weth1\r\n if (data['main']['temp']) <= 17 and (data['weather'][0]['description']) in badtypes_of_weather:\r\n a = '\\n Ну, и погодка у тебя в городе((('\r\n elif (data['main']['temp']) >= 17 and (data['weather'][0]['description']) in badtypes_of_weather and (data['weather'][0]['description']) != 'пасмурно':\r\n a = '\\n Плохая погода'\r\n elif (data['main']['temp']) <= 17:\r\n a = '\\n Прохладно, оденься потеплее)'\r\n elif (data['main']['temp']) <= 10:\r\n a = '\\n Холодно у вас((('\r\n elif (data['main']['temp']) >= 17:\r\n a = '\\n Хорошая погодка)))'\r\n return w + a\r\n except Exception as e:\r\n msd = 'Ошибка, попробуй ввести название города на английском, не забудь прописать \"Погода\"'\r\n return msd\r\n elif n == 2:\r\n msd = request_forecast(s_city)\r\n return msd\r\n n = 0\r\n","sub_path":"lower.py","file_name":"lower.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"204993566","text":"from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktLanguageVars\nimport re, string, json\n\nfrom cStringIO import StringIO\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import TextConverter\nfrom pdfminer.layout import LAParams\nfrom pdfminer.pdfpage import PDFPage\n\nimport codecs\n\n\ndef convert(infile, pages=None):\n if not pages:\n pagenums = set()\n else:\n pagenums = set(pages)\n\n output = StringIO()\n manager = PDFResourceManager()\n converter = TextConverter(manager, output, laparams=LAParams())\n interpreter = PDFPageInterpreter(manager, converter)\n\n for page in PDFPage.get_pages(infile, pagenums):\n interpreter.process_page(page)\n # infile.close()\n converter.close()\n text = output.getvalue()\n output.close\n with open(\"phys.text\",'w') as outfile:\n outfile.write(text)\n return text\n\ndef preprocess(phys):\n '''\n :param fname: a text file\n :return: a json of sentences, processed for searchability\n '''\n\n phys = phys.decode('utf-8')\n phys = re.sub('(\\n)+', '. ', phys)\n\n sentence_tokenizer = PunktSentenceTokenizer()\n sentences = sentence_tokenizer.tokenize(phys)\n\n for i in xrange(len(sentences)):\n sentence = unicode(sentences[i])\n sentence = sentence.replace('\\n', ' ')\n sentence = re.sub(' +',' ',sentence)\n sentence = re.sub(r'\\d+', '', sentence)\n sentence = sentence.replace(\"-\",\" \")\n exclude = string.punctuation\n sentence = ''.join(ch for ch in sentence if ch not in exclude)\n sentence = re.sub(' +',' ',sentence)\n sentences[i] = sentence\n # sentences[i] = sentence.encode('utf-8')\n count = 0\n for sentence in sentences:\n if sentence == ' ' or sentence == '':\n sentences.pop(count)\n count +=1\n\n # with open(fname.rstrip('txt')+'json', 'w') as outfile:\n # json.dump(sentences, outfile)\n\n return sentences\n\n# result = convert('document-page100.pdf')\n# preprocess('document-page100.txt')\n","sub_path":"Backend/manhattanproject/annotator/pdf2text.py","file_name":"pdf2text.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202100973","text":"# ! imports detection model\nfrom maskrcnn_benchmark.config import cfg\nfrom predictor import COCODemo # ! helper class, which loads model from config file and\n # perform pre-processing, model prediction and post-processing\nimport cv2\n\nconfig_file = \"e2e_faster_rcnn_X_101_32x8d_FPN_1x_visdrone.yaml\" # !get our network config\n\n# update the config options with the config file\ncfg.merge_from_file(config_file)\n# manual override some options\n#cfg.merge_from_list([\"MODEL.DEVICE\", \"cpu\"])\ncfg.merge_from_list([\"MODEL.WEIGHT\", \"visdrone_model_0360000.pth\"]) # ! get the pretrained weights\n\ncoco_demo = COCODemo(\n cfg,\n min_image_size=800,\n confidence_threshold=0.7,\n)\n# load image and then run prediction\nimage = cv2.imread('visdrone_test_img_0000001_02999_d_0000005.jpg') # ! get an image\npredictions = coco_demo.run_on_opencv_image(image) # ! get the prediction overlayed on the image\n#cv2.imwrite('drone_res.jpg', predictions)\ncv2.imshow('Predictions', predictions)\ncv2.waitKey(0)\n","sub_path":"mileStone1/train/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"92954422","text":"try:\n import urllib\n from urllib.request import Request, urlopen # Python 3\n import gzip\n from bs4 import BeautifulSoup\n import re\n import json\nexcept:\n # from urllib2 import Request, urlopen # Python 2\n print(\"Error\")\n\n\ndef collect(cookie, id_girl):\n data = urllib.parse.urlencode({\n \"class\": \"Girl\",\n \"action\": \"get_salary\",\n \"who\": id_girl\n }).encode(\"utf-8\")\n req = Request(\"https://nutaku.haremheroes.com/ajax.php\")\n req.add_header('Accept', 'application/json, text/javascript, */*; q=0.01')\n req.add_header('Accept-Encoding', 'gzip, deflate')\n req.add_header('Accept-Language', 'en-US,en;q=0.8')\n req.add_header('Content-Length', len(data))\n req.add_header('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')\n req.add_header('Connection', 'keep-alive')\n req.add_header('Host', 'nutaku.haremheroes.com')\n req.add_header('Origin', 'https://nutaku.haremheroes.com')\n req.add_header('Referer', 'https://nutaku.haremheroes.com/shop.html')\n req.add_header('X-Requested-With', 'XMLHttpRequest')\n req.add_header('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')\n req.add_header('Cookie', cookie)\n resp = urlopen(req, data)\n print(resp.read())\n return\n\n\n# cookie = input(\"Cookie: \");\ncookie = '__insp_uid=1067200004; __insp_wid=702324132; __insp_nv=false; __insp_targlpu=aHR0cDovL251dGFrdS5oYXJlbWhlcm9lcy5jb20vaGFyZW0vNQ%3D%3D; __insp_targlpt=SGFyZW0gSGVyb2Vz; __insp_identity=MjA4Nzk5; __insp_norec_sess=true; __insp_slim=1508434220525; __utmz=202145294.1520340041.622.437.utmcsr=pf.nutaku.info|utmccn=(referral)|utmcmd=referral|utmcct=/gadgets/ifr; __utma=202145294.667588660.1493013830.1520340041.1520350114.623; lang=en; HAPBK=web1; HH_SESS_11=2880i1tnoi69s79213n081ehd5'\nprint(cookie)\nreq = Request(\"https://nutaku.haremheroes.com/harem.html\")\nreq.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8')\nreq.add_header('Accept-Encoding', 'gzip, deflate')\nreq.add_header('Accept-Language', 'en-US,en;q=0.8')\nreq.add_header('Connection', 'keep-alive')\nreq.add_header('Host', 'nutaku.haremheroes.com')\nreq.add_header('Referer', 'https://nutaku.haremheroes.com/home.html')\nreq.add_header('Upgrade-Insecure-Requests', '1')\nreq.add_header('User-Agent',\n 'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')\nreq.add_header('Cookie', cookie)\nresp = urlopen(req)\n# content = resp.read()\n# print(content)\ngzipFile = gzip.GzipFile(fileobj=resp)\nhtml = gzipFile.read()\nprint(html)\n\nsoup = BeautifulSoup(html, 'html.parser')\n# print(soup.prettify())\nrs = re.finditer(r'(.*)(new Girl()(.*)();)(.*)',html.decode('utf-8'))\nprint(rs)\nfor item in rs:\n s = item.group(2)[9:-2]\n print(s)\n js = json.loads(s)\n id_girl = js['id_girl']\n pay_in = js['pay_in']\n if pay_in == 0:\n collect(cookie, id_girl)\n","sub_path":"HHBotTool/HHAutoCollect.py","file_name":"HHAutoCollect.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"3491293","text":"# pip install beautifulsoup4 - команда для установки парсера\nimport urllib.request as req\nfrom bs4 import BeautifulSoup\n#gui\nfrom tkinter import *\n#браузер\nimport webbrowser\n\n#Функция для открытия в браузере\ndef linker(href):\n\twebbrowser.open(href)\ndef php(root):\n\tfor widget in root.winfo_children():\n\t\twidget.destroy()\n\tinit(link='hub/php/')\ndef python(root):\n\tfor widget in root.winfo_children():\n\t\twidget.destroy()\n\tinit(link='hub/python/')\ndef java(root):\n\tfor widget in root.winfo_children():\n\t\twidget.destroy()\n\tinit(link='hub/java/')\ndef android(root):\n\tfor widget in root.winfo_children():\n\t\twidget.destroy()\n\tinit(link='hub/android/')\ndef top(root):\n\tfor widget in root.winfo_children():\n\t\twidget.destroy()\n\tinit(link='top/')\ndef refresh(root):\n\tfor widget in root.winfo_children():\n\t\twidget.destroy()\n\tinit()\ndef init(root = Tk(), link= 'all/'):\n\t# получаем html\n\thtml = req.urlopen('http://habrahabr.ru/'+link).read().decode('utf-8')\n\t# инициализируем парсер\n\tsoup = BeautifulSoup(html,\"html.parser\")\n\titems = soup.findAll(attrs={\"class\" : \"post__title_link\"})\n\t#инициализируем интерфейс\n\tfor item in items:\n\t\tButton(root, text=item.text, command= (lambda x = item['href']: linker(x)) ).pack(pady=5)\n\n\t#создаем анонимные функции для передачи параметров в момент нажатия кнопки\n\tref = lambda x = root: refresh(x)\n\ttopB = lambda x = root: top(x)\n\tphpB = lambda x = root: php(x)\n\tpythonB = lambda x = root: python(x)\n\tjavaB = lambda x = root: java(x)\n\tandroidB = lambda x = root: android(x)\n\t\n\tButton(root, text=\"Перезагрузить\", command=ref).pack(side='bottom', pady=2)\n\tButton(root, text=\"Top\", command=topB).pack(side='bottom', pady=2)\n\tButton(root, text=\"java\", command=javaB).pack(side='left', pady=2)\n\tButton(root, text=\"android\", command=androidB).pack(side='left', pady=2)\n\tButton(root, text=\"php\", command=phpB).pack(side='right', pady=2)\n\tButton(root, text=\"python\", command=pythonB).pack(side='right', pady=2)\n\t\ninit()\n\ninput()","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"85513637","text":"import xml.etree.ElementTree as XmlParser\nfrom ComponentsLoader import *\n\n\nclass ComponentsLoaderXml(ComponentsLoader):\n def __init__(self, source):\n ComponentsLoader.__init__(self, source)\n self.prefix = \"\"\n\n def load(self):\n xml_document = XmlParser.parse(self.source)\n xml = xml_document.getroot()\n\n self.prefix = xml.find('prefix').text\n\n for node in xml.iter('component'):\n if node.attrib['enabled'] == 'no':\n continue\n\n path_element = node.find('component_path')\n test_path_element = node.find('component_test_path')\n component_build_cmd_element = node.find('component_build_cmd')\n test_build_cmd_element = node.find('component_test_build_cmd')\n test_binary_element = node.find('component_test_binary')\n\n c = Component()\n c.name = node.attrib['name']\n c.tfsPath = self.join_path(self.prefix, path_element.text)\n c.testTfsPath = test_path_element.text\n c.componentBuildCmd = component_build_cmd_element.text\n c.testBuildCmd = test_build_cmd_element.text\n c.testBinary = test_binary_element.text\n\n dependencies_node = node.find('dependencies')\n if dependencies_node is not None:\n d_list = dependencies_node.findall('dependency')\n for dependency_node in d_list:\n d = Dependency(dependency_node.text)\n c.dependencies.append(Dependency(dependency_node.text))\n\n support_files_node = node.find('support_files')\n if support_files_node is not None:\n s_list = support_files_node.findall('file')\n for file_node in s_list:\n sf = SupportFile(file_node.text)\n sf.path_type = file_node.attrib['path_type']\n c.support_files.append(sf)\n\n self.components_list.append(c)\n\n return True\n\n def join_path(self, left, right):\n if left.endswith(\"/\"):\n left = left[:-1]\n if right.startswith(\"/\"):\n right = right[1:]\n return left + \"/\" + right\n","sub_path":"python-xml-build-script/ComponentsLoaderXml.py","file_name":"ComponentsLoaderXml.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"549926737","text":"import RPi.GPIO as GPIO\n\nfrom .sensor import Sensor\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\nsensores = [\n Sensor(name='productoLLeno', value =0,pin=7),\n Sensor(name='lectorBarcode', value =0,pin=8),\n]\n\nGPIO.setup(sensores[0].pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\nGPIO.setup(sensores[1].pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\n\n# GPIO.output(sensores[0], GPIO.LOW)\n\nclass ReadSensors:\n def __init__(self):\n pass\n\n def readAll(self):\n \"\"\"Read All sensors\n \"\"\"\n try:\n for x in range(len(sensores)): \n if (GPIO.input(sensores[x].pin) == GPIO.LOW):\n sensores[x].changeStatus(0)\n elif (GPIO.input(sensores[x].pin) == GPIO.HIGH):\n sensores[x].changeStatus(1) \n\n return sensores\n\n except KeyboardInterrupt: \n procesa = False\n \n GPIO.cleanup()\n\n def readOne(self,name):\n \"\"\"Read sensor value by name\n\n Args:\n name (str): name of sensor to read\n\n Returns:\n [int]: 0 or 1 if dont exist sensro name return 404\n \"\"\"\n for sensor in sensores:\n if sensor.name == name:\n return sensor.readStatus()\n \n return 404\n\nif __name__ == '__main__':\n readSensors = ReadSensors()\n sensor = readSensors.readAll()\n\n import pdb \n pdb.set_trace()","sub_path":"logicRasp/sensorsLogic/sensorsRead.py","file_name":"sensorsRead.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"470046836","text":"import itertools\nimport numpy as np\nfrom copy import copy, deepcopy\nfrom random import randrange\n\nrev = []\nco = []\naccep = []\nrc = []\ncpu_u = []\nbw_u = []\n\nprint(\"jjjjjjjjjjjj\")\nfor rr in range(1,11): \n print(\"rr = \", rr)\n filename_sub = 'small substrate 10 nodes cap20-40.txt'\n filename_vir = 'small_arbitrary_virtual_1lifetime_nodenum6-12.txt'\n nodenum, cpu_substrate, bw_substrate = read_Inp_substrate(filename_sub)\n VNR_list = read_virtual(filename_vir)\n\n bw_substrate = SN_transform_random_add_links(cpu_substrate, bw_substrate, rr)\n\n Inp1_nodenum = nodenum\n Inp2_nodenum = 0\n\n num_of_timeslots = 100\n total_cpu = sum(cpu_substrate)\n total_bw = sum(sum(bw_substrate))/2\n #print(\"total cpu = \",total_cpu)\n #print(\"total bw = \",total_bw)\n acceptance = 0\n total_cost = 0\n total_revenue = 0\n total_VNR = 0\n node_resource_table = [[] for i in range(len(cpu_substrate))]\n revenue_array = []\n cost_array = []\n acceptance_array = []\n RC_array = []\n cpu_utilization_array = []\n bw_utilization_array = []\n\n #先找出原本substrate network裡的所有link組合\n link_pairs = list(find_all_links(bw_substrate)) \n bw_resource_table = [[] for i in range(len(link_pairs))]\n #print(\"all pairs: \", link_pairs)\n\n\n for time in range(num_of_timeslots):\n #print(\"time = \", time)\n if VNR_list!=[]:\n arr_time = VNR_list[0] \n\n #先檢查是否有資源可以釋出\n for i in range(len(cpu_substrate)): #node resource\n for j in range(0,len(node_resource_table[i]),2):\n if node_resource_table[i][j]==time:\n cpu_substrate[i] = cpu_substrate[i]+ node_resource_table[i][j+1]\n\n for i in range(len(link_pairs)): #link resource\n for j in range(0,len(bw_resource_table[i]),2):\n if bw_resource_table[i][j]==time:\n which_link = link_pairs[i]\n bw_substrate[which_link[0]][which_link[1]] = bw_substrate[which_link[0]][which_link[1]] + bw_resource_table[i][j+1]\n bw_substrate[which_link[1]][which_link[0]] = bw_substrate[which_link[0]][which_link[1]]\n\n #print(\"node_resource_table: \", node_resource_table)\n #print(\"link_resource_table: \", bw_resource_table)\n #print(\"cpu substrate: \", cpu_substrate)\n #print(\"bw substrate: \", bw_substrate)\n\n\n\n\n while arr_time==time: \n #print(\"take a VNR!\")\n [arr_time, life_time, node_num, node_cap, bw_cap] = take_an_arbitrary_virtual(VNR_list, time) #pop one VNR from the VNR_list\n #print(\"arr time: \", arr_time)\n #print(\"life_time: \", life_time)\n #print(\"node_num: \", node_num)\n #print(\"node_cap: \", node_cap)\n #print(\"bw_cap: \", bw_cap)\n total_VNR = total_VNR+1\n #del VNR_list[0:2*node_num+2] #lineVNR\n del VNR_list[0:node_num*node_num+node_num+3]\n #print(\"VNR_list: \",VNR_list)\n\n subnodes = list(range(0,len(cpu_substrate)))\n #virlinks = list(range(0,len(node_cap)-1))\n\n\n SP_budget, SP_best_sol, SP_link_opt = PSO_fast_version(Inp1_nodenum, Inp2_nodenum, cpu_substrate, bw_substrate, node_num, node_cap, bw_cap, 800, 1, 1)\n #print(\"SP budget: \", SP_budget)\n #print(\"SP best sol: \", SP_best_sol)\n #print(\"SP link opt: \", SP_link_opt)\n\n if SP_budget!=100000000 and SP_best_sol!=[]:\n acceptance = acceptance+1\n total_cost = total_cost + SP_budget\n total_revenue = total_revenue + sum(sum(bw_cap))/2\n\n for i in range(len(node_cap)): #紀錄node資源什麼時候可以釋出,並且扣掉node資源\n cpu_substrate[SP_best_sol[i]] = cpu_substrate[SP_best_sol[i]]-node_cap[i] #扣掉substrate node資源\n node_resource_table[SP_best_sol[i]].append(arr_time+life_time)\n node_resource_table[SP_best_sol[i]].append(node_cap[i])\n\n\n #紀錄link資源什麼時候可以釋出,並且扣掉link資源\n r = -1\n for i in range(len(node_cap)):\n for s in range(i+1,len(node_cap)):\n if bw_cap[i][s] != 0:\n r = r+1\n for j in range(len(SP_link_opt[r])-1):\n bw_substrate[SP_link_opt[r][j]][SP_link_opt[r][j+1]] = bw_substrate[SP_link_opt[r][j]][SP_link_opt[r][j+1]] - bw_cap[i][s] #扣掉頻寬資源\n bw_substrate[SP_link_opt[r][j+1]][SP_link_opt[r][j]] = bw_substrate[SP_link_opt[r][j]][SP_link_opt[r][j+1]]\n a = SP_link_opt[r][j]\n b = SP_link_opt[r][j+1]\n if a0:\n RC_array.append(total_revenue/total_cost)\n else:\n RC_array.append(0)\n\n if total_VNR>0:\n acceptance_array.append(acceptance/total_VNR)\n else:\n acceptance_array.append(0)\n #print all information\n\n #print(\"revenue =\", revenue_array[num_of_timeslots-1])\n #print(\"cost =\", cost_array[num_of_timeslots-1])\n #print(\"acceptance ratio =\", acceptance_array[num_of_timeslots-1])\n #print(\"RC ratio = \", RC_array[num_of_timeslots-1])\n #print(\"CPU utilization =\", cpu_utilization_array[num_of_timeslots-1])\n #print(\"BW utilization =\", bw_utilization_array[num_of_timeslots-1])\n \n rev.append(revenue_array[num_of_timeslots-1])\n co.append(cost_array[num_of_timeslots-1])\n accep.append(acceptance_array[num_of_timeslots-1])\n rc.append(RC_array[num_of_timeslots-1])\n cpu_u.append(cpu_utilization_array[num_of_timeslots-1])\n bw_u.append(bw_utilization_array[num_of_timeslots-1])\n\nprint(\"revenue =\", rev)\nprint(\"cost =\", co)\nprint(\"acceptance ratio =\", accep)\nprint(\"RC ratio = \", rc)\nprint(\"CPU utilization =\", cpu_u)\nprint(\"BW utilization =\", bw_u)\n","sub_path":"single InP.py","file_name":"single InP.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"606109268","text":"\nfrom flask import Flask, request, abort\n\n# ---------------------------------創建Line Bot start---------------------------------- #\nfrom linebot import (\n LineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n InvalidSignatureError\n)\nfrom linebot.models import *\n\napp = Flask(__name__)\n\n# Channel Access Token\nline_bot_api = LineBotApi('2DmvpJgdmXcSHowzVSWZVfiF3aqsHskszknRMN7yicHtjlpV64tAEglzv9zzaZDA3NUlyciHlR/hmB/paASDE4rOBRb4tUI8a02iphYx5INjcPHrVmnUQc5x/td5TfPVuxSxWyorQPz4Elx1vp0IyAdB04t89/1O/w1cDnyilFU=')\n# Channel Secret\nhandler = WebhookHandler('7ee8f5c2aa2dc3a9a0dc6e52ed7241a6')\n# ---------------------------------創建Line Bot end----------------------------------- #\n\n# ------------------------------連接Firebase資料庫 start------------------------------- #\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nfrom firebase_admin import storage\n\n# 引用私密金鑰\ncred = credentials.Certificate(\"line--countdown-firebase-adminsdk-e43zw-fd20d58e12.json\")\n\n# 初始化firebase,注意不能重複初始化\nfirebase_admin.initialize_app(credential= cred, options={\"storageBucket\": \"line--countdown.appspot.com\"})\n\n# 初始化firestore\ndb = firestore.client()\nbucket = storage.bucket()\n\n# -------------------------------連接Firebase資料庫 end-------------------------------- #\n\n# --------------------------------引用其他套件 start------------------------------------ #\nimport datetime \n# ---------------------------------引用其他套件 end------------------------------------- #\n\n\n\n\n# 監聽所有來自 /callback 的 Post Request\n# 我們利用 Python 套件 flask 的幫助,告訴 Heorku,只要有人(以這個例子來說,是 LINE 送來資訊)呼叫 \"https://你-APP-的名字.herokuapp.com/callback\" ,就執行下列程式碼\n@app.route(\"/callback\", methods=['POST'])\ndef callback():\n # get X-Line-Signature header value\n signature = request.headers['X-Line-Signature']\n # get request body as text\n body = request.get_data(as_text=True)\n app.logger.info(\"Request body: \" + body)\n\n # 印出event內容\n print(body)\n\n # handle webhook body\n try:\n handler.handle(body, signature)\n except InvalidSignatureError:\n abort(400)\n return 'OK'\n\n\n\ndef sendDefaultMessage(reply_token, text=\"\"):\n msg_to_user = text \n if msg_to_user:\n msg_to_user = msg_to_user + '\\n'\n msg_to_user = msg_to_user + \"上傳照片以加入提醒清單\"\n message = TextSendMessage(text=msg_to_user, quick_reply=QuickReply(items=[\n QuickReplyButton(action=CameraAction(label=\"拍照上傳\")),\n QuickReplyButton(action=CameraRollAction(label=\"從手機上傳\"))\n ]))\n line_bot_api.reply_message(reply_token, message)\n\ndef initUserInfo(user_id):\n doc_ref = db.collection('users').document(user_id)\n\n doc_ref.set({\"status\": \"Standby\"})\n\ndef getUserInfo(user_id):\n doc_ref = db.collection('users').document(user_id)\n\n return doc_ref.get().to_dict()\n\ndef setUserInfo(user_id, docs):\n doc_ref = db.collection('users').document(user_id)\n \n doc_ref.set(docs)\n\ndef setUserStatus(user_id, status=\"default\"):\n docs = getUserInfo(user_id)\n docs['status'] = status\n setUserInfo(user_id, docs)\n\ndef getUserStatus(user_id):\n docs = getUserInfo(user_id)\n return docs['status']\n\ndef getUserImgList(user_id):\n # Get multiple documents from a collection group \n docs = db.collection('users').document(user_id).collection('stocks').stream() \n imgList = []\n # Get 欄位資料 from each document\n for doc in docs:\n doc = doc.to_dict()\n category = doc['category']\n expire_date = doc['expire_date']\n img = doc['file']\n imgList.append({ \"category\" : category,\n \"expire_date\" : expire_date,\n \"file\" : img\n })\n # Sort by expire date!\n imgList.sort(key = lambda s: s['expire_date']) \n return imgList\n\n# 尚未依照時間順序排序content\ndef generateJson(user_id , imgList):\n \n jsonContent = {\n \"type\": \"carousel\",\n \"contents\": []\n }\n\n for item in imgList:\n blob = bucket.blob(user_id + \"/\" + item['file'])\n category = item['category']\n expire_date = item['expire_date']\n # generate url for img\n url = blob.generate_signed_url(datetime.timedelta(seconds=300), method='GET')\n \n aContent = {\n \"type\": \"bubble\",\n \"size\": \"micro\",\n \"hero\": {\n \"type\": \"image\",\n \"size\": \"full\",\n \"aspectRatio\": \"20:13\",\n \"aspectMode\": \"cover\",\n \"url\": \"https://i.imgur.com/Zn1Pwbf.jpg\"\n },\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"spacing\": \"sm\",\n \"contents\": [\n {\n \"type\": \"text\",\n \"text\": \"零食甜點\",\n \"wrap\": True,\n \"weight\": \"bold\",\n \"size\": \"md\"\n },\n {\n \"type\": \"box\",\n \"layout\": \"baseline\",\n \"contents\": [\n {\n \"type\": \"text\",\n \"text\": \"2020-09-20\",\n \"wrap\": True,\n \"weight\": \"bold\",\n \"size\": \"md\",\n \"flex\": 0\n }\n ]\n },\n {\n \"type\": \"text\",\n \"text\": \"即將到期!\",\n \"wrap\": True,\n \"size\": \"sm\",\n \"margin\": \"md\",\n \"color\": \"#ff5551\",\n \"flex\": 0,\n \"weight\": \"bold\"\n }\n ]\n },\n \"footer\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"spacing\": \"sm\",\n \"contents\": [\n {\n \"type\": \"button\",\n \"style\": \"primary\",\n \"action\": {\n \"type\": \"message\",\n \"label\": \"已使用完畢\",\n \"text\": \"done\"\n },\n \"height\": \"sm\"\n },\n {\n \"type\": \"button\",\n \"action\": {\n \"type\": \"message\",\n \"label\": \"一週後提醒我\",\n \"text\": \"一週後\"\n },\n \"height\": \"sm\"\n }\n ]\n },\n \"styles\": {\n \"body\": {\n \"backgroundColor\": \"#D3FFEC\"\n },\n \"footer\": {\n \"backgroundColor\": \"#D3FFEC\"\n }\n }\n }\n \n aContent['hero']['url'] = url\n aContent['body']['contents'][0]['text'] = category\n aContent['body']['contents'][1]['contents'][0]['text'] = expire_date\n \n jsonContent['contents'].append(aContent)\n\n print(url)\n\n return jsonContent\n \n\n \n\n# 問候訊息\n@handler.add(FollowEvent)\ndef handle_follow(event):\n initUserInfo(event.source.user_id)\n text = \"哈囉~!歡迎使用滴答提醒。\\n\\n我可以幫助您記錄容易過期或忘記使用的產品並適時提醒您。\\n\\n您可以使用選單中的「紀錄品項」可以上傳照片,接著只要輸入日期就能成功紀錄。\\n如果您需要查看紀錄的產品與過期日,請點選「查看品項」。\"\n sendDefaultMessage(event.reply_token, text)\n\n@handler.add(PostbackEvent)\ndef handle_postback(event):\n if (getUserStatus(event.source.user_id) == \"wait_for_expire_date\"):\n docs = getUserInfo(event.source.user_id)\n last_image = docs['image just uploaded']\n doc_ref = db.collection('users').document(event.source.user_id).collection('stocks').document(last_image)\n docs = doc_ref.get().to_dict()\n docs['expire_date'] = event.postback.params['date']\n doc_ref.set(docs)\n setUserStatus(event.source.user_id, \"Standby\")\n sendDefaultMessage(event.reply_token, \"有效日期為「\"+event.postback.params['date']+\"」,我會在到期前提醒你ㄉ\")\n\n# 處理文字訊息 TextMessage\n@handler.add(MessageEvent, message=TextMessage)\ndef handle_message(event):\n \n #從Line的event物件抓資料\n userID = event.source.user_id\n message_type = event.message.type\n msg_from_user = event.message.text\n \n msg_to_user = \"\"\n message = \"\"\n items = [\"化妝保養品\",\"生鮮食材\",\"冷凍料理\",\"零食甜點\",\"料理用品\",\"保健食品\",\"醫療藥用品\"]\n match = False\n for item in items:\n if(msg_from_user == item):\n match = True\n break\n\n if(getUserStatus(event.source.user_id) == \"wait_for_select_category\"):\n if(match == True):\n docs = getUserInfo(event.source.user_id)\n last_image = docs['image just uploaded']\n doc_ref = db.collection('users').document(event.source.user_id).collection('stocks').document(last_image)\n doc_ref.set({\"category\": msg_from_user, \"file\": last_image})\n\n msg_to_user = \"已將此物品歸類至「\" + msg_from_user + \"」,請告訴我有效日期。\"\n message = TextSendMessage(text=msg_to_user, quick_reply=QuickReply(items=[\n QuickReplyButton(action=DatetimePickerAction(label=\"選擇日期\", mode=\"date\", data=\"expire_date\"))\n ]))\n line_bot_api.reply_message(event.reply_token, message)\n setUserStatus(event.source.user_id, \"wait_for_expire_date\")\n \n elif(msg_from_user == \"記錄品項\"):\n sendDefaultMessage(event.reply_token)\n\n elif(msg_from_user == \"提醒我\"):\n imgList = getUserImgList(userID)\n content = generateJson(userID , imgList)\n\n message = FlexSendMessage(\n alt_text = \"flex message\",\n contents = content\n ) \n \n line_bot_api.reply_message(event.reply_token, message)\n # 缺少使用完畢的刪除動作\n\n \n# 處理圖片訊息 ImageMessage\n@handler.add(MessageEvent, message=ImageMessage)\ndef handle_img_message(event):\n if getUserStatus(event.source.user_id) == \"Standby\":\n message_content = line_bot_api.get_message_content(event.message.id)\n\n temp_file_path = event.source.user_id\n with open(temp_file_path, 'wb') as fd:\n for chunk in message_content.iter_content():\n fd.write(chunk)\n\n file_name = str(event.timestamp) + \".jpg\"\n saving_path = str(event.source.user_id) + \"/\" + file_name\n blob = bucket.blob(saving_path)\n\n with open(temp_file_path, 'rb') as photo:\n blob.upload_from_file(photo)\n\n import os\n os.remove(temp_file_path)\n \n docs = getUserInfo(event.source.user_id)\n docs['image just uploaded'] = file_name\n setUserInfo(event.source.user_id, docs)\n\n setUserStatus(event.source.user_id, \"wait_for_select_category\")\n\n\n # contents = (寫好的json檔案)\n contents = {\n \"type\": \"carousel\",\n \"contents\": [\n {\n \"type\": \"bubble\",\n \"size\": \"micro\",\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"image\",\n \"size\": \"full\",\n \"action\": { #action定義點下去之後要做什麼動作,這邊是設定message action\n \"type\": \"message\",\n \"label\": \"action\",\n \"text\": \"化妝保養品\"\n },\n \"aspectMode\": \"cover\",\n \"aspectRatio\": \"7.65:10\",\n \"gravity\": \"top\",\n \"url\": \"https://i.imgur.com/n4GTDov.png\"\n }\n ],\n \"paddingAll\": \"0px\"\n }\n },\n {\n \"type\": \"bubble\",\n \"size\": \"micro\",\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"image\",\n \"size\": \"full\",\n \"action\": { #action定義點下去之後要做什麼動作,這邊是設定message action\n \"type\": \"message\",\n \"label\": \"action\",\n \"text\": \"生鮮食材\"\n },\n \"aspectMode\": \"cover\",\n \"aspectRatio\": \"7.65:10\",\n \"gravity\": \"top\",\n \"url\": \"https://i.imgur.com/DfBKjG2.png\"\n }\n ],\n \"paddingAll\": \"0px\"\n }\n },\n {\n \"type\": \"bubble\",\n \"size\": \"micro\",\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"image\",\n \"size\": \"full\",\n \"action\": { #action定義點下去之後要做什麼動作,這邊是設定message action\n \"type\": \"message\",\n \"label\": \"action\",\n \"text\": \"冷凍料理\"\n },\n \"aspectMode\": \"cover\",\n \"aspectRatio\": \"7.65:10\",\n \"gravity\": \"top\",\n \"url\": \"https://i.imgur.com/hO3hYW8.png\"\n }\n ],\n \"paddingAll\": \"0px\"\n }\n },\n {\n \"type\": \"bubble\",\n \"size\": \"micro\",\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"image\",\n \"size\": \"full\",\n \"action\": { #action定義點下去之後要做什麼動作,這邊是設定message action\n \"type\": \"message\",\n \"label\": \"action\",\n \"text\": \"零食甜點\"\n },\n \"aspectMode\": \"cover\",\n \"aspectRatio\": \"7.65:10\",\n \"gravity\": \"top\",\n \"url\": \"https://i.imgur.com/iXJ2LYM.png\"\n }\n ],\n \"paddingAll\": \"0px\"\n }\n },\n {\n \"type\": \"bubble\",\n \"size\": \"micro\",\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"image\",\n \"size\": \"full\",\n \"action\": { #action定義點下去之後要做什麼動作,這邊是設定message action\n \"type\": \"message\",\n \"label\": \"action\",\n \"text\": \"料理用品\"\n },\n \"aspectMode\": \"cover\",\n \"aspectRatio\": \"7.65:10\",\n \"gravity\": \"top\",\n \"url\": \"https://i.imgur.com/6nQMDds.png\"\n }\n ],\n \"paddingAll\": \"0px\"\n }\n },\n {\n \"type\": \"bubble\",\n \"size\": \"micro\",\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"image\",\n \"size\": \"full\",\n \"action\": { #action定義點下去之後要做什麼動作,這邊是設定message action\n \"type\": \"message\",\n \"label\": \"action\",\n \"text\": \"保健食品\"\n },\n \"aspectMode\": \"cover\",\n \"aspectRatio\": \"7.65:10\",\n \"gravity\": \"top\",\n \"url\": \"https://i.imgur.com/karOgVl.png\"\n }\n ],\n \"paddingAll\": \"0px\"\n }\n },\n {\n \"type\": \"bubble\",\n \"size\": \"micro\",\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"image\",\n \"size\": \"full\",\n \"action\": { #action定義點下去之後要做什麼動作,這邊是設定message action\n \"type\": \"message\",\n \"label\": \"action\",\n \"text\": \"醫療藥用品\"\n },\n \"aspectMode\": \"cover\",\n \"aspectRatio\": \"7.65:10\",\n \"gravity\": \"top\",\n \"url\": \"https://i.imgur.com/seM9Ff3.png\"\n }\n ],\n \"paddingAll\": \"0px\"\n }\n }\n ]\n}\n message = FlexSendMessage(\n alt_text = \"flex message\",\n contents = contents\n ) \n \n line_bot_api.reply_message(event.reply_token, message)\n\nimport os\nif __name__ == \"__main__\":\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":16429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"29568538","text":"import csv\nimport directory\n\ndef load(remote_root = 'Default', local_cache_root = ''):\n \"\"\" Return a list that represent all loaded symbols \"\"\"\n\n symbol_list_file = directory.open_prioritized_file(\\\n file_relative_path = 'StockInfo/stock_symbol_list.txt',\\\n remote_root = remote_root, local_cache_root = local_cache_root)\n\n stock_symbol_list = symbol_list_file.read().splitlines()\n \n return stock_symbol_list\n","sub_path":"build/lib/rqalpha/data/dtsk_python_interface/utility/stock_symbol_list.py","file_name":"stock_symbol_list.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"130618742","text":"import pygame # necessaire pour charger les images et les sons\nimport random\nimport math\n\nclass Joueur() : # classe pour créer le vaisseau du joueur\n def __init__(self) :\n self.position = 400\n self.image = pygame.image.load(\"vaisseau.png\")\n self.sens = \"O\"\n self.vitesse = 10\n self.score = 0\n\n def deplacer(self) :\n if (self.sens == \"droite\") and (self.position < 740):\n self.position = self.position + self.vitesse\n elif (self.sens == \"gauche\") and (self.position > 0):\n self.position = self.position - self.vitesse\n \n def tirer(self):\n self.sens = \"O\"\n \n def marquer(self):\n self.score = self.score + 1\n\nclass Balle() :\n def __init__(self, tireur):\n self.tireur = tireur\n self.depart = tireur.position + 16\n self.hauteur = 492\n self.image = pygame.image.load(\"balle.png\")\n self.etat = \"chargee\"\n self.vitesse = 10\n \n def bouger(self):\n if self.etat == \"chargee\":\n self.depart = self.tireur.position + 16\n self.hauteur = 492\n elif self.etat == \"tiree\" :\n self.hauteur = self.hauteur - self.vitesse\n \n if self.hauteur < 0:\n self.etat = \"chargee\"\n \n def toucher(self, vaisseau):\n if (math.fabs(self.hauteur - vaisseau.hauteur) < 40) and (math.fabs(self.depart - vaisseau.depart) < 40):\n self.etat = \"chargee\"\n return True\n \nclass Ennemi():\n NbEnnemis = 20\n \n def __init__(self):\n self.depart = random.randint(1,799)\n self.hauteur = 10\n self.type = random.randint(1,2)\n if (self.type == 1):\n self.image = pygame.image.load(\"invader1.png\")\n self.vitesse = 0.5\n elif (self.type ==2):\n self.image = pygame.image.load(\"invader2.png\")\n self.vitesse = 1\n \n def avancer(self):\n self.hauteur = self.hauteur + self.vitesse\n \n def disparaitre(self):\n self.depart = random.randint(1,700)\n self.hauteur = 10\n self.type = random.randint(1,2)\n if (self.type == 1):\n self.image = pygame.image.load(\"invader1.png\")\n self.vitesse = 1\n elif (self.type ==2):\n self.image = pygame.image.load(\"invader2.png\")\n self.vitesse = 2\n \n ","sub_path":"spaceinvaders/space.py","file_name":"space.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"111962569","text":"'''\r\n\\brief Module which receives DAO messages and calculates source routes.\r\n\r\n\\author Xavi Vilajosana , January 2013.\r\n'''\r\n\r\nimport logging\r\nclass NullHandler(logging.Handler):\r\n def emit(self, record):\r\n pass\r\nlog = logging.getLogger('RPL')\r\nlog.setLevel(logging.ERROR)\r\nlog.addHandler(NullHandler())\r\n\r\nimport threading\r\nfrom openType import typeUtils as u\r\n\r\nclass RPL(object):\r\n \r\n _TARGET_INFORMATION_TYPE = 0x05\r\n _TRANSIT_INFORMATION_TYPE = 0x06\r\n \r\n def __init__(self):\r\n \r\n # local variables\r\n self.dataLock = threading.Lock()\r\n self.parents = {}\r\n \r\n #======================== public ==========================================\r\n \r\n def indicateDAO(self,dao): \r\n '''\r\n \\brief Indicate a new DAO was received.\r\n \r\n This function parses the received packet, and if valid, updates the\r\n information needed to compute source routes.\r\n '''\r\n \r\n # retrieve source and destination\r\n try:\r\n destination = dao[0:8]\r\n source = dao[8:16]\r\n dao = dao[16:]\r\n except IndexError:\r\n log.warning(\"DAO too short ({0} bytes), no space for destination and source\".format(len(dao)))\r\n return\r\n \r\n # log\r\n output = []\r\n output += ['received DAO:']\r\n output += ['- destination : {0}'.format(u.formatAddress(destination))]\r\n output += ['- source : {0}'.format(u.formatAddress(source))]\r\n output += ['- dao : {0}'.format(u.formatBuf(dao))]\r\n output = '\\n'.join(output)\r\n log.debug(output)\r\n \r\n # retrieve DAO header\r\n dao_header = {}\r\n dao_transit_information = {}\r\n dao_target_information = {}\r\n \r\n try:\r\n # IPHC header\r\n dao_header['IPHC_b0'] = dao[0]\r\n dao_header['IPHC_b1'] = dao[1]\r\n dao_header['IPv6_nextHeader'] = dao[2]\r\n dao_header['IPv6_hoplimit'] = dao[3]\r\n dao_header['source_address'] = dao[4:12]\r\n # ICMPv6 header\r\n dao_header['ICMPv6_RPLType'] = dao[12]\r\n dao_header['ICMPv6_Code'] = dao[13]\r\n dao_header['ICMPv6_CheckSum_b0'] = dao[14]\r\n dao_header['ICMPv6_CheckSum_b1'] = dao[15]\r\n # RPL header\r\n dao_header['RPL_InstanceID'] = dao[16]\r\n dao_header['RPL_flags'] = dao[17]\r\n dao_header['RPL_Reserved'] = dao[18]\r\n dao_header['RPL_DAO_Sequence'] = dao[19]\r\n # DODAGID\r\n dao_header['DODAGID'] = dao[20:36]\r\n \r\n dao = dao[36:]\r\n # retrieve transit information header and parents\r\n parents = []\r\n children = []\r\n \r\n while (len(dao)>0): \r\n if (dao[0]==self._TRANSIT_INFORMATION_TYPE): \r\n # transit information option\r\n dao_transit_information['Transit_information_type'] = dao[0]\r\n dao_transit_information['Transit_information_length'] = dao[1]\r\n dao_transit_information['Transit_information_flags'] = dao[2]\r\n dao_transit_information['Transit_information_path_control'] = dao[3]\r\n dao_transit_information['Transit_information_path_sequence'] = dao[4]\r\n dao_transit_information['Transit_information_path_lifetime'] = dao[5]\r\n parents += [dao[6:14]]#address of the parent.\r\n dao=dao[14:]\r\n elif (dao[0]==self._TARGET_INFORMATION_TYPE):\r\n dao_target_information['Target_information_type'] = dao[0]\r\n dao_target_information['Target_information_length'] = dao[1]\r\n dao_target_information['Target_information_flags'] = dao[2]\r\n dao_target_information['Target_information_prefix_length'] = dao[3]\r\n children += [dao[4:12]]#address of the parent.\r\n dao=dao[12:]\r\n else:\r\n log.warning(\"DAO with wrong Option. Neither Transit nor Target. Option is ({0})\".format(dao[0]))\r\n return\r\n except IndexError:\r\n log.warning(\"DAO too short ({0} bytes), no space for DAO header\".format(len(dao)))\r\n return\r\n \r\n # log\r\n output = []\r\n output += ['parents:']\r\n for p in parents:\r\n output += ['- {0}'.format(u.formatAddress(p))]\r\n output = '\\n'.join(output)\r\n log.debug(output)\r\n \r\n \r\n output = []\r\n output += ['children:']\r\n for p in children:\r\n output += ['- {0}'.format(u.formatAddress(p))]\r\n output = '\\n'.join(output)\r\n log.debug(output)\r\n \r\n # if you get here, the DAO was parsed correctly\r\n \r\n # update parents information with parents collected\r\n with self.dataLock:\r\n self.parents.update({tuple(source):parents})\r\n \r\n def getRouteTo(self,destAddr):\r\n '''\r\n \\brief Retrieve the source route to a given mote.\r\n \r\n \\param[in] destAddr The EUI64 address of the final destination.\r\n \r\n \\return The source route, a list of EUI64 address, order from\r\n destination to source.\r\n '''\r\n \r\n sourceRoute = []\r\n with self.dataLock:\r\n try:\r\n self._getRouteTo_internal(destAddr,sourceRoute)\r\n except Exception as err:\r\n log.error(err)\r\n raise\r\n \r\n return sourceRoute\r\n \r\n #======================== private =========================================\r\n \r\n def _getRouteTo_internal(self,destAddr,sourceRoute):\r\n \r\n if not destAddr:\r\n # no more parents\r\n return\r\n \r\n if not self.parents.get(tuple(destAddr)):\r\n # this node does not have a list of parents\r\n return\r\n \r\n # first time add destination address\r\n if destAddr not in sourceRoute:\r\n sourceRoute += [destAddr]\r\n \r\n # pick a parent\r\n parent = self.parents.get(tuple(destAddr))[0]\r\n \r\n # avoid loops\r\n if parent not in sourceRoute:\r\n sourceRoute += [parent]\r\n \r\n # add non empty parents recursively\r\n nextparent = self._getRouteTo_internal(parent,sourceRoute)\r\n \r\n if nextparent:\r\n sourceRoute += [nextparent]\r\n \r\n #======================== helpers =========================================\r\n ","sub_path":"software/openvisualizer/networkState/RPL.py","file_name":"RPL.py","file_ext":"py","file_size_in_byte":7453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"614081666","text":"import os\nfrom setuptools import setup\n\ndef read(fname):\n try:\n with open(os.path.join(os.path.dirname(__file__), fname)) as fh:\n return fh.read()\n except IOError:\n return ''\n\nrequirements = read('requirements.txt').splitlines()\n\nsetup(name='PyEnergyDiagrams',\n version='1.1.0',\n description='Script to construct energy level diagrams',\n url='https://github.com/tyiannak/pyAudioAnalysis',\n author='csera',\n author_email='',\n license='MIT License, 2017',\n packages=['PyEnergyDiagrams'],\n package_data={\n \n },\n zip_safe=False,\n install_requires=requirements,\n )","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"267283091","text":"from django.urls import path\n\nfrom orders import views\n\napp_name = 'orders'\n\nhandler400 = 'orders.views_error.bad_request'\nhandler403 = 'orders.views_error.permission_denied'\nhandler404 = 'orders.views_error.not_found'\nhandler500 = 'orders.views_error.internal_server_error'\n\nurlpatterns = [\n path('', views.IndexView.as_view(), name='index'),\n path('login/', views.login_view, name='login'),\n path('logout/', views.logout_view, name='logout'),\n path('facilities/', views.FacilityListView.as_view(), name='facilities'),\n path('facilities/check', views.check_facility_serial_view, name='facilities-check'),\n path('facilities//', views.FacilityDetailView.as_view(), name='facility'),\n path('facilities//update/', views.FacilityUpdateView.as_view(), name='facility-update'),\n path('facilities//orders/', views.FacilityOrderListView.as_view(), name='facility-orders'),\n path('orders/', views.OrderListView.as_view(), name='orders'),\n path('myorders/', views.MyOrderListView.as_view(), name='myorders'),\n path('orders/change/', views.OrdersForChangeListView.as_view(), name='orders-for-change'),\n path('orders/close/', views.OrdersForCloseListView.as_view(), name='orders-for-close'),\n path('orders//', views.OrderDetailView.as_view(), name='order'),\n path('orders//close/', views.close_order_view, name='order-close'),\n path('orders//items/', views.OrderFacilityItemsListView.as_view(), name='order-items'),\n path('items//update', views.SerialNumberUpdateView.as_view(), name='item-update'),\n path('vendors/', views.VendorListView.as_view(), name='vendors'),\n path('myvendors/', views.MyVendorListView.as_view(), name='myvendors'),\n path('vendors/create/', views.VendorCreateView.as_view(), name='vendor-create'),\n path('vendors/order/', views.VendorsForOrderListView.as_view(), name='vendors-for-order'),\n path('vendors//', views.VendorDetailView.as_view(), name='vendor'),\n path('vendors//update/', views.VendorUpdateView.as_view(), name='vendor-update'),\n path('vendors//emails/create/', views.VendorEmailCreateView.as_view(), name='vendor-email-create'),\n path('vendors//phones/create/', views.VendorPhoneCreateView.as_view(), name='vendor-phone-create'),\n path('vendors//facilities/', views.VendorFacilityListView.as_view(), name='vendor-facilities'),\n path('vendors//facilities/create/', views.FacilityCreateView.as_view(), name='vendor-facility-create'),\n path('vendors//orders/', views.VendorOrdersListView.as_view(), name='vendor-orders'),\n path('vendors//orders/create/', views.OrderCreateView.as_view(), name='vendor-order-create'),\n]\n","sub_path":"orders/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"468959749","text":"from django.urls import path\nfrom . import views\n# app_name=\"users\"\nurlpatterns = [\n path('register/', views.register,name=\"user_register\"),\n path('user_login/',views.user_login,name ='user_login'),\n path('user_logout/',views.user_logout, name='user_logout'),\n path('private/data/',views.private_data,name=\"private_data\"),\n path('private/',views.private,name=\"private\"),\n path(\"private/success/\",views.private_success,name=\"private_success\"),\n path(\"private/raschet/\",views.private_raschet,name=\"private_raschet\"),\n path('private/remove_order//',views.remove_order,name=\"remove_order\"),\n path('private/user_rachet/',views.user_rachet,name=\"user_rachet\"),\n path('edit/',views.edit, name= 'edit'),\n\n\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"620618400","text":"import pandas as pd\nimport numpy as np\nfrom pyxll import xl_macro, xl_app, Formatter, XLCell, xlcAlert, xl_menu\nfrom win32com.client import constants\nfrom dataclasses import dataclass\n\n\n@xl_macro\ndef range_to_df():\n xlcAlert(\"Hello\")\n xl = xl_app()\n\n # tempRange = 'B1'\n # tempRange2 = 'E2'\n # tempRange3 = 'A6:B7'\n # searchRange = 'A1:D4'\n #\n # x = pd.DataFrame({\"A\": ['Jim', 6], \"B\": ['Paula', 8]}, index=None)\n # arr_x = x.to_numpy()\n\n # 'xl' is an instance of the Excel.Application object\n\n # Get the current ActiveSheet (same as in VBA)\n sheet = xl.ActiveSheet\n\n # Call the 'Range' method on the Sheet\n xl_range = sheet.Range(tempRange)\n # xl_range = sheet.Range('A1:I1')\n # xl_range.Merge()\n xl_range.Select()\n # xl_range.FormulaR1C1 = \"Test\"\n xl_range.Formula = \"=$B$2+$C$2\"\n\n xl_range = sheet.Range(tempRange2)\n xl_range.Select()\n xl_range.Formula = \"=MIN(COLUMN(\" + searchRange + \"))+COLUMNS(\" + searchRange + \")-1\"\n\n xl_range = sheet.Range(tempRange3)\n xl_range.Select()\n xl_range.Value = arr_x\n\n\n# make a dataclass with decorator\n@dataclass\nclass DataClassAccount:\n SNAM: str\n acc_cust: int\n\n\n# make an object with values required by dataclass\nDataClassObject = DataClass_Account(\"JLYONS\", 123456)\n\n# view dataclass object\nprint(DataClassObject)","sub_path":"src/pyxll_Macro_Test_2.py","file_name":"pyxll_Macro_Test_2.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"576950858","text":"# 5-10\n\ncurrent_users = ['markfromjoberg', 'ncmbartlett', 'nakedcranium', 'naomiche', 'therealekevin']\nnew_user = input('Please enter your desired username: ')\nnew_user = new_user.lower()\n\nwhile new_user in current_users:\n\tprint('Sorry that username is taken.')\n\tnew_user = input('Please enter another username: ')\n\tnew_user = new_user.lower()\ncurrent_users.append(new_user)\n\nif new_user in current_users:\n\tprint('Username successfully registered.')\nprint('\\r')\nprint(current_users)","sub_path":"Chapter 5/ch5q10.py","file_name":"ch5q10.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"307571585","text":"#!/usr/bin/env python3\n\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\nclass HelloWorld:\n def __init__(self):\n window = Gtk.Window()\n window.connect(\"destroy\", self.close_hello_world)\n\n button = Gtk.Button(\"Click here\")\n button.connect(\"clicked\", self.print_hello_world)\n window.add(button)\n\n window.show_all()\n\n def close_hello_world(self, widget):\n Gtk.main_quit()\n\n def print_hello_world(self, widget):\n print(\"Hello World\")\n\nHelloWorld()\nGtk.main()\n","sub_path":"_examples/gtkmainloop1.py","file_name":"gtkmainloop1.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"252618011","text":"from views.bcolors import Bcolors\n\n\ndef show_sub(submission):\n login = submission.user_login\n title = submission.title\n answer = submission.answer\n date = submission.date\n score = submission.score\n if submission.is_checked:\n print(Bcolors.GREEN + \"\\n{}'s submission for assingment: {}\\n<{}>\\nSent: {}\\nScore: {}\".format(\n login, title, answer, date, score) + Bcolors.ENDC)\n print(Bcolors.BLUE + '\\nIt was already checked by the mentor.\\n' + Bcolors.ENDC)\n else:\n print(Bcolors.RED + \"\\n{}'s submission for assingment: {}\\n<{}>\\nSent: {}\\nScore: {}\".format(\n login, title, answer, date, score) + Bcolors.ENDC)\n print(Bcolors.BLUE + Bcolors.BOLD + '\\nIt wasn\\'t checked by the mentor yet.\\n' + Bcolors.ENDC)\n","sub_path":"views/submission_view.py","file_name":"submission_view.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"54567880","text":"# -*- coding: utf-8 -*-\nimport random\nfrom numpy.random import Generator, MT19937\nimport time\nimport math\nimport cvxpy as cp\nimport numpy.random as nr\nimport io\nimport sys\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import grad\nimport numpy as np\nnp.set_printoptions(threshold=100)\n\n\nclass Back_gradient_poisoner():\n def __init__(self, xtrain, ytrain, xvalid, yvalid, eta, eps, steps, T, dataset_id, termination_cond, specific, multi, epochs, learning_rate, device, spmode, mulmode, decay, centroid, centroid_t, radius, radius_t, s_def, flip, solver, init_point_list=np.array([]), mal_0_id=-1, constraint=0, beta=0.1, step_max=-1, init_seed=0):\n self.nFeatures = xtrain.shape[1]\n self.nClasses = int(torch.max(ytrain)) + 1\n self.point = torch.empty(\n 1, self.nFeatures, device=device)\n self.label = torch.empty(\n 1, dtype=torch.long, device=device)\n self.model = None\n self.criterion = None\n self.dataset_id = dataset_id\n self.w_0 = torch.empty(self.nClasses, self.nFeatures, device=device)\n self.b_0 = torch.empty(self.nClasses, device=device)\n self.dx = torch.empty(1, self.nFeatures, device=device)\n self.dt = torch.empty(self.nClasses, self.nFeatures + 1, device=device)\n self.xtrain = xtrain\n self.ytrain = ytrain\n self.w_indices = torch.tensor(\n list(range(0, self.nFeatures)), device=device)\n self.b_indices = torch.tensor([self.nFeatures], device=device)\n if decay:\n self.eta = torch.tensor(0., device=device)\n self.init_eta = torch.tensor(eta, device=device)\n self.decay = None\n else:\n self.eta = torch.tensor(eta, device=device)\n self.termination_cond = termination_cond\n self.decay_on = decay\n self.eps = eps\n self.steps = steps\n self.T = T\n self.specific = specific\n self.multi = multi\n self.epochs = epochs\n self.learning_rate = learning_rate\n self.device = device\n self.spmode = spmode\n self.mulmode = mulmode\n self.init_point_list = init_point_list\n self.mal_0_id = mal_0_id\n self.selected_init = []\n self.constraint = constraint\n self.beta = torch.tensor(beta, device=device)\n self.step_max = step_max\n self.init_seed = random.randint(1, 10000)\n self.init_pdata_indices = None\n self.init_plabel_list = None\n self.init_goodware_indices = None\n self.xvalid = xvalid\n self.yvalid = yvalid\n self.centroid = torch.tensor(centroid, device=device).float()\n self.radius = torch.tensor(radius, device=device).float()\n self.centroid_t = torch.tensor(centroid, device=device).float()\n self.radius_t = torch.tensor(radius_t, device=device).float()\n self.s_def = s_def\n self.solver = solver\n self.phi_iris = torch.tensor([0., 10.], device=device)\n self.phi_ransom = torch.tensor([0., 1., 0.5], device=device)\n self.eta2 = torch.tensor(eta, device=device)\n eta_limit = 0.1\n self.eta_limit = torch.tensor(eta_limit, device=device)\n self.init_eta_limit = torch.tensor(eta_limit, device=device)\n self.decay_limit = None\n\n def phi_map(self, option=0):\n if(self.dataset_id == -1):\n return\n elif(self.dataset_id == 1):\n if(option == 0):\n for i in range(self.nFeatures):\n x = self.point[0][i]\n if(x <= self.phi_ransom[0]):\n x.copy_(self.phi_ransom[0])\n elif(x >= self.phi_ransom[1]):\n x.copy_(self.phi_ransom[1])\n elif(option == 1): # final\n for i in range(self.nFeatures):\n x = self.point[0][i]\n if(x <= self.phi_ransom[2]):\n x.copy_(self.phi_ransom[0])\n else:\n x.copy_(self.phi_ransom[1])\n elif(self.dataset_id == 2): # ember\n if(option == 0):\n for i in range(self.nFeatures):\n x = self.point[0][i]\n if(x <= self.phi_ransom[0]):\n x.copy_(self.phi_ransom[0])\n elif(x >= self.phi_ransom[1]):\n x.copy_(self.phi_ransom[1])\n return\n\n def gradient_descent(self):\n [w, b] = list(self.model.parameters())\n w.data.copy_(self.w_0)\n b.data.copy_(self.b_0)\n t = 0\n while(t < self.T):\n self.model.zero_grad()\n loss = self.criterion(self.model(\n torch.cat((self.xtrain, self.point))), torch.cat((self.ytrain, self.label)))\n loss.backward()\n for param in self.model.parameters():\n param.data.sub_(param.grad.data * self.eta)\n t += 1\n return\n\n def back_gradient_descent(self):\n self.dx.copy_(torch.zeros(1, self.nFeatures))\n [w, b] = list(self.model.parameters())\n self.model.zero_grad()\n self.point.requires_grad_(True)\n val_loss = self.criterion(self.model(self.xvalid), self.yvalid)\n w_grad_val_loss = grad(val_loss, w, create_graph=True)[0]\n b_grad_val_loss = grad(val_loss, b, create_graph=True)[0]\n g = w_grad_val_loss[0].reshape(self.nFeatures, 1)\n gT = torch.transpose(g, 0, 1)\n\n def jacobian(y, x, create_graph=False):\n jac = []\n flat_y = y.reshape(-1)\n grad_y = torch.zeros_like(flat_y)\n for i in range(len(flat_y)):\n grad_y[i] = 1.\n grad_x, = torch.autograd.grad(\n flat_y, x, grad_y, retain_graph=True, create_graph=create_graph, allow_unused=True)\n jac.append(grad_x[0].reshape(x.shape[1]))\n grad_y[i] = 0.\n return torch.stack(jac).reshape(y.shape[0], x.shape[1])\n\n self.model.zero_grad()\n loss = self.criterion(self.model(\n torch.cat((self.xtrain, self.point))), torch.cat((self.ytrain, self.label)))\n w_grad_train_loss = grad(loss, w, create_graph=True)[0]\n H = jacobian(w_grad_train_loss[0], w)\n delta = 10\n H = delta * torch.eye(self.nFeatures, self.nFeatures) + H\n Hinv = H.inverse()\n self.model.zero_grad()\n ploss = self.criterion(self.model(self.point), self.label)\n p_w_grad_loss = grad(ploss, w, create_graph=True)[0]\n p_xw_grad_loss = jacobian(p_w_grad_loss[0], self.point)\n pT = torch.transpose(p_xw_grad_loss, 0, 1)\n dwdx = torch.mm(Hinv, p_xw_grad_loss)\n dt = torch.mm(gT, dwdx)\n x = dt.to('cpu').detach().numpy().copy()\n dt = torch.from_numpy(x.astype(np.float32)).clone()\n self.dx.copy_(dt)\n self.point.requires_grad_(False)\n return self.dx\n\n def make_poisoning_point_using_solver(self):\n\n def sigmoid(x):\n return 1. / (1. + math.exp(-x))\n\n def necessary_sphere(cent, radius, data):\n distanse = torch.sqrt(torch.sum((data - cent)**2))\n return distanse > radius\n\n def vec2centroid(cent, radius, data):\n to_cent = cent - data\n distanse = torch.sqrt(torch.sum((data - cent)**2))\n return to_cent * (distanse - radius) / distanse\n\n self.init_poisoning_point()\n\n if (self.solver):\n [w, b] = list(self.model.parameters())\n w = w[0].detach().numpy()\n c = b[0].detach().numpy()\n mu1 = self.centroid\n mu2 = self.centroid_t\n mu2 = self.point[0]\n r1 = self.radius\n r2 = self.radius_t\n r2 = 0.7\n n = len(w)\n x = cp.Variable(n)\n objective = cp.Minimize(w * x + c)\n print(\"constraints: ||x|| <= r , r = {:.5f}\".format(r1))\n print(\"r2 = {:.5f}\".format(r2))\n constraints = [cp.sum_squares(\n x - mu1) <= r1 * r1, cp.sum_squares(x - mu2) <= r2 * r2, x >= 0, x <= 1]\n problem = cp.Problem(objective, constraints)\n result = problem.solve()\n print(\"min_x ( w * x + c ) : {:.2f} ||x-mu1|| : {:.5f} ||x-mu2|| : {:.5f}\".format(\n result, cp.sum_squares(x - mu1).value, cp.sum_squares(x - mu2).value))\n print(\"x : {}\".format(x.value))\n p = sigmoid(result)\n self.point[0] = torch.tensor(x.value)\n\n if necessary_sphere(self.centroid, self.radius, self.point[0]):\n self.point[0].add_(vec2centroid(\n self.centroid, self.radius, self.point[0]))\n loss = self.criterion(self.model(self.point), self.label).item()\n self.phi_map(1)\n\n if necessary_sphere(self.centroid, self.radius, self.point[0]):\n v = self.centroid - self.point[0]\n for i in range(1, 10):\n tempx = self.point[0] + 0.1 * i * v\n for i in range(self.nFeatures):\n if(tempx[i] <= self.phi_ransom[2]):\n tempx[i].copy_(self.phi_ransom[0])\n else:\n tempx[i].copy_(self.phi_ransom[1])\n if (not necessary_sphere(self.centroid, self.radius, tempx)):\n self.point[0] = tempx\n break\n loss = self.criterion(self.model(self.point), self.label).item()\n sys.stdout.flush()\n return\n\n def make_poisoning_point(self):\n def sigmoid(x):\n return 1. / (1. + math.exp(-x))\n\n def necessary_sphere(cent, radius, data):\n distanse = np.linalg.norm(data - cent)\n return distanse, (distanse > radius + 0.1)\n\n def vec2centroid(cent, radius, data):\n to_cent = cent - data\n distanse = torch.sqrt(torch.sum((data - cent)**2))\n return to_cent * (distanse - radius) / distanse\n\n self.init_poisoning_point()\n self.model = LogisticRegression(\n self.nFeatures, self.nClasses).to(device=self.device)\n self.criterion = nn.CrossEntropyLoss()\n [w, b] = list(self.model.parameters())\n self.w_0.copy_(w.data)\n self.b_0.copy_(b.data)\n\n if self.constraint != 0:\n const_goodware = self.xtrain[self.init_goodware_indices.pop(0)]\n init_point = torch.tensor(self.point)\n\n loss = sys.float_info.max\n i = 0\n while(True):\n if self.step_max == i:\n break\n if self.decay_on:\n self.decay = torch.tensor(\n 1 / np.sqrt(i + 1), device=self.device)\n self.eta.copy_(self.init_eta * self.decay)\n pre_point = torch.tensor(self.point)\n pre_loss = loss\n self.gradient_descent()\n\n if self.constraint == 1:\n self.point.requires_grad_(True)\n l2norm_square = torch.norm(self.point - const_goodware)**2\n grad_l2 = grad(l2norm_square, self.point)[0]\n self.point.detach_()\n self.point.add_(self.eta * self.back_gradient_descent())\n self.point.sub_(self.eta * self.beta * grad_l2)\n elif self.constraint == 0:\n self.point.add_(\n self.eta2 * self.back_gradient_descent())\n\n if self.s_def:\n dist_defense, is_defense = necessary_sphere(\n self.centroid, self.radius, self.point[0])\n if is_defense:\n vec_defense = vec2centroid(\n self.centroid, self.radius, self.point[0])\n self.point[0].add_(vec_defense)\n self.phi_map()\n print(\"Poisoning Point (steps:{}): {}\".format(\n i + 1, self.point.cpu().numpy()))\n print(\"eta: {}\".format(self.eta))\n sys.stdout.flush()\n\n i += 1\n\n [w, b] = list(self.model.parameters())\n w.data.copy_(torch.ones(self.nClasses, self.nFeatures))\n b.data.copy_(torch.ones(self.nClasses))\n for epoch in range(self.epochs):\n self.model.zero_grad()\n loss = self.criterion(self.model(\n torch.cat((self.xtrain, self.point))), torch.cat((self.ytrain, self.label)))\n loss.backward()\n for param in self.model.parameters():\n param.data.sub_(param.grad.data * self.learning_rate)\n if self.constraint == 1:\n l2norm_square = torch.norm(self.point[0] - const_goodware)**2\n loss = self.criterion(self.model(self.xvalid), self.yvalid).item(\n ) + self.beta.item() * l2norm_square.item()\n elif self.constraint == 0:\n loss = self.criterion(self.model(\n self.xvalid), self.yvalid).item()\n if(pre_loss - loss < self.eps):\n break\n self.phi_map(1)\n del(self.model)\n del(self.criterion)\n return\n\n def init_poisoning_point(self):\n self.point[0].copy_(\n self.xtrain[self.init_pdata_indices.pop(0)])\n self.label.copy_(torch.tensor(\n [self.init_plabel_list.pop(0)]).long())\n return\n\n def init_selection(self, num):\n def necessary_sphere(cent, radius, data):\n distanse = torch.sqrt(torch.sum((data - cent)**2))\n return distanse > radius\n nr.seed(self.init_seed)\n l = np.where(self.init_point_list == self.mal_0_id)[0]\n\n for i in reversed(range(len(l))):\n if (necessary_sphere(self.centroid, self.radius, self.xtrain[l[i]])):\n l = np.delete(l, i)\n\n self.init_pdata_indices = nr.choice(l, num).tolist()\n self.init_plabel_list = [0] * num\n self.selected_init = self.init_pdata_indices[:]\n nr.seed(self.init_seed)\n l = np.where(self.init_point_list == 0)[0]\n self.init_goodware_indices = nr.choice(l, num).tolist()\n return\n\n def make_poisoning_data_using_solver(self, num):\n start = time.time()\n poisoning_data_x = torch.empty(num, self.nFeatures, device=self.device)\n poisoning_data_y = torch.empty(\n num, dtype=torch.long, device=self.device)\n self.init_selection(num)\n fraction = torch.tensor(num / self.xtrain.shape[0], device=self.device)\n self.model = LogisticRegression(\n self.nFeatures, self.nClasses).to(device=self.device)\n self.criterion = nn.CrossEntropyLoss()\n print(self.model.parameters())\n [w, b] = list(self.model.parameters())\n w.data.fill_(0)\n b.data.fill_(0)\n burn = 2000\n n = 1\n p = 0\n while(n <= num + burn):\n if (n > burn):\n print(\"\\n --- creating point ({})\".format(p + 1))\n self.make_poisoning_point_using_solver()\n sys.stdout.flush()\n self.decay_limit = torch.tensor(1 / np.sqrt(n + 1), device=self.device)\n self.eta_limit.copy_(self.init_eta_limit * self.decay_limit)\n self.model.zero_grad()\n loss1 = self.criterion(self.model(self.xtrain), self.ytrain)\n [w, b] = list(self.model.parameters())\n w_grad_loss1 = grad(loss1, w, create_graph=True)[0]\n b_grad_loss1 = grad(loss1, b, create_graph=True)[0]\n w.detach().sub_(self.eta_limit * (w_grad_loss1.detach()))\n b.detach().sub_(self.eta_limit * (b_grad_loss1.detach()))\n if (n > burn):\n loss2 = self.criterion(self.model(self.point), self.label)\n w_grad_loss2 = grad(loss2, w, create_graph=True)[0]\n b_grad_loss2 = grad(loss2, b, create_graph=True)[0]\n w.detach().sub_(self.eta_limit * (w_grad_loss2.detach() * fraction))\n b.detach().sub_(self.eta_limit * (b_grad_loss2.detach() * fraction))\n sys.stdout.flush()\n poisoning_data_x[p].copy_(self.point[0])\n poisoning_data_y[p].copy_(self.label[0])\n if (n > burn):\n p += 1\n n += 1\n [w, b] = list(self.model.parameters())\n del(self.model)\n del (self.criterion)\n return poisoning_data_x, poisoning_data_y\n\n def make_poisoning_data(self, num):\n start = time.time()\n poisoning_data_x = torch.empty(num, self.nFeatures, device=self.device)\n poisoning_data_y = torch.empty(\n num, dtype=torch.long, device=self.device)\n self.init_selection(num)\n n = 0\n while(n < num):\n print(\"\\n --- creating point ({})\".format(n + 1))\n sys.stdout.flush()\n self.make_poisoning_point()\n if(torch.sum(self.point != self.point).item() != 0):\n continue\n else:\n poisoning_data_x[n].copy_(self.point[0])\n poisoning_data_y[n].copy_(self.label[0])\n n += 1\n return poisoning_data_x, poisoning_data_y\n\n def get_selected_init_indices(self):\n return self.selected_init\n\n\nclass LogisticRegression(nn.Module):\n def __init__(self, input_size, num_classes):\n super(LogisticRegression, self).__init__()\n self.linear = nn.Linear(input_size, num_classes)\n\n def forward(self, x):\n out = self.linear(x)\n return out\n","sub_path":"poisoner.py","file_name":"poisoner.py","file_ext":"py","file_size_in_byte":17453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"321310875","text":"import asyncio\nfrom dataclasses import dataclass\nfrom typing import Callable, Awaitable, Any, Optional\n\nimport asyncpg # type: ignore\n\n\n# ----------------------\n# ----- data types -----\n# ----------------------\n@dataclass\nclass Job:\n \"a generic job\"\n job_id: str\n job_name: str\n cmd_type: str\n cmd_payload: str\n\n\n@dataclass\nclass CronJob(Job):\n \"job scheduled with cron syntax (ie. recurring)\"\n timezone: str\n cron_schedule: str\n\n\n@dataclass\nclass AdhocJob(Job):\n \"job scheduled with cron syntax (ie. recurring)\"\n schedule_ts: float\n\n\n@dataclass\nclass HttpJob(Job):\n \"a job to be executed as an http request\"\n method: str\n url: str\n body: Optional[str] = None\n\n\n# ----------------------\n# --- database types ---\n# ----------------------\n# an update callback to receive the latest cron_jobs\nDBCon = asyncpg.Connection\nNotifyChannel = str\nNotifyPayload = str\nPgNotifyListener = Callable[[NotifyPayload], Any]\n\n\n# ----------------------\n# ---- other types -----\n# ----------------------\nJobHandler = Callable[[Job], Awaitable[None]]\nEventLoop = asyncio.AbstractEventLoop\n","sub_path":"pjobq/apptypes.py","file_name":"apptypes.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"293338199","text":"\"\"\"\npaho mqtt function\n\"\"\"\nfrom typing import List\nimport json\nimport numpy as np\nimport paho.mqtt.client as mqtt\n\nfrom visualization.bokeh_visualizer import show_map\n\nfrom scheme.mqtt import WorldSet\nfrom scheme.mqtt import CustomQueue, DrawMapInfo, LGSVLMqttInfo\n\n\nclass Mqtt:\n \"\"\"\n Basic Mqtt class\n \"\"\"\n\n def __init__(self, topic: List[str], address: str, port: int) -> None:\n self.client: mqtt.Client = mqtt.Client()\n self.client.on_connect = self.on_connect\n self.client.on_message = self.on_message\n self.topic: List[str] = topic\n self.address: str = address\n self.port: int = port\n\n def __call__(self) -> None:\n \"\"\"\n subscribe loop forever\n \"\"\"\n self.client.connect(self.address, self.port)\n self.client.subscribe(self.topic, 1)\n self.client.loop_forever()\n\n def on_connect(self, client, userdata, flags, rc) -> None:\n \"\"\"\n start subscribe\n \"\"\"\n print(\"Connected with result code \" + str(rc))\n client.subscribe(self.topic)\n\n def on_message(self, client, userdata, msg):\n pass\n\n\nclass LGSVLMqtt(Mqtt):\n \"\"\"\n LGSVL Mqtt Subscriber\n\n Args:\n lgsvl_info (LGSVLMqttInfo): information for lgsvl subscriber and bokeh visualizer\n \"\"\"\n\n def __init__(self, lgsvl_info: LGSVLMqttInfo) -> None:\n super().__init__(lgsvl_info.topic, lgsvl_info.address, lgsvl_info.port)\n\n self.vehicle_que = CustomQueue(100)\n self.obstacle_que = CustomQueue(100)\n\n self.world_set: WorldSet = lgsvl_info.world_set\n self.plot = lgsvl_info.plot\n self.map_info = lgsvl_info.map_info\n self.out_dir = lgsvl_info.out_dir\n self.img_dir = lgsvl_info.img_dir\n self.trans_scale = lgsvl_info.trans_scale\n\n def on_message(self, client, userdata, msg) -> None:\n \"\"\"\n subscribe mqtt message\n\n Args:\n client:\n userdata:\n msg: message from mqtt publisher\n \"\"\"\n topic = msg.topic\n payload = json.loads(str(msg.payload.decode(\"utf-8\")))\n payload[\"topic\"] = topic\n self.parse_data(topic, payload)\n\n if (\n len(self.vehicle_que) != 0\n and len(self.obstacle_que) != 0\n and len(self.vehicle_que) == len(self.obstacle_que)\n ):\n draw_map_data = {\n \"vehicle_que\": self.vehicle_que,\n \"obstacle_que\": self.obstacle_que,\n \"plot\": self.plot,\n \"map_info\": self.map_info,\n \"trans_scale\": self.trans_scale,\n \"out_dir\": self.out_dir,\n \"img_dir\": self.img_dir,\n }\n draw_map_info = DrawMapInfo(**draw_map_data)\n show_map(draw_map_info)\n\n def parse_data(self, topic: str, payload: dict) -> None:\n \"\"\"\n parse mqtt message\n\n Args:\n topic: topic in message\n payload: payload(body) in message\n \"\"\"\n try:\n if topic == \"/apollo/sensor/gnss/odometry\":\n x = payload[\"localization\"][\"position\"][\"x\"] - self.world_set.x_0\n y = payload[\"localization\"][\"position\"][\"y\"] - self.world_set.y_0\n v_pos = np.array([x, y])\n self.vehicle_que.push(v_pos)\n elif topic == \"/apollo/perception/obstacles\":\n obstacles = payload[\"perceptionObstacle\"]\n ids, polygons = [], []\n for obstacle in obstacles:\n # add id\n id = obstacle[\"id\"]\n ids.append(id)\n # add polygon points\n poly_pos = np.zeros((0, 2))\n for pp in obstacle[\"polygonPoint\"]:\n x = pp[\"x\"] - self.world_set.x_0\n y = pp[\"y\"] - self.world_set.y_0\n poly_pos = np.vstack((poly_pos, [x, y]))\n polygons.append(poly_pos)\n # tuple(list, np.ndarray)\n self.obstacle_que.push((ids, np.array(polygons)))\n else:\n raise Exception(\"topic does not existed.\")\n except Exception as e:\n print(e)\n","sub_path":"client/src/python_mqtt/mqtt.py","file_name":"mqtt.py","file_ext":"py","file_size_in_byte":4233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"45435016","text":"#다중 분류\nimport numpy as np\n\n#sklearn boston\nfrom sklearn.datasets import load_iris\n\n#1.\ndataset = load_iris()\nx = dataset.data\ny = dataset.target\nprint(\"shape of iris dataset : \", x.shape, y.shape)\n#(150, 4)(150,)\n\n# print(dataset.feature_names)\n# print(dataset.DESCR)\n\n#one-hot encoding\nfrom tensorflow.keras.utils import to_categorical\n# y = to_categorical(y)\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x, y, \n train_size=0.8, random_state=66)\n\n#2.\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Input\n\nmodel = Sequential()\nmodel.add(Dense(10, activation='relu', input_shape=(4,)))\nmodel.add(Dense(50))\nmodel.add(Dense(20))\nmodel.add(Dense(3, activation='softmax')) #다중분류 = softmax\n# 라벨개수 (... one hot encoding)\n\n\n#3.\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc'])\nmodel.fit(x_train, y_train, epochs=100, batch_size=1,\n verbose=1, validation_split=0.1)\n\n#4.\nloss = model.evaluate(x_test, y_test)\nprint(\"loss : \", loss[0]) #[categorical_crossentropy loss , accuarcy]\nprint(\"acc : \", loss[1])\n\ny_predict = model.predict(x_test)\nprint(y_test[:3])\nprint(y_predict[:3])\n\nfrom sklearn.metrics import r2_score\nR2 = r2_score(y_predict, y_test)\nprint(\"R2 : \", R2)","sub_path":"Keras/keras13_iris3_sparse.py","file_name":"keras13_iris3_sparse.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"513196722","text":"import argparse\nimport logging\nfrom pathlib import Path\nimport sys\nimport time\n\nimport ldap3\nimport yaml\nfrom kubernetes import config as k_config\nfrom prometheus_client import start_http_server, Counter, Summary, Gauge\n\nfrom maintain_kubeusers.k8s_api import K8sAPI\nfrom maintain_kubeusers.utils import (\n generate_pk,\n get_tools_from_ldap,\n get_admins_from_ldap,\n process_new_users,\n process_disabled_users,\n process_removed_users,\n)\n\n\"\"\"\nAutomate the process of generating user credentials for Toolforge\nKubernetes\n\n\n - Get a list of all the users from LDAP\n - Get a list of namespaces/configmaps in k8s for each toolforge user\n - Do a diff, find new users and users with deleted configmaps\n - For each new user or removed configmap:\n - Create new namespace (only for a new user)\n - generate a CSR (including the right group for RBAC/PSP)\n - Validate and approve the CSR\n - Drop the .kube/config file in the tool directory\n - Annotate the namespace with configmap\n\n\"\"\"\n\n\nrun_time = Summary(\n \"maintain_kubeusers_run_seconds\", \"Time spent on maintain-kubeusers runs\"\n)\nrun_finished = Gauge(\n \"maintain_kubeusers_run_finished\",\n \"Timestamp when the last maintain-kubeusers run finished\",\n)\naccounts_created = Counter(\n \"maintain_kubeusers_accounts_created\",\n \"Number of new accounts created\",\n [\"account_type\"],\n)\naccounts_renewed = Counter(\n \"maintain_kubeusers_accounts_renewed\",\n \"Number of new accounts whose certificates were renewed\",\n [\"account_type\"],\n)\naccounts_disabled = Counter(\n \"maintain_kubeusers_accounts_disabled\",\n \"Number of new accounts whose access was disabled pending deletion\",\n [\"account_type\"],\n)\naccounts_removed = Counter(\n \"maintain_kubeusers_accounts_removed\",\n \"Number of new accounts completely removed\",\n [\"account_type\"],\n)\n\n\n@run_time.time()\ndef do_run(k8s_api, ldap_config, ldap_servers, project, api_server, ca_data):\n cur_users, expiring_users = k8s_api.get_current_users()\n with ldap3.Connection(\n ldap_servers,\n read_only=True,\n user=ldap_config[\"user\"],\n auto_bind=True,\n password=ldap_config[\"password\"],\n raise_exceptions=True,\n receive_timeout=60,\n ) as conn:\n tools = get_tools_from_ldap(conn, project)\n admins = get_admins_from_ldap(conn, project)\n\n # Initialize these to zero in cases where something is missing.\n new_tools = 0\n new_admins = 0\n\n removed_tools = process_removed_users(tools, cur_users[\"tools\"], k8s_api)\n accounts_removed.labels(account_type=\"tool\").inc(removed_tools)\n\n removed_admins = process_removed_users(\n admins, cur_users[\"admins\"], k8s_api, admins=True\n )\n accounts_removed.labels(account_type=\"admin\").inc(removed_admins)\n\n if tools:\n new_tools = process_new_users(\n tools,\n cur_users[\"tools\"],\n k8s_api,\n admin=False,\n )\n accounts_created.labels(account_type=\"tool\").inc(new_tools)\n\n if expiring_users[\"tools\"]:\n for tool_name in expiring_users[\"tools\"]:\n tools[tool_name].pk = generate_pk()\n k8s_api.generate_csr(tools[tool_name].pk, tool_name)\n tools[tool_name].cert = k8s_api.approve_cert(tool_name)\n tools[tool_name].create_homedir()\n tools[tool_name].write_kubeconfig(api_server, ca_data)\n k8s_api.update_expired_ns(tools[tool_name])\n logging.info(\"Renewed creds for tool %s\", tool_name)\n accounts_renewed.labels(account_type=\"tool\").inc()\n\n if admins:\n new_admins = process_new_users(\n admins,\n cur_users[\"admins\"],\n k8s_api,\n admin=True,\n )\n accounts_created.labels(account_type=\"admin\").inc(new_admins)\n\n if expiring_users[\"admins\"]:\n for admin_name in expiring_users[\"admins\"]:\n admins[admin_name].pk = generate_pk()\n k8s_api.generate_csr(\n admins[admin_name].pk, admin_name, admin=True\n )\n admins[admin_name].cert = k8s_api.approve_cert(\n admin_name, admin=True\n )\n admins[admin_name].create_homedir()\n admins[admin_name].write_kubeconfig(api_server, ca_data)\n k8s_api.update_expired_ns(admins[admin_name])\n logging.info(\"Renewed creds for admin user %s\", admin_name)\n accounts_renewed.labels(account_type=\"admin\").inc()\n\n disabled_tools = process_disabled_users(tools, cur_users[\"tools\"], k8s_api)\n accounts_disabled.labels(account_type=\"tool\").inc(disabled_tools)\n\n logging.info(\n \"finished run, wrote %s new accounts, disabled %s accounts, \"\n \"cleaned up %s accounts\",\n new_tools + new_admins,\n disabled_tools,\n removed_tools + removed_admins,\n )\n\n\ndef main():\n argparser = argparse.ArgumentParser()\n group1 = argparser.add_mutually_exclusive_group()\n argparser.add_argument(\n \"--ldapconfig\",\n help=\"Path to YAML LDAP config file\",\n default=\"/etc/ldap.yaml\",\n )\n argparser.add_argument(\n \"--debug\", help=\"Turn on debug logging\", action=\"store_true\"\n )\n argparser.add_argument(\n \"--project\",\n help=\"Project name to fetch LDAP users from\",\n default=\"tools\",\n )\n group1.add_argument(\n \"--interval\", help=\"Seconds between between runs\", default=60\n )\n group1.add_argument(\"--once\", help=\"Run once and exit\", action=\"store_true\")\n argparser.add_argument(\n \"--local\",\n help=\"Specifies this is not running in Kubernetes (for debugging)\",\n action=\"store_true\",\n )\n\n args = argparser.parse_args()\n\n loglvl = logging.DEBUG if args.debug else logging.INFO\n logging.basicConfig(format=\"%(message)s\", level=loglvl)\n\n with open(args.ldapconfig, encoding=\"utf-8\") as f:\n ldap_config = yaml.safe_load(f)\n\n ldap_servers = ldap3.ServerPool(\n [ldap3.Server(s, connect_timeout=1) for s in ldap_config[\"servers\"]],\n ldap3.ROUND_ROBIN,\n active=True,\n exhaust=True,\n )\n\n if args.local:\n k_config.load_kube_config()\n else:\n k_config.load_incluster_config()\n\n k8s_api = K8sAPI()\n api_server, ca_data = k8s_api.get_cluster_info()\n\n start_http_server(9000)\n\n while True:\n logging.info(\"starting a run\")\n # Touch a temp file for a Kubernetes liveness check to prevent hangs\n Path(\"/tmp/run.check\").touch()\n\n do_run(\n k8s_api=k8s_api,\n ldap_servers=ldap_servers,\n ldap_config=ldap_config,\n project=args.project,\n api_server=api_server,\n ca_data=ca_data,\n )\n\n run_finished.set_to_current_time()\n\n if args.once:\n break\n\n time.sleep(args.interval)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"maintain_kubeusers/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":6996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7059033","text":"\n# 24 RGB values, one for each 15-degree hue incr around the HSV color wheel\nwheel = [\n (255,0,0),\n (255,51,0),\n (255,102,0),\n (255,128,0),\n (255,153,0),\n (255,178,0),\n (255,204,0),\n (255,229,0),\n (255,255,0),\n (204,255,0),\n (153,255,0),\n (51,255,0),\n (0,204,0),\n (0,178,102),\n (0,153,153),\n (0,102,178),\n (0,51,204),\n (25,25,178),\n (51,0,153),\n (64,0,153),\n (102,0,153),\n (153,0,153),\n (204,0,153),\n (229,0,102),\n]\n\n# Offsets used to yield different color cycling methods\nanalogicOffsets = [ 0, 12, 18, 6, 1, 13, 19, 7 ]\ntetradOffsets = [ 0, 22, 2, 1, 23, 3 ]\ntriadOffsets = [ 0, 4, 6, 2, 5, 3, 7, 1 ]\n\n# Generate index values (into 'wheel') for each cycling method\n\nanalogicSteps = []\nfor offset in analogicOffsets:\n analogicSteps.append(offset)\n analogicSteps.append((offset + 2) % 24)\n analogicSteps.append((offset + 4) % 24)\n\ntetradSteps = []\nfor offset in tetradOffsets:\n tetradSteps.append(offset)\n tetradSteps.append((offset + 4) % 24)\n tetradSteps.append((offset + 12) % 24)\n tetradSteps.append((offset + 16) % 24)\n\ntriadSteps = []\nfor offset in triadOffsets:\n triadSteps.append(offset)\n triadSteps.append((offset + 8) % 24)\n triadSteps.append((offset + 16) % 24)\n\n# Generate color cycle values from a given stepping pattern\ndef cycle(steps):\n for n in xrange(len(wheel)):\n yield wheel[steps[n]]\n \n# Bake color cycles into lists for random access\nanalogicColors = list(rgb for rgb in cycle(analogicSteps))\ntetradColors = list(rgb for rgb in cycle(tetradSteps))\ntriadColors = list(rgb for rgb in cycle(triadSteps))\n\ndef get_color(colors, index):\n return colors[index % len(colors)]\n \n","sub_path":"colorwheel.py","file_name":"colorwheel.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"30394269","text":"class Richter_Scale():\n \"\"\"Calculates the energy (joules) and equivalant in tons of TNT from given richter scale float.\"\"\"\n\n def __init__(self, richter):\n self.richter = richter\n\n #Richter to joules\n def richter_joules(self):\n if self == '':\n richter = 0\n sum = (1.5 * self) + 4.8\n print(\"Equivalence in joules: \" + str(10**sum))\n return str(10**sum)\n \n #Joules to TNT(by the Ton)\n def joules_tnt(self):\n if self == '':\n richter = 0\n sum = Richter_Scale.richter_joules(self)/4.184e9\n return \"Equivalence in tons of TNT: \" + str(sum)\n\n #Prompt with richter conversion examples\n def richter_sample_message():\n prompt = (\n \"Richter Joules TNT\\n\"\n \"1 1995262.3149688789 0.00047687913837688307\\n\"\n \"5 1995262314968.8828 476.87913837688404\\n\"\n \"9.1 2.818382931264449e+18 673609687.2046962\\n\" \n \"9.2 3.981071705534953e+18 951498973.5982201\\n\"\n \"9.3 5.623413251903491e+18 1344028023.8775074\\n\"\n )\n print(prompt)\n\n def start():\n Richter_Scale.richter_sample_message()\n richter = float(input(\"\\nPlease enter a Richter scale value: \"))\n for f in Richter_Scale.index:\n print(f(richter))\n\n #index to cycle through methods\n index = [richter_joules, joules_tnt]\n\nRichter_Scale.start()","sub_path":"proj02.py","file_name":"proj02.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"415746354","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\n# Copyright 2019 The FATE 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\nfrom google.protobuf import json_format\n\nfrom arch.api.proto import feature_binning_meta_pb2, feature_binning_param_pb2\nfrom arch.api.utils import log_utils\nfrom federatedml.feature.binning.base_binning import IVAttributes\nfrom federatedml.feature.binning.bucket_binning import BucketBinning\nfrom federatedml.feature.binning.quantile_binning import QuantileBinning\nfrom federatedml.model_base import ModelBase\nfrom federatedml.param.feature_binning_param import FeatureBinningParam\nfrom federatedml.statistic.data_overview import get_header\nfrom federatedml.util import abnormal_detection\nfrom federatedml.util import consts\nfrom federatedml.util.transfer_variable.hetero_feature_binning_transfer_variable import \\\n HeteroFeatureBinningTransferVariable\n\nLOGGER = log_utils.getLogger()\n\nMODEL_PARAM_NAME = 'FeatureBinningParam'\nMODEL_META_NAME = 'FeatureBinningMeta'\n\n\nclass BaseHeteroFeatureBinning(ModelBase):\n \"\"\"\n Do binning method through guest and host\n\n Attributes\n ----------\n header : list\n record headers of input table\n\n has_synchronized : bool\n Record whether the encryption information has been synchronized or not.\n\n flowid : str\n Use in cross validation\n\n binning_result: dict\n Record binning result of guest party. The format is {'col_name': 'iv_attr', ... }\n\n host_results: dict\n This attribute uses to record host results. For future version which may record multiple host results,\n the format is dict of dict.\n e.g.\n host_results = {'host1': {'x1': iv1, 'x2: iv2}\n 'host2': ...\n }\n\n \"\"\"\n\n def __init__(self):\n super(BaseHeteroFeatureBinning, self).__init__()\n self.transfer_variable = HeteroFeatureBinningTransferVariable()\n self.cols = None\n self.cols_dict = {}\n self.binning_obj = None\n self.header = []\n self.schema = {}\n self.has_synchronized = False\n self.flowid = ''\n self.binning_result = {} # dict of iv_attr\n self.host_results = {} # dict of host results\n self.party_name = 'Base'\n self.model_param = FeatureBinningParam()\n\n def _init_model(self, params):\n self.model_param = params\n self.cols_index = params.cols\n if self.model_param.method == consts.QUANTILE:\n self.binning_obj = QuantileBinning(self.model_param, self.party_name)\n elif self.model_param.method == consts.BUCKET:\n self.binning_obj = BucketBinning(self.model_param, self.party_name)\n else:\n # self.binning_obj = QuantileBinning(self.bin_param)\n raise ValueError(\"Binning method: {} is not supported yet\".format(self.model_param.method))\n\n def transform(self, data_instances):\n self._parse_cols(data_instances)\n transform_cols_idx = self.model_param.transform_param.transform_cols\n transform_type = self.model_param.transform_param.transform_type\n data_instances = self.binning_obj.transform(data_instances, transform_cols_idx, transform_type)\n\n self.set_schema(data_instances)\n self.data_output = data_instances\n\n return data_instances\n\n def _get_meta(self):\n col_list = [str(x) for x in self.cols]\n\n meta_protobuf_obj = feature_binning_meta_pb2.FeatureBinningMeta(\n method=self.model_param.method,\n compress_thres=self.model_param.compress_thres,\n head_size=self.model_param.head_size,\n error=self.model_param.error,\n bin_num=self.model_param.bin_num,\n cols=col_list,\n adjustment_factor=self.model_param.adjustment_factor,\n local_only=self.model_param.local_only,\n need_run=self.need_run\n )\n return meta_protobuf_obj\n\n def _get_param(self):\n\n binning_result = self.binning_result\n\n host_results = self.host_results\n\n iv_attrs = {}\n for col_name, iv_attr in binning_result.items():\n iv_result = iv_attr.result_dict()\n iv_object = feature_binning_param_pb2.IVParam(**iv_result)\n iv_attrs[col_name] = iv_object\n binning_result_obj = feature_binning_param_pb2.FeatureBinningResult(binning_result=iv_attrs)\n\n final_host_results = {}\n for host_id, this_host_results in host_results.items():\n host_result = {}\n for host_col_idx, iv_attr in this_host_results.items():\n iv_result = iv_attr.result_dict()\n iv_object = feature_binning_param_pb2.IVParam(**iv_result)\n host_result[str(host_col_idx)] = iv_object\n final_host_results[host_id] = feature_binning_param_pb2.FeatureBinningResult(binning_result=host_result)\n\n result_obj = feature_binning_param_pb2.FeatureBinningParam(binning_result=binning_result_obj,\n host_results=final_host_results)\n # json_result = json_format.MessageToJson(result_obj)\n # LOGGER.debug(\"json_result: {}\".format(json_result))\n return result_obj\n\n def _load_model(self, model_dict):\n model_param = list(model_dict.get('model').values())[0].get(MODEL_PARAM_NAME)\n # self._parse_need_run(model_dict, MODEL_META_NAME)\n model_meta = list(model_dict.get('model').values())[0].get(MODEL_META_NAME)\n # model_meta.cols = list(model_meta.cols)\n # model_meta.transform_param.transform_cols = list(model_meta.transform_param.transform_cols)\n self.cols = list(map(int, model_meta.cols))\n bin_method = str(model_meta.method)\n if bin_method == consts.QUANTILE:\n self.binning_obj = QuantileBinning(model_meta, self.party_name)\n else:\n self.binning_obj = BucketBinning(model_meta, self.party_name)\n\n binning_result_obj = dict(model_param.binning_result.binning_result)\n host_params = dict(model_param.host_results)\n\n self.binning_result = {}\n self.host_results = {}\n for col_name, iv_attr_obj in binning_result_obj.items():\n iv_attr = IVAttributes([], [], [], [], [], [])\n iv_attr.reconstruct(iv_attr_obj)\n self.binning_obj.reconstruct_by_iv_obj(col_name, iv_attr)\n self.binning_result[col_name] = iv_attr\n # self.cols.append(col_name)\n\n for host_name, host_result_obj in host_params.items():\n host_result_obj = dict(host_result_obj.binning_result)\n for col_name, iv_attr_obj in host_result_obj.items():\n iv_attr = IVAttributes([], [], [], [], [], [])\n iv_attr.reconstruct(iv_attr_obj)\n host_result_obj[col_name] = iv_attr\n self.host_results[host_name] = host_result_obj\n # LOGGER.debug(\"In feature binning load model, self.binning_result: {}, cols: {}, host_results: {}\".format(\n # self.binning_result, self.cols, self.host_results\n # ))\n\n def export_model(self):\n if self.model_output is not None:\n return self.model_output\n\n meta_obj = self._get_meta()\n param_obj = self._get_param()\n result = {\n MODEL_META_NAME: meta_obj,\n MODEL_PARAM_NAME: param_obj\n }\n self.model_output = result\n return result\n\n def save_data(self):\n return self.data_output\n\n def _parse_cols(self, data_instances):\n if self.header is not None and len(self.header) != 0:\n return\n\n LOGGER.debug(\"Before Binning, schema is : {}\".format(data_instances.schema))\n header = get_header(data_instances)\n self.schema = data_instances.schema\n self.header = header\n # LOGGER.debug(\"data_instance count: {}, header: {}\".format(data_instances.count(), header))\n if self.cols_index == -1:\n if header is None:\n raise RuntimeError('Cannot get feature header, please check input data')\n self.cols = [i for i in range(len(header))]\n else:\n self.cols = self.cols_index\n\n self.cols_dict = {}\n for col in self.cols:\n col_name = header[col]\n self.cols_dict[col_name] = col\n\n def set_schema(self, data_instance):\n self.schema['header'] = self.header\n data_instance.schema = self.schema\n LOGGER.debug(\"After Binning, when setting schema, schema is : {}\".format(data_instance.schema))\n\n\n def _abnormal_detection(self, data_instances):\n \"\"\"\n Make sure input data_instances is valid.\n \"\"\"\n abnormal_detection.empty_table_detection(data_instances)\n abnormal_detection.empty_feature_detection(data_instances)\n","sub_path":"federatedml/feature/hetero_feature_binning/base_feature_binning.py","file_name":"base_feature_binning.py","file_ext":"py","file_size_in_byte":9365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"609888147","text":"import os\nimport importlib\n\n# keras\nfrom keras.optimizers import SGD, Adam\nfrom keras.callbacks import ModelCheckpoint, CSVLogger\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.utils import plot_model\nfrom keras.layers.core import Dropout\nfrom keras.models import clone_model\n\n# tensorflow\nimport tensorflow as tf \nfrom tensorflow.keras.metrics import AUC, Precision, Recall\n\n# utility\nfrom utility.dl.diagnostics import plotHistory\nfrom utility.dl.args import parseTrainArguments\nfrom utility.dl.cnn import getVgg16, getResNet50, getInceptionV3\nfrom utility.dl.cnn import loadFromFile, saveToFile\nfrom utility.dl.scale import getBinaryClassWeights\nfrom utility.dl.losses import binary_focal_loss\n\n\ndef main():\n\n \"\"\" \n setup model based on command line input and execute training \n \"\"\"\n\n # parse arguments\n args = parseTrainArguments()\n print ( 'epochs {} / batch size {}'.format ( args.epochs, args.batch_size ) )\n\n # start session\n session = tf.keras.backend.get_session()\n init = tf.global_variables_initializer()\n session.run(init)\n\n # optional model creation\n if args.load_path is not None:\n\n # load model from file\n model, args.model = loadFromFile( args.load_path )\n\n else:\n\n # define topmost cnn layers plugged into pretrained model\n layers = { 'fc' : [ { 'units' : 256, 'activation' : 'relu', 'dropout' : 0.2 },\n { 'units' : 128, 'activation' : 'relu', 'dropout' : 0.2 } ],\n 'out' : [ { 'units' : 1, 'activation' : 'sigmoid' } ]\n }\n\n # create model from argument\n cnn_library = { 'vgg16': getVgg16, 'resnet50': getResNet50, 'inception_v3': getInceptionV3 }\n model = cnn_library[ args.model ]( ( args.image_size, args.image_size, 3 ), layers )\n\n\n # valid model\n plot_model(model, show_shapes=True, to_file='model.png')\n if model is not None: \n\n # setup optimiser and compile\n #opt = SGD( lr=0.01, momentum=0.9 )\n opt = Adam( lr=1e-6 )\n model.compile( optimizer=opt, \n loss='binary_crossentropy', \n metrics=[AUC(name='auc'),Precision(name='precision'),Recall(name='recall') ] )\n \n #opt = Adam( lr=1e-6 )\n #model.compile( optimizer=opt, \n # loss=[binary_focal_loss(alpha=.90, gamma=2)], \n # metrics=[AUC(name='auc'),Precision(name='precision'),Recall(name='recall') ] )\n model.summary()\n\n # select preprocess_input wrapper\n module = importlib.import_module( 'keras.applications.{}'.format( args.model ) )\n preprocess_input = module.preprocess_input\n \n # create data generators\n train_datagen = ImageDataGenerator( preprocessing_function=preprocess_input,\n horizontal_flip=True, \n vertical_flip=True, \n rotation_range=90 )\n \n test_datagen = ImageDataGenerator( preprocessing_function=preprocess_input )\n\n # get train iterator - binary classification\n path = os.path.join( args.data_path, 'train' )\n train_it = train_datagen.flow_from_directory( path, \n class_mode='binary', \n batch_size=args.batch_size, \n classes=[ 'grinding', 'integrated' ],\n target_size=(args.image_size, args.image_size) )\n\n # get test iterator - binary classification\n path = os.path.join( args.data_path, 'test' )\n test_it = test_datagen.flow_from_directory( path, \n class_mode='binary', \n batch_size=1, \n classes=[ 'grinding', 'integrated' ],\n target_size=(args.image_size, args.image_size) )\n\n # confirm the iterator works\n batchX, batchy = train_it.next()\n print('Batch shape=%s, min=%.3f, max=%.3f, mean=%.3f, std=%.3f' % (batchX.shape, batchX.min(), batchX.max(), batchX.mean(), batchX.std() ))\n\n # setup callbacks\n callbacks = [ CSVLogger( 'log.csv', append=True ) ]\n if args.checkpoint_path is not None:\n\n # create sub-directory if required\n if not os.path.exists ( args.checkpoint_path ):\n os.makedirs( args.checkpoint_path )\n\n # setup checkpointing callback\n path = os.path.join( args.checkpoint_path, \"weights-{epoch:02d}-{val_recall:.2f}.h5\" )\n checkpoint = ModelCheckpoint( path, \n monitor='val_recall', \n verbose=1, \n save_best_only=True, \n mode='max' )\n callbacks.append( checkpoint )\n\n\n # fit model\n weights = getBinaryClassWeights( args.data_path, [ 'grinding', 'integrated' ] )\n history = model.fit_generator( train_it, \n steps_per_epoch=len(train_it), \n class_weight=weights,\n validation_data=test_it, \n validation_steps=len(test_it), \n epochs=args.epochs, \n callbacks=callbacks,\n verbose=1 )\n\n # evaluate model\n scores = model.evaluate_generator( test_it, \n steps=len(test_it), \n verbose=1 )\n print('Final Metric Scores> {}'.format( scores ) )\n\n # optional save\n if args.save_path is not None:\n saveToFile( model, args.save_path, args.model )\n\n # plot learning curves\n plotHistory(history)\n\n return\n \n# execute main\nif __name__ == '__main__':\n main()\n","sub_path":"cement/plant-type/src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"188941580","text":"from flask import Flask, render_template,session,redirect\napp = Flask(__name__)\napp.secret_key = \"Welp\"\n\n@app.route('/')\ndef index():\n if 'count' not in session:\n session['count'] = 0\n\n session['count'] += 1\n return render_template('index.html',count=session['count'])\n\n@app.route('/twice')\ndef twice():\n session['count'] +=1\n return redirect('/')\n\n@app.route('/reset')\ndef reset():\n session['count'] = 0\n return redirect('/')\n\nif __name__ == '__main__':\n app.run(debug=True)\n ","sub_path":"Flask/Counter/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"174329607","text":"from omni.isaac.utils.scripts.nucleus_utils import find_nucleus_server\nimport carb\nimport omni\nfrom pxr import UsdGeom, Gf, Sdf, PhysxSchema, PhysicsSchema, PhysicsSchemaTools\nfrom omni.isaac.synthetic_utils import DomainRandomization\n\n\n\n\nclass Environment:\n def __init__(self, omni_kit, z_height=0):\n self.omni_kit = omni_kit\n\n # 링크 확인\n result, nucleus_server = find_nucleus_server()\n if result is False:\n carb.log_error(\n \"Could not find nucleus server with /Isaac folder. Please specify the correct nucleus server in experiences/isaac-sim-python.json\"\n )\n return\n\n # 변수 설정\n self.tile_size = [25.0, 25.0]\n\n # 1=UP, 2 = DOWN, 3 = LEFT, 4= RIGHT\n self.direction_map = {1: 180, 2: 0, 3: -90, 4: 90}\n\n self.prims = [] # list of spawned tiles\n self.height = z_height # height of the ground tiles\n self.tiles = None\n self.state = None\n # because the ground plane is what the robot drives on, we only do this once. We can then re-generate the road as often as we need without impacting physics\n self.setup_physics()\n self.road_map = None\n self.road_path_helper = None\n\n self.omni_kit.create_prim(\"/World/Floor\", \"Xform\")\n\n # cube 생성\n stage = omni.usd.get_context().get_stage()\n cubeGeom = UsdGeom.Cube.Define(stage, \"/World/Floor/thefloor\")\n cubeGeom.CreateSizeAttr(300)\n offset = Gf.Vec3f(75, 75, -150.1)\n cubeGeom.AddTranslateOp().Set(offset)\n\n # 환경 load\n # In manual mode, user can control when scene randomization occur whereas in non-manual mode scene randomization is controlled via the duration parameter in various DR components.\n self.dr = DomainRandomization()\n self.dr.toggle_manual_mode()\n self.omni_kit.update(1 / 60.0)\n print(\"waiting for materials to load...\")\n\n while self.omni_kit.is_loading():\n self.omni_kit.update(1 / 60.0)\n\n # Create a sphere room so the world is not black\n lights = []\n for i in range(5):\n prim_path = \"/World/Lights/light_\" + str(i)\n self.omni_kit.create_prim(\n prim_path,\n \"SphereLight\",\n translation=(0, 0, 200),\n rotation=(0, 0, 0),\n attributes={\"radius\": 10, \"intensity\": 1000.0, \"color\": (1.0, 1.0, 1.0)},\n )\n lights.append(prim_path)\n\n self.dr.create_light_comp(light_paths=lights)\n self.dr.create_movement_comp(prim_paths=lights, min_range=(0, 0, 30), max_range=(150, 150, 30))\n\n def generate_lights(self):\n prim_path = omni.kit.utils.get_stage_next_free_path(self.omni_kit.get_stage(), \"/World/Env/Light\", False)\n self.omni_kit.create_prim(\n prim_path,\n \"RectLight\",\n translation=(75, 75, 100),\n rotation=(0, 0, 0),\n attributes={\"height\": 150, \"width\": 150, \"intensity\": 2000.0, \"color\": (1.0, 1.0, 1.0)},\n )\n\n def reset(self, shape):\n self.generate_warehouse(shape)\n self.dr.randomize_once() # scene을 randomize한다는데 무슨 의미인지 확인해야 함\n\n def generate_warehouse(self, shape):\n stage = self.omni_kit.get_stage()\n result, nucleus_server = find_nucleus_server()\n if result is False:\n carb.log_error(\"Could not find nucleus server with /Isaac folder\")\n return\n\n path = nucleus_server + \"/Isaac/Environments/Simple_Warehouse/warehouse.usd\"\n prefix = \"/World/Env/Track\"\n prim_path = omni.kit.utils.get_stage_next_free_path(stage, prefix, False)\n track_prim = stage.DefinePrim(prim_path, \"Xform\")\n track_prim.GetReferences().AddReference(path)\n\n def setup_physics(self):\n stage = self.omni_kit.get_stage()\n # Add physics scene\n scene = PhysicsSchema.PhysicsScene.Define(stage, Sdf.Path(\"/World/Env/PhysicsScene\"))\n # Set gravity vector\n scene.CreateGravityAttr().Set(Gf.Vec3f(0.0, 0.0, -981.0))\n # Set physics scene to use cpu physics\n PhysxSchema.PhysxSceneAPI.Apply(stage.GetPrimAtPath(\"/World/Env/PhysicsScene\"))\n physxSceneAPI = PhysxSchema.PhysxSceneAPI.Get(stage, \"/World/Env/PhysicsScene\")\n physxSceneAPI.CreatePhysxSceneEnableCCDAttr(True)\n physxSceneAPI.CreatePhysxSceneEnableStabilizationAttr(True)\n physxSceneAPI.CreatePhysxSceneEnableGPUDynamicsAttr(False)\n physxSceneAPI.CreatePhysxSceneBroadphaseTypeAttr(\"MBP\")\n physxSceneAPI.CreatePhysxSceneSolverTypeAttr(\"TGS\")\n # Create physics plane for the ground\n PhysicsSchemaTools.addGroundPlane(\n stage, \"/World/Env/GroundPlane\", \"Z\", 100.0, Gf.Vec3f(0, 0, self.height), Gf.Vec3f(1.0)\n )\n # Hide the visual geometry\n imageable = UsdGeom.Imageable(stage.GetPrimAtPath(\"/World/Env/GroundPlane/geom\"))\n if imageable:\n imageable.MakeInvisible()\n\n # def get_valid_location(self): #### 수정\n # # keep try until within the center track\n # dist = 1\n # x = 4\n # y = 4\n # while dist > LANE_WIDTH:\n # x = random.randint(0, TRACK_DIMS[0])\n # y = random.randint(0, TRACK_DIMS[1])\n # dist = center_line_dist(np.array([x, y]))\n #\n # print(\"get valid location called\", x, y)\n # return (x, y)\n","sub_path":"Isaacsim_WarehouseEnv/warehouse_environment.py","file_name":"warehouse_environment.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"388380995","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) \\\n Chrome/49.0.2623.87 Safari/537.36'\n}\n\n\ndef get_item_link(who_sells):\n start_url = 'http://bj.58.com/pbdn/{}/'.format(who_sells)\n item_links = []\n web_data = requests.get(start_url, headers=headers)\n soup = BeautifulSoup(web_data.text, 'lxml')\n time.sleep(1)\n links = soup.select('td.t a.t')\n for link in links:\n item_url = link.get('href').split('?')[0]\n # if 'jump' and 'jing' and 'zhuanzhuan' not in item_url:\n if 'jump' not in item_url and 'jing' not in item_url and 'zhuanzhuan' not in item_url:\n # print(item_url)\n item_links.append(item_url)\n return item_links\n\n\ndef get_item_info(who_sells=0):\n item_links = get_item_link(who_sells)\n for link in item_links:\n web_data = requests.get(link, headers=headers)\n time.sleep(1)\n soup = BeautifulSoup(web_data.text, 'lxml')\n # seller_mark = link.split('/')[-1]\n cate = soup.select('.crb_i a')[1].text\n title = soup.select('#content h1')[0].text\n date = soup.select('li.time')[0].text\n price = soup.select('span.price')[0].text\n position = list(soup.select('span.c_25d')[0].stripped_strings) if soup.find_all('span', 'c_25d') else None\n data = {\n 'cate': cate,\n 'title': title,\n 'date': date,\n 'price': price,\n 'position': position,\n 'views': get_views(link),\n 'seller': '个人' if who_sells == 0 else '商家'\n }\n print(data)\n\n\ndef get_views(link):\n url = 'http://jst1.58.com/counter?infoid={}'.format(link.strip('x.shtml').split('/')[-1])\n web_data = requests.get(url)\n return web_data.text.split('=')[-1]\n\n\nget_item_info()\n\n# print(get_views('http://bj.58.com/pingbandiannao/25481834511792x.shtml'))\n\n","sub_path":"homework_follow/week1/week1_homework.py","file_name":"week1_homework.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"228289993","text":"import os\nimport re\nimport json\nimport copy\nimport string\nimport time\nfrom bs4 import BeautifulSoup\n\nDATA_PATH = './ECT/'\nDEBUG = False\n\n# Assign variables for keys to avoid hard-coding and possible bugs if any key is changed\n\nDATE = 'Date'\nPARTICIPANTS = 'Participants'\nPRESENTATION = 'Presentation'\nQUESTIONNAIRE = 'Questionnaire'\n\n''' Sorting function to sort input files in lexicographically increasing order '''\n\n\ndef sortKey(s):\n return int(s.split('-')[0])\n\n\nfiles = os.listdir(DATA_PATH)\nfiles.sort(key=sortKey)\ntotal_files = len(files)\n\n''' Replace some unicode characters with ASCII equivalent in the .json files '''\n\n\ndef replace_unicode(response):\n response = re.sub(u\"(\\u2018|\\u2019)\", \"'\", response)\n response = re.sub(u\"(\\u2013|\\u2014)\", \"-\", response)\n response = re.sub(u\"(\\u2026)\", \"...\", response)\n return response\n\n\n''' Extracts the date mentioned in the html file using Regex matching '''\n\n\ndef populate_dates(soup, data_dict):\n\n months = ['January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December']\n paragraphs = soup.find_all('p', {'class': 'p'})\n\n for loop in range(min(5, len(paragraphs))):\n para = paragraphs[loop].text\n # Remove possible multiple spaces\n para = ' '.join(para.split())\n tokens = para.split()\n found = False\n for month in months:\n if month in tokens:\n pattern = month + r' [0-9]{1,2}, [1-9][0-9]{1,3}'\n result = re.search(pattern, para)\n if result:\n found = True\n data_dict[DATE] = result.group(0)\n assert data_dict[DATE] in para\n break\n if found:\n break\n\n\n# An auxiliary list which stores only the names of the participants \\\n# Used for easy checking a participant while building Presentations and Questionnaire\nparticipant_names = []\n\n''' Extract the Participants from the paragraph elements containing the name '''\n\n\ndef add_participant_category(pos, paragraphs, data_dict):\n new_added = 0\n for idx in range(pos + 1, len(paragraphs)):\n text = ''\n try:\n # Check for elements inside span\n element = paragraphs[idx].contents[0].contents[0]\n text = paragraphs[idx].get_text()\n except AttributeError:\n text = paragraphs[idx].get_text()\n if text == \" \":\n continue\n text = text.replace('–', '-')\n if '-' in text:\n first_name = text.split(' - ')[0].strip()\n name = text.strip()\n if len(name) <= 200:\n name = replace_unicode(name)\n first_name = replace_unicode(first_name)\n participant_names.append(first_name)\n data_dict[PARTICIPANTS].append(name)\n new_added = new_added + 1\n else:\n break\n return new_added\n\n\n''' Populate the list of participants belonging to different categories '''\n\n\ndef populate_participants(soup, data_dict):\n\n data_dict[PARTICIPANTS] = []\n paragraphs = soup.find_all('p')\n\n # Mark the starting index for the next task\n last_participant_pos = 0\n\n for idx in range(len(paragraphs)):\n text = paragraphs[idx].text\n if type(text) != str: # span tag exists\n text = paragraphs[idx].contents[0].text.strip()\n else:\n text = text.strip()\n\n text = text.lower()\n\n if text == 'company participants':\n last_participant_pos = idx + \\\n add_participant_category(idx, paragraphs, data_dict)\n if text == 'conference call participants':\n last_participant_pos = idx + \\\n add_participant_category(idx, paragraphs, data_dict)\n if text == 'corporate participants':\n last_participant_pos = idx + \\\n add_participant_category(idx, paragraphs, data_dict)\n if text == 'company representatives':\n last_participant_pos = idx + \\\n add_participant_category(idx, paragraphs, data_dict)\n if text == 'executives':\n last_participant_pos = idx + \\\n add_participant_category(idx, paragraphs, data_dict)\n if text == 'analysts':\n last_participant_pos = idx + \\\n add_participant_category(idx, paragraphs, data_dict)\n\n return last_participant_pos\n\n\n''' Populate the Presentations key in the dictionary using the list of participants calculated previously '''\n\n\ndef populate_presentations(start, soup, data_dict, counter, participants):\n data_dict[PRESENTATION] = {}\n paragraphs = soup.find_all('p')\n\n # Add anonymous names\n participants.append('Operator')\n participants.append('operator')\n participants.append('Unidentified Analyst')\n participants.append('Unidentified Company Representative')\n\n name = ''\n nested_name = ''\n taking_inline = True\n taking_nested = False\n\n # Start from the ending of participants section (pointed by start)\n for idx in range(start + 1, len(paragraphs)):\n para = paragraphs[idx]\n # Filter start of QnA section\n if para.has_attr('id'):\n break\n if para.get_text() == 'Question-and-Answer Session': # Filter start of QnA section\n break\n if len(para.contents) < 1: # Filter tags like

\n continue\n # Check if the tag is a name or dialogue\n try:\n element = para.contents[0].contents[0]\n name = para.get_text().strip()\n if name == 'Question-and-Answer Session':\n break\n try:\n element = element.contents[0]\n nested_name = para.get_text().strip()\n nested_name = replace_unicode(nested_name)\n taking_inline = False\n taking_nested = True\n if nested_name not in data_dict[PRESENTATION].keys() and nested_name in participants:\n data_dict[PRESENTATION][nested_name] = []\n except AttributeError:\n dialogue = para.get_text()\n dialogue = replace_unicode(dialogue)\n if nested_name != '' and dialogue != \" \" and taking_nested and nested_name in participants:\n data_dict[PRESENTATION][nested_name].append(dialogue)\n name = replace_unicode(name)\n if name not in data_dict[PRESENTATION].keys() and taking_inline and name in participants:\n data_dict[PRESENTATION][name] = []\n taking_nested = False\n except AttributeError:\n dialogue = para.get_text()\n dialogue = replace_unicode(dialogue)\n if name != '' and dialogue != \" \" and taking_inline and name in participants:\n data_dict[PRESENTATION][name].append(dialogue)\n except IndexError:\n continue\n\n\n''' Build the Questionnaire key in the dictionary using the list of participants '''\n\n\ndef build_questionnaire(soup, data_dict, counter, participants):\n data_dict[QUESTIONNAIRE] = {}\n paragraphs = soup.find_all('strong')\n\n # Add anonymous names\n participants.append('Operator')\n participants.append('operator')\n participants.append('Unidentified Analyst')\n participants.append('Unidentified Company Representative')\n\n qNa_started = False\n\n position = 1\n\n for para in paragraphs:\n name = para.get_text().strip()\n if 'Question-and' in name or 'Question-' in name:\n qNa_started = True\n continue\n\n if not qNa_started:\n continue\n\n person = \"\"\n if name in participants:\n person = name\n elif len(name.split('-')) > 1:\n splits = name.split('-')\n splits[0] = splits[0].strip()\n splits[1] = splits[1].strip()\n if splits[0] in participants:\n person = splits[0]\n if splits[1] in participants:\n person = splits[1]\n\n person = person.strip()\n if person == \"\" or person == \" \" or name == None:\n continue\n\n para_parent = para.parent\n response = \"\"\n\n for sibling in para_parent.next_siblings:\n if sibling.name == None:\n continue\n children = sibling.find_all('strong', recursive=False)\n if sibling.get_text() == \" \":\n continue\n if len(children):\n break\n response += str(sibling.get_text()) + '\\n'\n\n person = replace_unicode(person)\n response = replace_unicode(response)\n\n data_dict[QUESTIONNAIRE][position] = {\n 'Speaker': person,\n 'Remark': response\n }\n\n position += 1\n\n\n''' Helper functions to write different keys of the Nested Dictionary to respective .txt files'''\n\n\ndef write_date(value):\n\n text = DATE + '\\n'\n text += value\n text += '\\n'\n return text\n\n\ndef write_participants(list_of_participants):\n\n text = PARTICIPANTS + '\\n'\n\n for name in list_of_participants:\n text += name\n text += '\\n'\n\n return text\n\n\ndef write_presentation(presentations):\n\n text = PRESENTATION + '\\n'\n\n for key, value in presentations.items():\n text += key + '\\n'\n for dialogue in value:\n text += dialogue + '\\n'\n\n return text\n\n\ndef write_questionnaire(questionnaire):\n\n text = QUESTIONNAIRE + '\\n'\n\n for key, value in questionnaire.items():\n text += str(key) + '\\n'\n speaker = value['Speaker']\n text += speaker + '\\n'\n remark = value['Remark']\n text += remark + '\\n'\n\n return text\n\n\n''' Wrapper function to write the Dictioary 'data_dict' to the corresponding .txt files '''\n\n\ndef build_textCorpus(soup, data_dict):\n\n text = ''\n if DATE in data_dict.keys():\n text += write_date(data_dict[DATE])\n text += write_participants(data_dict[PARTICIPANTS])\n text += write_presentation(data_dict[PRESENTATION])\n text += write_questionnaire(data_dict[QUESTIONNAIRE])\n\n return text\n\n\n''' Driver function which builds the Nested Dictionary and ECTText file for each html file '''\n\n\ndef build_ECTNestedDict():\n\n if not os.path.exists('ECTNestedDict'):\n os.makedirs('ECTNestedDict')\n\n if not os.path.exists('ECTText'):\n os.makedirs('ECTText')\n\n file_num = 0\n\n for file in files:\n data_dict = {}\n abs_path = os.path.abspath(os.path.join(DATA_PATH, file))\n soup = BeautifulSoup(open(abs_path), \"html.parser\")\n\n # Counter for debugging purposes\n counter = re.match(r'[0-9]{1,4}', file).group(0)\n counter = (int)(counter)\n\n populate_dates(soup, data_dict)\n last_participant_pos = populate_participants(soup, data_dict)\n participants = copy.deepcopy(participant_names)\n\n populate_presentations(last_participant_pos, soup,\n data_dict, counter, participants)\n build_questionnaire(soup, data_dict, counter, participants)\n\n text_file = build_textCorpus(soup, data_dict)\n\n out_json_file = os.path.join(\n 'ECTNestedDict', str(file_num) + '.json')\n\n out_text_file = os.path.join(\n 'ECTText', str(file_num) + '.txt')\n\n with open(out_json_file, 'w') as outFile:\n json.dump(data_dict, outFile)\n\n with open(out_text_file, 'w') as outFile:\n outFile.write(text_file)\n\n file_num = file_num + 1\n if DEBUG and file_num % 100 == 0:\n print('ECTNestedDict - Steps done: {}'.format(file_num))\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n build_ECTNestedDict()\n if DEBUG:\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"Assignment-1/ASSIGNMENT1_17EC10063_2.py","file_name":"ASSIGNMENT1_17EC10063_2.py","file_ext":"py","file_size_in_byte":11855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"501899234","text":"# with\n# 传统写法\n# file = open('english_ascii.txt','r')\n# content = file.read()\n# print(content)\n# file.close()\n# 传统写法缺点 每一次要记得打开关闭文件,跟try except连用时结构不太清晰。\n\n# with\nwith open('chinese_utf8.txt','r',encoding='utf8')as f:\n # f.__enter__() # 文件打开的预处理\n content = f.read()\n print(content)\n # f.__exit__() #对象结束后的操作,例如 f.close()\n\n\n\"\"\"\nwith:with语句要求后面跟的对象实现 进入方法__enter__() 退出方法__exit__()\nas:把...当做...。跟等号相似。\n场景:一项任务有固定的预处理和退出处理,把这些任务的实现代码封装到__enter__() __exit__()中,这样在with语句块中只用写主要的业务逻辑,代码更加清晰。\n\"\"\"\n\n\n# file = open('write.txt', 'w', encoding='utf-8')\n# file.write('hello world')\n# file.write('小明')\n# file.write('\\n')\n# file.write('天黑的开始早了')\n\n# file.writelines(['第一行','second line','第三行'])\n\n","sub_path":"L7本地文件读写/5with语句.py","file_name":"5with语句.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"470316916","text":"from nltk import word_tokenize, sent_tokenize\n\n\nclass SentenceFilter:\n\n def __init__(self,text):\n self.text = text\n self.logic_sentences = []\n self.description_sentences = []\n\n def filter_sentences(self):\n conditional_conjunctions = ['because', 'before', 'but', 'even if', 'if', 'if only', 'once', 'only if','only','at least'\n 'on the condition that', 'provided' , 'since', 'therefore', 'unless',\n 'until', 'when', 'then']\n tokenized_sentences = [token for token in sent_tokenize(self.text)]\n # print(tokenized_sentences)\n\n for sent in tokenized_sentences:\n lower_sent = sent.lower()\n #print(sent)\n for word in conditional_conjunctions:\n if word in word_tokenize(lower_sent):\n self.logic_sentences.append(sent)\n break\n\n self.description_sentences = list(set(tokenized_sentences) - set(self.logic_sentences))\n print(\"Description:\",self.description_sentences)\n print(\"Logic:\", self.logic_sentences)\n\n","sub_path":"com-logic/src/SentenceFilter.py","file_name":"SentenceFilter.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"424711172","text":"import sys\nfrom PyQt5.QtWidgets import QApplication\nfrom mainWindow import MainWindow\n\ndef main(argv):\n app = QApplication(argv)\n w = MainWindow()\n w.show()\n sys.exit(app.exec())\n\nif __name__==\"__main__\":\n main(sys.argv)","sub_path":"example/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"10125097","text":"# imports\nimport random\nimport copy\nimport csv\n\n# parameters\npopulationCount = int(input(\"What is the population size? \"))\nupperBound = float(input(\"What is the upper bound of each gene? \"))\nlowerBound = float(input(\"What is the lower bound of each gene? \"))\ngeneCount = int(input(\"What is the length of the genes? \"))\nmutationRate = float(input(\"What is the mutation rate? (%) \")) / 100\nmaxMutation = float(input(\"What is the maximum mutation change (0.0-1.0) \"))\nnumberOfGenerations = input(\"How many generations would you like this to run for? \")\n\n\n# define Individual class\nclass Individual:\n gene = []\n fitness = 0\n\n\npopulation = []\n\n\ndef get_fittest(pop):\n current_best = pop[0]\n for j in range(len(pop)):\n if pop[j].fitness > current_best.fitness:\n current_best = pop[j]\n return current_best.fitness\n\n\ndef single_point_crossover(pop):\n for j in range(0, len(pop), 2):\n crossoverPoint = random.randint(0, geneCount)\n offspring1Genes = pop[j].gene\n offspring2Genes = pop[j + 1].gene\n\n swapGene1 = offspring1Genes[crossoverPoint:]\n keepGene1 = offspring1Genes[:crossoverPoint]\n\n swapGene2 = offspring2Genes[crossoverPoint:]\n keepGene2 = offspring2Genes[:crossoverPoint]\n\n newGene1 = keepGene1 + swapGene2\n newGene2 = keepGene2 + swapGene1\n\n pop[j].gene = newGene1\n pop[j + 1].gene = newGene2\n return pop\n\n\ndef create_offspring(pop):\n offspring = []\n for j in range(0, populationCount):\n parent1 = random.randint(0, populationCount - 1)\n offspring1 = pop[parent1]\n parent2 = random.randint(0, populationCount - 1)\n offspring2 = pop[parent2]\n if offspring1.fitness > offspring2.fitness:\n offspring.append(offspring1)\n else:\n offspring.append(offspring2)\n return offspring\n\n\ndef generate_fitness(pop):\n for k in range(populationCount):\n for j in range(0, geneCount):\n pop[k].fitness += pop[k].gene[j]\n\ndef calculate_fitness(pop):\n total_fitness = 0\n for count in range(len(pop)):\n total_fitness += pop[count].fitness\n return total_fitness\n\n\ndef bitwise_mutation(pop):\n mutatedPop = []\n for k in range(0, populationCount):\n newind = Individual()\n newind.gene = []\n for j in range(0, geneCount):\n gene = pop[k].gene[j]\n mutprob = random.randint(0, 100)\n if mutprob < (100 * mutationRate):\n alter = random.uniform(0, maxMutation)\n if random.randint(0, 2):\n if gene + alter > upperBound:\n gene = upperBound\n else:\n gene += alter\n else:\n if gene - alter < lowerBound:\n gene = lowerBound\n else:\n gene -= alter\n newind.gene.append(gene)\n mutatedPop.append(newind)\n return mutatedPop\n\n\ndef calculate_average_fitness(pop):\n total_fitness = 0\n for count in range(len(pop)):\n total_fitness += pop[count].fitness\n avg_fitness = total_fitness / len(pop)\n return avg_fitness\n\n\n# setup population with genes and fitnesses\nfor x in range(0, populationCount):\n tempGene = []\n for i in range(0, geneCount):\n tempGene.append(random.uniform(lowerBound, upperBound))\n newind = Individual()\n newind.gene = tempGene.copy()\n\n fitness = 0\n for i in range(0, geneCount):\n fitness += newind.gene[i]\n \n newind.fitness = fitness\n\n population.append(newind)\n\noffspring = create_offspring(population)\n\nwith open ('maximisation.csv', 'w') as maximisation:\n maximisationWriter = csv.writer(maximisation)\n\n maximisationWriter.writerow(['Generation No.', 'Fittest Individual', 'Average Fitness'])\n\n for i in range(int(numberOfGenerations)):\n offspring = copy.deepcopy(create_offspring(population))\n offspring = copy.deepcopy(single_point_crossover(offspring))\n mutatedPop = copy.deepcopy(bitwise_mutation(offspring))\n generate_fitness(mutatedPop)\n\n mutationFitness = calculate_fitness(mutatedPop)\n bestInGeneration = get_fittest(mutatedPop)\n avgMutatedFitness = calculate_average_fitness(mutatedPop)\n\n population = copy.deepcopy(mutatedPop)\n\n maximisationWriter.writerow([i + 1, bestInGeneration, avgMutatedFitness])\n\n print(\"\\n---- Generation \" + str(i + 1) + \" ----\")\n print(\"Total Fitness: \" + str(mutationFitness))\n print(\"Fittest Individual: \" + str(bestInGeneration))\n print(\"Average Fitness: \" + str(avgMutatedFitness))\n\nmaximisation.close()\n","sub_path":"maximisation.py","file_name":"maximisation.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"563521544","text":"# -*- coding: utf-8 -*-\n\"\"\"\nfiledesc: Module for extending webob Request and Response classes\n\"\"\"\n# to use in our server application\nimport json\n\nimport webob\nfrom mako.template import Template\nfrom noodles.utils.datahandler import datahandler\nfrom noodles.utils.logger import log\nfrom config import EXCEPTION_FLAVOR\n\nSET_COOKIES = '__set_cookies'\nUNSET_COOKIES = '__unset_cookies'\n\n\nclass Request(webob.Request):\n \" Request object wrapper fo adding session handling and other features \"\n def __init__(self, env):\n super(Request, self).__init__(env)\n\n\nclass BaseResponse(webob.Response):\n \" Just wrapper, may be implemnt cookies there, may be somthing else )) \"\n is_noodles_response = True # for check if it really noodles response\n\n\nclass Response(BaseResponse):\n \" Simple response class with 200 http header status \"\n def __init__(self, body=''):\n super(Response, self).__init__()\n # Set standard response attributes\n self.status = 200 # 200 OK, it's default, but anyway...\n self.headerlist = [('Content-type', 'text/html')]\n self.charset = 'utf-8'\n self.text = body\n\n\nclass XMLResponse(Response):\n \"\"\"Simple response class with 200 http header status\n \"\"\"\n def __init__(self, body=''):\n super(XMLResponse, self).__init__(body)\n self.headerlist = [('Content-type', 'text/xml')]\n\n\nclass Redirect(BaseResponse):\n \" Redirect response \"\n def __init__(self, redirect_url, cookie_dict=None):\n super(Redirect, self).__init__()\n self.status = 302\n self.headerlist = [('Content-type', 'text/html')]\n self.charset = 'utf-8'\n #TODO: serg\n if cookie_dict:\n for cookie in cookie_dict:\n self.set_cookie(str(cookie), str(cookie_dict.get(cookie)))\n self.location = redirect_url\n\n\nclass Error403(BaseResponse):\n \" Simple Http 403 error implementation \"\n def __init__(self, error_body=''):\n super(Error403, self).__init__()\n self.status = 403\n self.headerlist = [('Content-type', 'text/html')]\n self.charset = 'utf-8'\n self.text = error_body\n\n\nclass Error404(BaseResponse):\n \" Simple Http 404 error implementation \"\n def __init__(self, error_body=''):\n super(Error404, self).__init__()\n self.status = 404\n self.headerlist = [('Content-type', 'text/html')]\n self.charset = 'utf-8'\n self.text = error_body\n\n\nclass Error500(BaseResponse):\n \"\"\"\n HTTP 500 error response with server traceback if DEBUG\n \"\"\"\n def __init__(self, ex=None, tb=None):\n super(Error500, self).__init__()\n self.status = 500\n self.headerlist = [('Content-type', 'text/html')]\n self.charset = 'utf-8'\n if tb:\n if EXCEPTION_FLAVOR=='html':\n tb = '
'.join(tb.split('\\n'))\n else:\n tb = \"Please, load this page later\"\n if ex:\n ex = ex.__repr__()\n else:\n ex = \"Sorry, an error occured\"\n if EXCEPTION_FLAVOR=='html':\n error_500_template = \"\"\"\n

500 error

\n
\n ${ex}\n
\n\n
\n ${tb}\n
\n \"\"\"\n elif EXCEPTION_FLAVOR=='text':\n error_500_template='\\n\\n\\n'.join([\"500 error\",\n \"${ex}\",\n \"${tb}\"])\n if EXCEPTION_FLAVOR=='text':\n self.headerlist.append(('Content-type','text/plain'))\n self.body = Template(error_500_template).render(ex=ex.__repr__(),\n tb=tb).encode('utf-8')\n\n\nclass XResponse(BaseResponse):\n \" Ajax response, return a JSON object \"\n def __init__(self, response_dict):\n # Set standard response attributes\n super(XResponse, self).__init__()\n self.status = 200 # 200 OK, it's default, but anyway...\n self.headerlist = [('Content-type', 'application/x-javascript')]\n self.charset = 'utf-8'\n\n # Set and unset cookies\n # Set cookies\n\n try:\n set_cookies_dict = response_dict.get(SET_COOKIES)\n except:\n raise\n\n log.debug('response_dict2 is %s. Set-cookies dict is %s'\n % (response_dict, set_cookies_dict))\n if set_cookies_dict:\n for cookie in set_cookies_dict:\n log.debug('Try to set cookie %s to value %s'\n % (cookie, set_cookies_dict[cookie]))\n self.set_cookie(cookie, str(set_cookies_dict[cookie]))\n response_dict.pop(SET_COOKIES)\n\n # Unset cookies\n unset_cookies_dict = response_dict.get(UNSET_COOKIES)\n if unset_cookies_dict:\n for cookie in unset_cookies_dict:\n self.delete_cookie(cookie)\n response_dict.pop(UNSET_COOKIES)\n self.text = json.dumps(response_dict, default=datahandler,indent=True,sort_keys=True)\n\n\n# Specify decorator for ajax response controller functions\n# Usage:\n#\n# @ajax_response\n# def some_controller(request):\n# # some code\n# return resonse_dict # dictionary object with response values\ndef ajax_response(func):\n def gen(**kwargs):\n resp_dict = func(**kwargs)\n return XResponse(resp_dict)\n return gen\n","sub_path":"http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"51294662","text":"#!/usr/bin/env python\n# coding=utf8\nfrom __future__ import absolute_import\nimport json\nimport six\nfrom . import result_aggregators as ra\nfrom .annospan import SpanGroup\n\n\nclass AnnoTier(object):\n \"\"\"\n A group of AnnoSpans stored sorted by start offset.\n \"\"\"\n def __init__(self, spans=None):\n if spans is None:\n self.spans = []\n elif isinstance(spans, AnnoTier):\n self.spans = list(spans.spans)\n else:\n self.spans = sorted(spans)\n\n def __repr__(self):\n return ('AnnoTier([' +\n ', '.join([six.text_type(span) for span in self.spans]) +\n '])')\n\n def __len__(self):\n return len(self.spans)\n\n def __add__(self, other_tier):\n return AnnoTier(self.spans + other_tier.spans)\n\n def __iter__(self):\n return iter(self.spans)\n\n def to_json(self):\n docless_spans = []\n for span in self.spans:\n span_dict = span.__dict__.copy()\n del span_dict['doc']\n docless_spans.append(span_dict)\n return json.dumps(docless_spans)\n\n def group_spans_by_containing_span(self,\n other_tier,\n allow_partial_containment=False):\n \"\"\"\n Group spans in the other tier by the spans that contain them.\n\n >>> from .annospan import AnnoSpan\n >>> from .annodoc import AnnoDoc\n >>> doc = AnnoDoc('one two three')\n >>> tier_a = AnnoTier([AnnoSpan(0, 3, doc), AnnoSpan(4, 7, doc)])\n >>> tier_b = AnnoTier([AnnoSpan(0, 1, doc)])\n >>> list(tier_a.group_spans_by_containing_span(tier_b))\n [(0-3:one, [0-1:o]), (4-7:two, [])]\n \"\"\"\n if isinstance(other_tier, AnnoTier):\n other_spans = other_tier.spans\n else:\n other_spans = sorted(other_tier)\n other_spans_idx = 0\n for span in self.spans:\n span_group = []\n # iterate over the other spans that come before this span.\n while other_spans_idx < len(other_spans):\n if allow_partial_containment:\n if other_spans[other_spans_idx].end > span.start:\n break\n else:\n if other_spans[other_spans_idx].start >= span.start:\n break\n other_spans_idx += 1\n other_span_idx_2 = other_spans_idx\n while other_span_idx_2 < len(other_spans):\n if other_spans[other_span_idx_2].start >= span.end:\n break\n if not allow_partial_containment:\n # Skip the other span if it is not contained by this span.\n # It is possible there is another shorter span that starts\n # after it and is fully contained by this span.\n if other_spans[other_span_idx_2].end > span.end:\n other_span_idx_2 += 1\n continue\n span_group.append(other_spans[other_span_idx_2])\n other_span_idx_2 += 1\n yield span, span_group\n\n def with_label(self, label):\n \"\"\"\n Create a tier from the spans which have the given label\n\n >>> from .annospan import AnnoSpan\n >>> from .annodoc import AnnoDoc\n >>> doc = AnnoDoc('one two three')\n >>> tier = AnnoTier([AnnoSpan(0, 3, doc, 'odd'),\n ... AnnoSpan(4, 7, doc, 'even'),\n ... AnnoSpan(8, 13, doc, 'odd')])\n >>> tier.with_label(\"odd\")\n AnnoTier([0-3:odd, 8-13:odd])\n \"\"\"\n return AnnoTier([span for span in self if span.label == label])\n\n def optimal_span_set(self, prefer=\"text_length\"):\n \"\"\"\n Create a tier with the set of non-overlapping spans from this tier that\n maximizes the prefer function.\n\n >>> from .annospan import AnnoSpan\n >>> from .annodoc import AnnoDoc\n >>> doc = AnnoDoc('one two three')\n >>> tier = AnnoTier([AnnoSpan(0, 3, doc, 'odd'),\n ... AnnoSpan(4, 7, doc, 'even'),\n ... AnnoSpan(3, 13, doc, 'long_span'),\n ... AnnoSpan(8, 13, doc, 'odd')])\n >>> tier.optimal_span_set()\n AnnoTier([0-3:odd, 3-13:long_span])\n \"\"\"\n return AnnoTier(ra.combine([self.spans], prefer=prefer))\n\n def without_overlaps(self, other_tier):\n \"\"\"\n Create a copy of this tier without spans that overlap a span in the\n other tier.\n \"\"\"\n span_groups = self.group_spans_by_containing_span(other_tier,\n allow_partial_containment=True)\n result = []\n for span, group in span_groups:\n if len(group) == 0:\n result.append(span)\n return AnnoTier(result)\n\n def with_contained_spans_from(self, other_tier, allow_partial_containment=False):\n \"\"\"\n Create a new tier from pairs spans in this tier and the other tier\n where the span in this tier contains one in the other tier.\n \"\"\"\n span_groups = self.group_spans_by_containing_span(other_tier,\n allow_partial_containment=allow_partial_containment)\n result = []\n for span, group in span_groups:\n for other_span in group:\n result.append(SpanGroup([span, other_span]))\n return AnnoTier(result)\n\n def with_nearby_spans_from(self, other_tier, max_dist=100):\n \"\"\"\n Create a new tier from pairs spans in this tier and the other tier\n that are near eachother.\n \"\"\"\n return AnnoTier(ra.near([self, other_tier], max_dist=max_dist))\n\n def combined_adjacent_spans(self, max_dist=1):\n \"\"\"\n Create a new tier from groups of spans within max_dist of eachother.\n\n >>> from .annospan import AnnoSpan\n >>> from .annodoc import AnnoDoc\n >>> doc = AnnoDoc('one two three four')\n >>> tier = AnnoTier([AnnoSpan(0, 3, doc),\n ... AnnoSpan(8, 13, doc),\n ... AnnoSpan(14, 18, doc)])\n >>> tier.combined_adjacent_spans()\n AnnoTier([SpanGroup(text=one, label=None, 0-3:one), SpanGroup(text=three four, label=None, 8-13:three, 14-18:four)])\n \"\"\"\n prev_span = None\n span_groups = []\n span_group = None\n for span in self:\n if not prev_span:\n span_group = [span]\n elif prev_span.end + max_dist >= span.start:\n span_group.append(span)\n else:\n span_groups.append(SpanGroup(span_group))\n span_group = [span]\n prev_span = span\n if span_group:\n span_groups.append(SpanGroup(span_group))\n return AnnoTier(span_groups)\n","sub_path":"epitator/annotier.py","file_name":"annotier.py","file_ext":"py","file_size_in_byte":6934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"572323896","text":"import sys\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = []\ny = []\nwith open(sys.argv[1]) as f:\n\tfor line in f.readlines():\n\t\tsplt = line.split()\n\t\tx.append(int(splt[0]))\n\t\ty.append(int(splt[1]))\nx.append(x[0])\ny.append(y[0])\n\nnpx = np.array(x)\nnpy = np.array(y)\n\nplt.plot(npx,npy)\nplt.show()\n","sub_path":"dealpts.py","file_name":"dealpts.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"251221100","text":"# -*- coding:utf-8 -*-\n\"\"\"\n作者:86173\n日期:2021年09月27日\n\"\"\"\n\nimport random\nfrom collections import defaultdict, Counter\nfrom datetime import datetime\nfrom functools import reduce\nimport numpy as np\nfrom math import sqrt\n\ng_dataset = {} # dataset数据集\ng_test_good = {}\ng_test_bad = {}\nNUM_ROWS = 32 # 行数\nNUM_COLS = 32 # 列数\nDATA_TRAINING = 'digit-training.txt'\nDATA_TESTING = 'digit-testing.txt'\nDATA_PREDICT = 'digit-predict.txt'\n\n# kNN parameter 参数\nKNN_NEIGHBOR = 7\n\n\n##########################\n##### Load Data #########\n##########################\n\n# Convert next digit from input file as a vector 将输入文件中的下一个数字转换为矢量\n# Return (digit, vector) or (-1, '') on end of file 在文件末尾返回(数字,向量)或(-1, '')\ndef read_digit(p_fp):\n # read entire digit (inlude linefeeds) 读取整个数字(包括换行符)\n bits = p_fp.read(NUM_ROWS * (NUM_COLS + 1))\n if bits == '':\n return -1, bits\n # convert bit string as digit vector 将位字符串转换为数字向量\n vec = [int(b) for b in bits if b != '\\n']\n val = int(p_fp.readline())\n return val, vec\n\n\n# Parse all digits from training file 解析训练文件中的所有数字\n# and store all digits (as vectors) 并存储所有数字(作为向量)\n# in dictionary g_dataset 字典中的g_dataset\ndef load_data(p_filename=DATA_TRAINING):\n global g_dataset\n # Initial each key as empty list 每个键的首字母都是空列表\n g_dataset = defaultdict(list)\n with open(p_filename) as f:\n while True:\n val, vec = read_digit(f)\n if val == -1:\n break\n g_dataset[val].append(vec)\n\n\n##########################\n##### kNN Models #########\n##########################\n\n# Given a digit vector, returns 给定一个数字向量,返回\n# the k nearest neighbor by vector distance 向量距离的k近邻\ndef knn(p_v, size=KNN_NEIGHBOR):\n nn = []\n for d, vectors in g_dataset.items():\n for v in vectors:\n dist = round(distance(p_v, v), 2)\n nn.append((dist, d))\n\n # TODO: find the nearest neigbhors 找到最近的邻居\n # 对列表nn进行排序(含有元组的列表排序方法)\n sortednn = sorted(nn, key=lambda x: x[0])\n return sortednn[0:size] # 取出前size个\n\n\n# Based on the knn Model (nearest neighhor) 基于knn模型(最近的Neighor)\n# return the target value 返回目标值\n# 基于knn模型(最近的Neighor),返回目标值\ndef knn_by_most_common(p_v):\n nn = knn(p_v)\n\n # TODO: target value 目标值\n\n \"\"\"找出nn元组列表中出现次数最多的value\n 键:值 (key:value)\"\"\"\n\n # collection_nn = Counter(nn) # Counter类排序\n d_nn = dict(nn) # 将元组列表转为字典\n target_key = max(d_nn.keys()) # 寻找最大的key\n # return target_value\n target = d_nn[target_key] # 输出最大key对应的value\n return target\n\n##########################\n##### Prediction ########\n##########################\n\n# Make prediction based on kNN model 基于kNN模型进行预测\n# Parse each digit from the predict file 解析predict文件中的每个数字\n# and print the predicted balue 并打印预测的balue\ndef predict(p_filename=DATA_PREDICT):\n # TODO\n print('TO DO: show results of prediction')\n\n # load_data(p_filename)\n # 解析predict文件中的每个数字\n with open(p_filename) as f:\n while True:\n val, vec = read_digit(f)\n if val == -1:\n break\n result = knn_by_most_common(vec) # 调用knn算法进行测试\n print(result)\n\n##########################\n##### Accuracy #########\n##########################\n\n# Compile an accuracy report by 编制一份准确度报告\n# comparing the data set with every 将数据集与每个\n# digit from the testing file 测试文件中的数字\ndef validate(p_filename=DATA_TESTING):\n global g_test_bad, g_test_good\n g_test_bad = defaultdict(int)\n g_test_good = defaultdict(int)\n\n data_by_random(100) # 为每个数据随机选择100个样本\n load_data(p_filename) # 读取数据\n list1 = []\n for v in g_dataset.values():\n a = len(v)\n list1.append(a)\n l = sum(list1) # 获取数据g_dataset.values的总值,作为进度百分号的分母\n i = 0 # 计算测试数据次数\n print('TODO: Training Info')\n for val, vecs in g_dataset.items():\n for vec in vecs:\n test_result = knn_by_most_common(vec)\n if test_result == val:\n g_test_good[val] += 1\n else:\n g_test_bad[val] += 1\n i += 1\n print(\"\\r进度:{}%\".format(round(100 * i / l, 2)), end='')\n print()\n\n # 法二:【此方法样本数较小例如10,判断速度快,同时准确率也会降低,样本为100时基本无差别】\n # data_by_random(10) # 为每个数据随机选择10个样本\n # g_data = defaultdict(list)\n # with open(p_filename) as f:\n # while True:\n # val, vec = read_digit(f)\n # if val == -1:\n # break\n # g_data[val].append(vec)\n # l = sum([len(v) for v in g_data.values()]) # 五行的简洁式\n #\n # i = 0 # 计算测试数据次数\n # print('TODO: Training Info')\n # for val, vecs in g_data.items():\n # for vec in vecs:\n # test_result = knn_by_most_common(vec)\n # if test_result == val:\n # g_test_good[val] += 1\n # else:\n # g_test_bad[val] += 1\n # i += 1\n # print(\"\\r进度:{}%\".format(round(100 * i / l, 2)), end='')\n # print()\n\n start = datetime.now()\n\n # TODO: Validate your kNN model with 使用验证kNN模型\n # digits from test file. 数据来自测试文件\n\n stop = datetime.now()\n show_test(start, stop)\n\n\n##########################\n##### Data Models ########\n##########################\n\n# Randomly select X samples for each digit 为每个数据随机选择X个样本\ndef data_by_random(size=25):\n for digit in g_dataset.keys():\n g_dataset[digit] = random.sample(g_dataset[digit], size)\n\n\n##########################\n##### Vector #########\n##########################\n\n# Return distance between vectors v & w 向量 v & w 之间的返回距离\ndef distance(v, w):\n\n \"\"\" 欧氏距离计算 \"\"\"\n\n vector1 = np.array(v)\n vector2 = np.array(w)\n op = np.linalg.norm(vector1 - vector2) # 欧氏距离计算\n return op\n\n\n##########################\n##### Report #########\n##########################\n\n# Show info for training data set 显示训练数据集的信息\ndef show_info():\n print('TODO: Training Info')\n for d in range(10):\n print(d, '=', len(g_dataset[d]))\n\n\n# Show test results 显示测试结果\ndef show_test(start=\"????\", stop=\"????\"):\n print('Beginning of Validation @ ', start) # 验证的开始@\n print('TODO: Testing Info')\n\n \"\"\"\n format格式化字符串函数 \n round()方法返回浮点数x的四舍五入值,逗��后面表示保留几位小数\n \"\"\"\n\n # result = ['KNN_NEIGHBOR={}\\n'.format(KNN_NEIGHBOR)]\n print('各数字准确率为:')\n sum = 0\n for d in range(10):\n good = g_test_good[d]\n bad = g_test_bad[d]\n accuracy = 100 * good / (good + bad) # 准确率\n # format格式化字符串函数\n # output = \"{}={} {} {}%\\n\".format(d, good, bad, round(accuracy, 2))\n # result.append(output)\n sum += accuracy\n print(str(d) + '=' + str(good) + ' ' + str(bad) + ' ' + str(round(accuracy, 2)) + '%')\n average = \"average:{}%\\n\".format(round(sum / 10, 2))\n print(average)\n print('End of Validation @ ', stop) # 验证结束@\n # result.append(average)\n # with open('准确率and平均值.txt', 'a') as f:\n # f.writelines(result)\n # 所有注释部分可把结果输出到txt文件中\n\nif __name__ == '__main__':\n load_data()\n show_info()\n validate()\n predict()\n","sub_path":"KNN-bamboo.py","file_name":"KNN-bamboo.py","file_ext":"py","file_size_in_byte":8086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"357120871","text":"from __future__ import print_function, division, absolute_import, unicode_literals\n\nfrom fontTools.misc.py23 import BytesIO\nfrom fontTools.ttLib import TTFont\nfrom ufo2ft.constants import USE_PRODUCTION_NAMES, GLYPHS_DONT_USE_PRODUCTION_NAMES\nimport logging\nimport re\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PostProcessor(object):\n \"\"\"Does some post-processing operations on a compiled OpenType font, using\n info from the source UFO where necessary.\n \"\"\"\n\n GLYPH_NAME_INVALID_CHARS = re.compile(\"[^0-9a-zA-Z_.]\")\n MAX_GLYPH_NAME_LENGTH = 63\n\n def __init__(self, otf, ufo, glyphSet=None):\n self.ufo = ufo\n self.glyphSet = glyphSet if glyphSet is not None else ufo\n stream = BytesIO()\n otf.save(stream)\n stream.seek(0)\n self.otf = TTFont(stream)\n self._postscriptNames = ufo.lib.get(\"public.postscriptNames\")\n\n def process(self, useProductionNames=None, optimizeCFF=True):\n \"\"\"\n useProductionNames:\n By default, when value is None, this will rename glyphs using the\n 'public.postscriptNames' in then UFO lib. If the mapping is not\n present, no glyph names are renamed.\n If the value is False, no glyphs are renamed whether or not the\n 'public.postscriptNames' mapping is present.\n If the value is True, but no 'public.postscriptNames' are present,\n then uniXXXX names are generated from the glyphs' unicode.\n\n The 'com.github.googlei18n.ufo2ft.useProductionNames' key can be set\n in the UFO lib to control this parameter (plist boolean value).\n\n For legacy reasons, an alias key (with an inverted meaning) is also\n supported: \"com.schriftgestaltung.Don't use Production Names\";\n when this is present if the UFO lib and is set to True, this is\n equivalent to 'useProductionNames' set to False.\n\n optimizeCFF:\n Run compreffor to subroubtinize CFF table, if present.\n \"\"\"\n if useProductionNames is None:\n useProductionNames = self.ufo.lib.get(\n USE_PRODUCTION_NAMES,\n not self.ufo.lib.get(GLYPHS_DONT_USE_PRODUCTION_NAMES)\n and self._postscriptNames is not None,\n )\n if useProductionNames:\n logger.info(\"Renaming glyphs to final production names\")\n self._rename_glyphs_from_ufo()\n if optimizeCFF and \"CFF \" in self.otf:\n from compreffor import compress\n\n logger.info(\"Subroutinizing CFF table\")\n compress(self.otf)\n return self.otf\n\n def _rename_glyphs_from_ufo(self):\n \"\"\"Rename glyphs using ufo.lib.public.postscriptNames in UFO.\"\"\"\n rename_map = self._build_production_names()\n\n otf = self.otf\n otf.setGlyphOrder([rename_map.get(n, n) for n in otf.getGlyphOrder()])\n\n # we need to compile format 2 'post' table so that the 'extraNames'\n # attribute is updated with the list of the names outside the\n # standard Macintosh glyph order; otherwise, if one dumps the font\n # to TTX directly before compiling first, the post table will not\n # contain the extraNames.\n if \"post\" in otf and otf[\"post\"].formatType == 2.0:\n otf[\"post\"].extraNames = []\n otf[\"post\"].compile(self.otf)\n\n if \"CFF \" in otf:\n cff = otf[\"CFF \"].cff.topDictIndex[0]\n char_strings = cff.CharStrings.charStrings\n cff.CharStrings.charStrings = {\n rename_map.get(n, n): v for n, v in char_strings.items()\n }\n cff.charset = [rename_map.get(n, n) for n in cff.charset]\n\n def _build_production_names(self):\n seen = {}\n rename_map = {}\n for name in self.otf.getGlyphOrder():\n # Ignore glyphs that aren't in the source, as they are usually generated\n # and we lack information about them.\n if name not in self.glyphSet:\n continue\n prod_name = self._build_production_name(self.glyphSet[name])\n\n # strip invalid characters not allowed in postscript glyph names\n if name != prod_name:\n valid_name = self.GLYPH_NAME_INVALID_CHARS.sub(\"\", prod_name)\n if len(valid_name) > self.MAX_GLYPH_NAME_LENGTH:\n # if the length of the generated production name is too\n # long, try to fall back to the original name\n valid_name = self.GLYPH_NAME_INVALID_CHARS.sub(\"\", name)\n else:\n valid_name = self.GLYPH_NAME_INVALID_CHARS.sub(\"\", name)\n\n if len(valid_name) > self.MAX_GLYPH_NAME_LENGTH:\n logger.warning(\n \"glyph name length exceeds 63 characters: '%s'\", valid_name\n )\n # add a suffix to make the production names unique\n rename_map[name] = self._unique_name(valid_name, seen)\n return rename_map\n\n @staticmethod\n def _unique_name(name, seen):\n \"\"\"Append incremental '.N' suffix if glyph is a duplicate.\"\"\"\n if name in seen:\n n = seen[name]\n while (name + \".%d\" % n) in seen:\n n += 1\n seen[name] = n + 1\n name += \".%d\" % n\n seen[name] = 1\n return name\n\n def _build_production_name(self, glyph):\n \"\"\"Build a production name for a single glyph.\"\"\"\n\n # use PostScript names from UFO lib if available\n if self._postscriptNames:\n production_name = self._postscriptNames.get(glyph.name)\n return production_name if production_name else glyph.name\n\n # use name derived from unicode value\n unicode_val = glyph.unicode\n if glyph.unicode is not None:\n return \"%s%04X\" % (\"u\" if unicode_val > 0xFFFF else \"uni\", unicode_val)\n\n # use production name + last (non-script) suffix if possible\n parts = glyph.name.rsplit(\".\", 1)\n if len(parts) == 2 and parts[0] in self.glyphSet:\n return \"%s.%s\" % (\n self._build_production_name(self.glyphSet[parts[0]]),\n parts[1],\n )\n\n # use ligature name, making sure to look up components with suffixes\n parts = glyph.name.split(\".\", 1)\n if len(parts) == 2:\n liga_parts = [\"%s.%s\" % (n, parts[1]) for n in parts[0].split(\"_\")]\n else:\n liga_parts = glyph.name.split(\"_\")\n if len(liga_parts) > 1 and all(n in self.glyphSet for n in liga_parts):\n unicode_vals = [self.glyphSet[n].unicode for n in liga_parts]\n if all(v and v <= 0xFFFF for v in unicode_vals):\n return \"uni\" + \"\".join(\"%04X\" % v for v in unicode_vals)\n return \"_\".join(\n self._build_production_name(self.glyphSet[n]) for n in liga_parts\n )\n\n return glyph.name\n","sub_path":"Lib/ufo2ft/postProcessor.py","file_name":"postProcessor.py","file_ext":"py","file_size_in_byte":6923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633267508","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: 1.0\n@author: panfeng\n@license: Apache Licence \n@file: app.py\n@time: 2018/12/25 10:22\n\"\"\"\n\nfrom controller import account\n\naction = input(\">>>\").strip()\n\nif (hasattr(account, action)):\n func = getattr(account,action)\n result = func()\nelse:\n result = \"404\"\n\nprint(result)\n","sub_path":"student_day8/反射/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134482526","text":"\"\"\"\n@File: time_task.py\n@CreateTime: 2020/1/6 上午11:05\n@Desc: 定时任务schedule\n\"\"\"\nimport schedule\nimport time\n\n\ndef one_job(message=\"stuff\"):\n print(\"I'm working on:\", message)\n\n\ndef two_job(message='working'):\n print(\"The Worker Status is:\", message)\n\n\nif __name__ == '__main__':\n schedule.every(10).minutes.do(one_job) # 每十分钟执行一次任务\n schedule.every().hour.do(one_job) # 每隔一小时执行一次任务\n schedule.every(5).to(10).days.do(two_job) # 每隔5到10天执行一次任务\n schedule.every().hour.do(two_job, message='sleep') # 带参数\n schedule.every().day.at(\"10:30\").do(one_job) # 每天的10:30执行任务\n schedule.every().wednesday.at(\"13:15\").do(one_job) # 每周三的13:15执行一次任务\n\n while True:\n schedule.run_pending() # 运行所有可以运行的任务\n time.sleep(1)\n\n\n\n\n\n\n\n","sub_path":"extra_study/time_task_one.py","file_name":"time_task_one.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"619863801","text":"import os\nimport sys\nimport inspect\nimport datetime\nimport threading\nimport cryptocompare\n\ncurrent_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparent_dir = os.path.dirname(current_dir)\nsys.path.insert(0, parent_dir)\ncommon_utils = parent_dir + '/' + 'utilities/'\ncommon_utils_dir = os.path.dirname(common_utils)\n\nsys.path.insert(0, current_dir)\nsys.path.insert(0, parent_dir)\nsys.path.insert(1, common_utils_dir)\n\nfrom settings import *\nfrom utils import CommonUtilities\nfrom mongo_utils import MongoUtilities\n\nclass GetHistoricalData():\n def __init__(self):\n cryptocompare.cryptocompare._set_api_key_parameter(CRYPTOCOMPARE_KEY)\n self.utils_obj = CommonUtilities()\n self.log = self.utils_obj.init_logger(LOG_FILE)\n self.mongo_obj = MongoUtilities(self.log, MONGO_CREDENTIALS)\n\n def _get_symbols(self):\n cur = self.mongo_obj.search({}, DATA_DB, DATA_COLLECTION, {'symbol': 1, 'currency': 1, '_id': 0})\n items = {(obj['symbol'], obj['currency']) for obj in cur}\n\n return list(items)\n\n def _prepare_records(self, symbol, currency, history):\n historical_records = []\n for item in history:\n average = (item['close'] + item['open']) / 2\n change = item['close'] - item['open']\n percent = (change / item['open']) * 100 if item['open'] else 0\n\n new_rec = {\n \"symbol\" : symbol,\n \"currency\": currency,\n \"info\" : {\n \"highest_buy_bid\" : 0,\n \"lowest_sell_bid\" : 0,\n \"last_traded_price\" : item['close'],\n \"yes_price\" : item['open'],\n \"volume\" : {\n \"max\" : item[\"high\"],\n \"min\" : item[\"low\"],\n \"volume\" : item['volumefrom']\n },\n },\n \"timestamp\" : datetime.datetime.utcnow().timestamp(),\n \"dt_added\" : datetime.datetime.utcnow().timestamp(),\n \"datetime\" : item['time'],\n \"high\" : item[\"high\"],\n \"low\": item[\"low\"],\n \"bid\" : 0,\n \"bidVolume\" : \"\",\n \"ask\" : 0,\n \"askVolume\" : \"\",\n \"vwap\" : \"\",\n \"open\" : item['open'],\n \"close\" : item['close'],\n \"last\" : item['close'],\n \"baseVolume\" : item['volumefrom'],\n \"quoteVolume\" : \"\",\n \"previousClose\" : 0,\n \"change\" : change,\n \"percentage\" : percent,\n \"average\" : average\n }\n\n historical_records.append(new_rec)\n\n return historical_records\n\n def get_historical_info(self, symbol, currency='', num_days=1):\n history = cryptocompare.get_historical_price_day(symbol, currency=currency, limit=num_days)\n return history\n\n def historical_info_to_db(self, input_arr, num_days=1):\n for inp in input_arr:\n symbol, currency = inp\n history = self.get_historical_info(symbol, currency, num_days)\n if not history:\n continue\n\n historical_records = self._prepare_records(symbol, currency, history)\n self.mongo_obj.upload_to_mongo(historical_records, DATA_DB, DATA_COLLECTION)\n\n return\n\n def get_and_upload_historical_info(self, num_days=1):\n symbols = self._get_symbols()\n\n chunk_size = len(symbols) // MAX_THREADS\n chunks = [symbols[i:i + chunk_size] for i in range(0, len(symbols), chunk_size)]\n\n thrds = []\n for ch in chunks:\n th = threading.Thread(target=self.historical_info_to_db, args=(ch, num_days))\n th.start()\n\n thrds.append(th)\n\n for t in thrds:\n t.join()\n\nif __name__ == '__main__':\n GetHistoricalData().get_and_upload_historical_info(NUM_DAYS)\n","sub_path":"dataIngestion/get_historical_data.py","file_name":"get_historical_data.py","file_ext":"py","file_size_in_byte":3970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"227791448","text":"\nfrom sys import argv\n\n\ndef top(arg):\n\n r_if = 0\n if arg: r_if = (1 if arg == 1 else arg)\n else: r_if == arg # 0 case only.\n\n r_while = 0\n i = arg\n while i: r_while = (1 if arg == 1 else arg); i -= 1\n\n r_for = 0\n for i in range(arg): r_for = (1 if arg == 1 else arg)\n\n try: raises_if(arg)\n except Exception: r_exc = (1 if arg == 1 else arg)\n else: r_exc = arg # 0 case only.\n finally: r_fin = (1 if arg == 1 else arg)\n\n\ndef raises_if(arg):\n if arg: raise Exception(arg)\n\n\nfor a in argv[1]: top(int(a))\n","sub_path":"test/inline_{}.py","file_name":"inline_{}.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"554185952","text":"import requests\n\nimport logging\nLOGGER = logging.getLogger(\"PYWPS\")\n\n\ndef patch_compliance_checker():\n \"\"\"\n Patch compliance_checker for ESGF OpenDAP with ``.dodsrc``.\n \"\"\"\n def patched_is_opendap(url):\n '''\n Returns True if the URL is a valid OPeNDAP URL\n :param str url: URL for a remote OPeNDAP endpoint\n '''\n # If the server replies to a Data Attribute Structure request\n das_url = url + '.das'\n response = requests.get(das_url, allow_redirects=True)\n if 'xdods-server' in response.headers:\n return True\n # Check if it is an access restricted ESGF thredds service\n if response.status_code == 401 and \\\n 'text/html' in response.headers['content-type'] and \\\n 'The following URL requires authentication:' in response.text:\n return True\n return False\n from compliance_checker.protocols import opendap\n opendap.is_opendap = patched_is_opendap\n","sub_path":"hummingbird/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7293235","text":"#!coding=utf-8\n\nimport re\nimport requests\nimport json\n\n\n#相对url转绝对url,假定将从网页中提取的不是http开头的,全部替换成从Index_Url中的第一个/前面部分+网页中提取到的部分\t\t\t\t\t\n#将穿进来的url统一转换成list返回\ndef Relative_to_Absolute(index_url,url_tail,site_name):\n\tif site_name == \"letv_show\":\n\t\tres_urls = []\n\t\tfor i in url_tail:\n\t\t\tres_urls.append(\"http://www.le.com/zongyi/{aid}.html\".format(aid=i))\n\t\treturn res_urls\n\telif site_name == \"letv_sp\":\n\t\tres_urls = []\n\t\tfor i in url_tail:\n\t\t\tres_urls.append(\"http://www.le.com/zongyi/{aid}.html\".format(aid=i))\n\t\treturn res_urls\n\telse:\n\t\thead_url = re.search(r'(.+//).+?/',index_url).group()\n\t\tif type(url_tail) is list and len(url_tail) > 0:\n\t\t\tres_urls = []\n\t\t\tif re.search(r'^//',url_tail[0]):\n\t\t\t\tfor url in url_tail:\n\t\t\t\t\tres_urls.append(re.sub(r'^//',\"http://\",url))\n\t\t\t\treturn res_urls\n\t\t\telif (not re.search(r'^http://',url_tail[0])) and (not re.search(r'^https://',url_tail[0])):\n\t\t\t\tif re.search(r'^/',url_tail[0]):\n\t\t\t\t\tfor url in url_tail:\n\t\t\t\t\t\turl = re.sub(r'^/',\"\",url)\n\t\t\t\t\t\tres_urls.append(head_url + url)\n\t\t\t\telse:\n\t\t\t\t\tfor url in url_tail:\n\t\t\t\t\t\tres_urls.append(head_url + url)\n\t\t\t\treturn res_urls\n\t\t\telse:\n\t\t\t\treturn url_tail\n\t\telse:\n\t\t\tif (not re.search(r'^http://',''.join(url_tail))) and (not re.search(r'^https://',''.join(url_tail))):\n\t\t\t\tif re.search(r'^/',''.join(url_tail)):\n\t\t\t\t\treturn [head_url + re.sub(r'^/',\"\",''.join(url_tail))]\n\t\t\t\telse:\n\t\t\t\t\treturn [head_url + ''.join(url_tail)]\n\t\t\telse:\n\t\t\t\treturn [''.join(url_tail)]\n\ndef Relative_to_Absolute2(index_url,url_tail,site_name):\n\tif site_name == \"mangguo_sp\":\n\t\tres_urls = []\n\t\ttarget_url = \"http://pcweb.api.mgtv.com/variety/showlist?collection_id={data_id}&month={time_id}\"\n\t\tdata_id = re.search('(?<=/b/)\\d+',index_url).group()\n\t\tfor i in url_tail:\n\t\t\t\tres_urls.append(target_url.format(data_id=data_id,time_id=i))\n\t\treturn res_urls\n\telif site_name == \"souhu_sp\":\n\t\tres_urls = []\n\t\ttarget_url = \"http://tv.sohu.com/item/VideoServlet?source=sohu&id={id}&year=2016&month=0\"\n\t\tfor i in url_tail:\n\t\t\t\tres_urls.append(target_url.format(id=i))\n\t\treturn res_urls\n\telse:\n\t\treturn url_tail\n\t#乐视综艺不再使用这个接口 (按照月份和综艺id) 传递数据,将其注释掉\n\t\"\"\"\n\telif site_name == \"letv_sp\":\n\t\tres_urls = []\n\t\ttarget_url = \"http://api.le.com/mms/out/albumInfo/getVideoListByIdAndDate?&year=2016&type=1&month={month}&id={data_id}\"\n\t\tdata_id = re.search('\\d+',index_url).group()\n\t\tfor i in url_tail:\n\t\t\t\tres_urls.append(target_url.format(month=i,data_id=data_id))\n\t\treturn res_urls\n\t\"\"\"\n\n\ndef Get_Valid_Url(urls):\n\tif type(urls) is list and len(urls) > 1:\n\t\tres_urls = []\n\t\tif re.search(r'^//',urls[0]):\n\t\t\tfor url in urls:\n\t\t\t\tres_urls.append(\"https://\"+re.sub(r'^//',\"\",url))\n\t\telse:\n\t\t\tres_urls = urls\n\t\treturn res_urls\n\telse:\n\t\tif re.search(r'^//',''.join(urls)):\n\t\t\treturn re.sub(r'^//',\"\",''.join(urls))\n\t\telse:\n\t\t\treturn ''.join(urls)\n\t\t\t\n\ndef get_HeadUrl(index_url,spider_name):\n\tif spider_name == \"youku_show\":\n\t\t\treturn re.sub(r\"\\d.html\",\"{page}.html\",index_url)\n\tif spider_name == \"mangguo_show\":\n\t\t\treturn re.sub(r\"\\d-0--.html\",\"{page}-0--.html\",index_url)\n\tif spider_name == \"mangguo_sp\":\n\t\t\treturn re.sub(r\"\\d-0--.html\",\"{page}-0--.html\",index_url)\n\tif spider_name == \"souhu_show\":\n\t\t\treturn re.sub(r\"\\d_p11_p12_p13.html\",\"{page}_p11_p12_p13.html\",index_url)\n\telse:\n\t\t\treturn re.sub(\"(\\d+)$\",\"{page}\",index_url)\n\t\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"netTv_Spider/netTv_Spider/Path_translate.py","file_name":"Path_translate.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"576373450","text":"#!/usr/bin/env python3\n\"\"\"\nVotes 1024 times for your id\n\"\"\"\nimport requests\n\n\nfor i in range(1024):\n requests.post(\"http://158.69.76.135/level0.php\",\n data={'id': '380', 'holdthedoor': 'Submit'})\n","sub_path":"level_0/level_0.py","file_name":"level_0.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"229873964","text":"import httpx\nimport json\n\nfrom typing import Union, List\n\nfrom Rest.Models.BenBot import NewCosmetics, Build\n\n\nBASE_URL = \"https://benbot.app/api/\"\n\nclass BenBot:\n def __init__(self, data):\n self.http = httpx.Client()\n self.language = data.language\n\n self.params = {\n 'lang': self.language\n }\n\n def new_cosmetics(self) -> Union[None, NewCosmetics]:\n res = self.http.get(\n url=BASE_URL + 'v1/newCosmetics',\n params=self.params\n )\n if res.status_code == 200:\n data = res.json()\n return NewCosmetics(data)\n \n def get_build(self) -> Union[None, Build]:\n res = self.http.get(\n url=BASE_URL + 'v1/aes',\n )\n if res.status_code == 200:\n data = res.json()\n return Build(data)","sub_path":"Rest/Getters/BenBot.py","file_name":"BenBot.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117029078","text":"\"\"\"\n Project Name\n ~~~~~~~~\n :copyright: (c) 2015 by Angzhou\n\"\"\"\n\nimport os\nimport json\nimport datetime\nimport functools\nimport urllib.parse\nimport traceback\n\nimport tornado.web\n\nfrom redis import Redis\nfrom rq import Queue\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom sqlalchemy.orm.interfaces import MapperOption\nfrom models import User\nfrom site_config import config\n\njobq = Queue(connection=Redis(host=config['RQ_SVR'], db=config['RQ_DB']))\n\nif config['DB_TYPE'] == 'mysql':\n engine = create_engine(\n \"mysql+pymysql://%(DB_USER)s:%(DB_PASS)s@%(DB_SVR)s:%(DB_PORT)s/%(DB_NAME)s?charset=utf8\"\n % config, echo=config['DEBUG'], pool_recycle=7200)\nelif config['DB_TYPE'] == 'postgres':\n engine = create_engine(\n \"postgresql+psycopg2://%(DB_USER)s:%(DB_PASS)s@%(DB_SVR)s:%(DB_PORT)s/%(DB_NAME)s\"\n % config, echo=config['DEBUG'],\n isolation_level=\"AUTOCOMMIT\",\n pool_recycle=7200)\nelse:\n engine = create_engine('sqlite:///db.db')\n\n\nif config['DBCACHE_SVR']:\n import dogpile.cache\n import caching_query\n cache_region = dogpile.cache.make_region()\n cache_settings = {\n \"cache.redis.backend\": \"dogpile.cache.redis\",\n \"cache.redis.arguments.host\": config['DBCACHE_SVR'],\n \"cache.redis.arguments.port\": 6379,\n }\n cache_region.configure_from_config(cache_settings, \"cache.redis.\")\n cache_regions = {\"default\": cache_region}\n FromCache = caching_query.FromCache\n DB_Session = scoped_session(sessionmaker(\n bind=engine, query_cls=caching_query.query_callable(cache_regions)))\n\nelse:\n class FromCache(MapperOption):\n pass\n\n DB_Session = scoped_session(sessionmaker(bind=engine))\n\n\n# 考虑更灵活的login机制,如login_required(\"student\",\"teacher\") 可以只让学生和老师登陆\ndef login_required(user_type=\"any\"):\n \"\"\"Decorate methods with this to require that the user be logged in.\"\"\"\n def decorator(method):\n @functools.wraps(method)\n def wrapper(self, *args, **kwargs):\n if not self.current_user:\n if self.request.method in (\"GET\", \"HEAD\"):\n\n self.redirect(\"/login?r=%s\" % urllib.parse.quote(self.request.path))\n return\n raise tornado.web.HTTPError(403)\n if user_type == \"any\":\n type_byte = 63\n elif user_type == \"oadmin\":\n type_byte = 8\n elif user_type == \"teacher\":\n type_byte = 4\n elif user_type == \"parent\":\n type_byte = 2\n else:\n type_byte = 1\n if not self.current_user.type & type_byte:\n \n self.write(\"无相应权限查看本页内容\")\n return\n \n return method(self, *args, **kwargs)\n\n\n return wrapper\n\n return decorator\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n\n def __init__(self, application, request, **kwargs):\n super(BaseHandler, self).__init__(application, request, **kwargs)\n # curh is current handler class name without 'Handler' part\n self.tmpdict = {\n \"path\": self.request.path,\n \"curh\": self.__class__.__name__[:-7],\n 'extmpl': self.extmpl}\n\n def initialize(self):\n self.db = DB_Session()\n\n def on_finish(self):\n self.db.close()\n\n def extmpl(self, filename):\n o = None\n with open(os.path.join(self.application.settings['template_path'], filename)) as f:\n o = f.read()\n return o\n\n def get_current_user(self):\n user = self.get_secure_cookie(\"user\")\n if user:\n user = json.loads(user.decode('utf-8'))\n userinfo = self.db.query(User).options(FromCache()).get(user['id'])\n if userinfo:\n \n self.tmpdict['nickname'] = userinfo.username\n return userinfo\n else:\n # has cookie, but no user\n self.set_cookie(\"user\", \"\", expires=(\n datetime.datetime.utcnow() - datetime.timedelta(days=365)))\n return None\n else:\n return None\n\n def write_error(self, code, **kwargs):\n # FIXME: 404模版没写\n # if code==404:\n # self.render('404.html')\n # return\n\n # 从tornado源码copy,只是加了charset\n # 注意版本3.1.1后这里有变化, 不判断debug而是serve_traceback\n # if hasattr(self, 'get_error_html'):\n # if 'exc_info' in kwargs:\n # exc_info = kwargs.pop('exc_info')\n # kwargs['exception'] = exc_info[1]\n # try:\n # # Put the traceback into sys.exc_info()\n # raise_exc_info(exc_info)\n # except Exception:\n # self.finish(self.get_error_html(status_code, **kwargs))\n # else:\n # self.finish(self.get_error_html(status_code, **kwargs))\n # return\n if self.request.method == \"POST\":\n self.write({\"code\": code, 'reason': self._reason})\n self.finish()\n elif self.settings.get(\"debug\") and \"exc_info\" in kwargs:\n # in debug mode, try to send a traceback\n self.set_header('Content-Type', 'text/plain; charset=UTF-8')\n for line in traceback.format_exception(*kwargs[\"exc_info\"]):\n self.write(line)\n self.finish()\n else:\n self.finish(\n '%(code)d: %(message)s'\n \"%(code)d: %(message)s\"\n % {\"code\": code, \"message\": self._reason})\n","sub_path":"website/server/site_base.py","file_name":"site_base.py","file_ext":"py","file_size_in_byte":5755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463297159","text":"# -*- coding: utf-8 -*-\r\n'''\r\nJDoe_JSmith_1_4_2: Read and show an image.\r\n'''\r\nimport matplotlib.pyplot as plt\r\nimport os.path\r\nimport numpy as np # “as” lets us use standard abbreviations\r\nimport PIL\r\n\r\n \r\n'''Read the image data'''\r\n# Get the directory of this python script\r\ndirectory = os.path.dirname(os.path.abspath(__file__)) \r\n# Build an absolute filename from directory + filename\r\nfilename = os.path.join(directory, 'man.jpg')\r\n# Read the image data into an array\r\nimg = plt.imread(filename)\r\n \r\n'''Show the image data'''\r\n# Create figure with 1 subplot\r\nfig, ax = plt.subplots(1, 2)\r\n# Show the image data in a subplot\r\nax[0].imshow(img, interpolation='none')\r\nax[0].set_title('I sleep on them')\r\nax[1].set_title('Real stuff?')\r\nax[1].set_ylim(260, 0)\r\nax[1].plot(605,121,'ro')\r\nax[1].plot(654,118,'ro')\r\n\r\nimg2 = img\r\nheight = len(img)\r\nwidth = len(img[0])\r\nfor r in range(height):\r\n for c in range(width):\r\n if sum(img[r][c])<50: # brightness R+G+B goes up to 3*255=765\r\n img[r][c]=[255,255,255] # R + B = magenta\r\n\r\n''' img2 = PIL.Image.fromarray(img)\r\nbox = (100,100,300,300)'''\r\nax[1].imshow(img2, interpolation='none')\r\n\r\n# Show the figure on the screen\r\nfig.show()\r\n","sub_path":"Files/Image.py","file_name":"Image.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"464200997","text":"#!/usr/bin/env python\n#coding:utf-8\nimport random\nimport numpy as np\n# from utils.treebank import StanfordSentiment\nimport time\nfrom sgd_wrapper import *\nfrom sgd import *\nfrom datasetFactory import getdataset\nimport negSampling\n\nimport db_model\nimport wv\n\n\ncost, grad = f(x)\nx = x - grad*step\n\ncost, gradIn, gradOut = skipgram(string)\n\n# Context size\nC = 3 #5\n\nentry = db_model.fetch_entry_untreated()\nstring = entry[2]\nentryId = entry[0]\ntrainingPairs, tokens, wordVectors = wv.getDataset(string,C)\n\n# 最后mark\ndb_model.mark_entry_as_treated(entryId)\n\n\n# Reset the random seed to make sure that everyone gets the same results\n# random.seed(314)\n# dataset = getdataset() # StanfordSentiment()\n# tokens = dict([('我',0),('是',1),('测试',2),('句子',3),('初级',4),('前端',5),('工程师',6)]) #dataset.tokens()\n\n# nWords = len(tokens)\n# We are going to train 10-dimensional vectors for this assignment\n# dimVectors = 16 #10\n\n\n# Reset the random seed to make sure that everyone gets the same results\n# random.seed(31415)\n# np.random.seed(9265)\n\nstartTime=time.time()\n\n\n# 意思是 input vector是随机启动, output vector是zeros\n# randomStartVector = (np.random.rand(nWords, dimVectors) - 0.5)\n# zerosVector = np.zeros((nWords, dimVectors))\n# wordVectors = np.concatenate((randomStartVector/dimVectors, zerosVector),axis=0)\n# print(wordVectors)\n\n# 训练,关键\nwordVectors = sgd(\n lambda vec: word2vec_sgd_wrapper(skipgram, tokens, vec, dataset, C,negSamplingCostAndGradient),\n wordVectors,\n 0.3, # step 0.3\n 2000, # iteration: 40000\n None,\n True,\n PRINT_EVERY=10\n) \n\n# 这里是什么鬼,又拼接回去??? 我把它倒过来\n# concatenate the input and output word vectors\n# print('wordVectors before')\n# print(wordVectors)\n# wordVectors = np.concatenate(\n# (wordVectors[:nWords,:], wordVectors[nWords:,:]),\n# axis=0)\nwordVectors = np.concatenate(\n ( wordVectors[nWords:,:],wordVectors[:nWords,:]),\n axis=0)\n\n# wordVectors = wordVectors[:nWords,:] + wordVectors[nWords:,:]\n# print('wordVectors after')\n# print(wordVectors)\n\n\nvisualizeWords = ['我','是', '测试', '句子','前端', '工程师']#\"annoying\"\n# print( visualizeWords[2])\nvisualizeIdx = [tokens[word] for word in visualizeWords]\n# print('visualizeIdx')\n# print(visualizeIdx)\nvisualizeVecs = wordVectors[visualizeIdx, :]\n# print('visualizeVecs')\n# print(visualizeVecs.shape)\n#总之很奇怪的处理方法\n\n# 减去平均值, 标准化吗\ntemp = (visualizeVecs - np.mean(visualizeVecs, axis=0))\nprint('temp')\nprint(temp.shape)\n\n# covariance 协方差\ncovariance = 1.0 / len(visualizeIdx) * temp.T.dot(temp)\nprint('covariance')\nprint(covariance.shape)\n\n# 奇异值分解\nU,S,V = np.linalg.svd(covariance)\ncoord = temp.dot(U[:,0:2])\nprint('coord')\nprint(coord)\n\nimport matplotlib\n\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False #用来正常显示负号\nfor i in range(len(visualizeWords)):\n plt.text(coord[i,0], coord[i,1], visualizeWords[i],\n bbox=dict(facecolor='green', alpha=0.1))\n\nplt.xlim((np.min(coord[:,0]), np.max(coord[:,0])))\nplt.ylim((np.min(coord[:,1]), np.max(coord[:,1])))\n\nplt.savefig('q3_word_vectors.png')\nplt.show()\n","sub_path":"dep/test_run.py","file_name":"test_run.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"607302035","text":"# -*- coding: utf-8 -*-\n\"\"\"Collect Vray Scene and prepare it for extraction and publishing.\"\"\"\nimport re\n\nimport maya.app.renderSetup.model.renderSetup as renderSetup\nfrom maya import cmds\n\nimport pyblish.api\n\nfrom openpype.pipeline import legacy_io\nfrom openpype.lib import get_formatted_current_time\nfrom openpype.hosts.maya.api import lib\n\n\nclass CollectVrayScene(pyblish.api.InstancePlugin):\n \"\"\"Collect Vray Scene.\n\n If export on farm is checked, job is created to export it.\n \"\"\"\n\n order = pyblish.api.CollectorOrder + 0.01\n label = \"Collect Vray Scene\"\n families = [\"vrayscene\"]\n\n def process(self, instance):\n \"\"\"Collector entry point.\"\"\"\n collected_render_layers = instance.data[\"setMembers\"]\n instance.data[\"remove\"] = True\n context = instance.context\n\n _rs = renderSetup.instance()\n # current_layer = _rs.getVisibleRenderLayer()\n\n # collect all frames we are expecting to be rendered\n renderer = cmds.getAttr(\n \"defaultRenderGlobals.currentRenderer\"\n ).lower()\n\n if renderer != \"vray\":\n raise AssertionError(\"Vray is not enabled.\")\n\n maya_render_layers = {\n layer.name(): layer for layer in _rs.getRenderLayers()\n }\n\n layer_list = []\n for layer in collected_render_layers:\n # every layer in set should start with `LAYER_` prefix\n try:\n expected_layer_name = re.search(r\"^.+:(.*)\", layer).group(1)\n except IndexError:\n msg = \"Invalid layer name in set [ {} ]\".format(layer)\n self.log.warning(msg)\n continue\n\n self.log.info(\"processing %s\" % layer)\n # check if layer is part of renderSetup\n if expected_layer_name not in maya_render_layers:\n msg = \"Render layer [ {} ] is not in \" \"Render Setup\".format(\n expected_layer_name\n )\n self.log.warning(msg)\n continue\n\n # check if layer is renderable\n if not maya_render_layers[expected_layer_name].isRenderable():\n msg = \"Render layer [ {} ] is not \" \"renderable\".format(\n expected_layer_name\n )\n self.log.warning(msg)\n continue\n\n layer_name = \"rs_{}\".format(expected_layer_name)\n\n self.log.debug(expected_layer_name)\n layer_list.append(expected_layer_name)\n\n frame_start_render = int(self.get_render_attribute(\n \"startFrame\", layer=layer_name))\n frame_end_render = int(self.get_render_attribute(\n \"endFrame\", layer=layer_name))\n\n if (int(context.data['frameStartHandle']) == frame_start_render\n and int(context.data['frameEndHandle']) == frame_end_render): # noqa: W503, E501\n\n handle_start = context.data['handleStart']\n handle_end = context.data['handleEnd']\n frame_start = context.data['frameStart']\n frame_end = context.data['frameEnd']\n frame_start_handle = context.data['frameStartHandle']\n frame_end_handle = context.data['frameEndHandle']\n else:\n handle_start = 0\n handle_end = 0\n frame_start = frame_start_render\n frame_end = frame_end_render\n frame_start_handle = frame_start_render\n frame_end_handle = frame_end_render\n\n # Get layer specific settings, might be overrides\n data = {\n \"subset\": expected_layer_name,\n \"layer\": layer_name,\n \"setMembers\": cmds.sets(layer, q=True) or [\"*\"],\n \"review\": False,\n \"publish\": True,\n \"handleStart\": handle_start,\n \"handleEnd\": handle_end,\n \"frameStart\": frame_start,\n \"frameEnd\": frame_end,\n \"frameStartHandle\": frame_start_handle,\n \"frameEndHandle\": frame_end_handle,\n \"byFrameStep\": int(\n self.get_render_attribute(\"byFrameStep\",\n layer=layer_name)),\n \"renderer\": self.get_render_attribute(\"currentRenderer\",\n layer=layer_name),\n # instance subset\n \"family\": \"vrayscene_layer\",\n \"families\": [\"vrayscene_layer\"],\n \"asset\": legacy_io.Session[\"AVALON_ASSET\"],\n \"time\": get_formatted_current_time(),\n \"author\": context.data[\"user\"],\n # Add source to allow tracing back to the scene from\n # which was submitted originally\n \"source\": context.data[\"currentFile\"].replace(\"\\\\\", \"/\"),\n \"resolutionWidth\": lib.get_attr_in_layer(\n \"defaultResolution.height\", layer=layer_name\n ),\n \"resolutionHeight\": lib.get_attr_in_layer(\n \"defaultResolution.width\", layer=layer_name\n ),\n \"pixelAspect\": lib.get_attr_in_layer(\n \"defaultResolution.pixelAspect\", layer=layer_name\n ),\n \"priority\": instance.data.get(\"priority\"),\n \"useMultipleSceneFiles\": instance.data.get(\n \"vraySceneMultipleFiles\")\n }\n\n # Define nice label\n label = \"{0} ({1})\".format(expected_layer_name, data[\"asset\"])\n label += \" [{0}-{1}]\".format(\n int(data[\"frameStartHandle\"]), int(data[\"frameEndHandle\"])\n )\n\n instance = context.create_instance(expected_layer_name)\n instance.data[\"label\"] = label\n instance.data.update(data)\n\n def get_render_attribute(self, attr, layer):\n \"\"\"Get attribute from render options.\n\n Args:\n attr (str): name of attribute to be looked up.\n\n Returns:\n Attribute value\n\n \"\"\"\n return lib.get_attr_in_layer(\n \"defaultRenderGlobals.{}\".format(attr), layer=layer\n )\n","sub_path":"openpype/hosts/maya/plugins/publish/collect_vrayscene.py","file_name":"collect_vrayscene.py","file_ext":"py","file_size_in_byte":6253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"245586735","text":"# Tile class\n# Luis Henriquez and Iavor Dekov\n#\n\nimport pygame\n\n\"\"\"\nRepresents a single tile in the minsweeper game.\n\"\"\"\n\nclass Tile:\n \"\"\"\n Represents an individual tile on the board.\n \"\"\"\n def __init__(self, leftTop, TILESIZE):\n # coordinates of the tile from the top left hand corner of the board\n self.leftTop = leftTop\n self.size = TILESIZE\n self.isBomb = False\n self.isVisible = False\n self.text = None\n self.img = None\n self.colorrevealed = pygame.Color(124, 166, 79)\n self.colorhidden = pygame.Color(108, 170, 238)\n # self.color = pygame.Color(124, 166, 79)\n self.bordercolor = pygame.Color(0, 0, 0)\n self.rect = pygame.Rect(leftTop[0], leftTop[1], TILESIZE, TILESIZE)\n self.border = pygame.Rect(leftTop[0], leftTop[1], TILESIZE, TILESIZE)\n\n\n def getLeftTop(self):\n \"\"\"\n Return a tuple containing the the left top coordinate of the tile --> (left, top)\n :return:\n \"\"\"\n return self.leftTop\n\t\n def hasBomb(self):\n \"\"\"\n Returns whether the tile has a bomb or not.\n :return:\n \"\"\"\n return self.isBomb\n\n def setBomb(self):\n \"\"\"\n Sets a bomb on the tile.\n :param hasbomb:\n :return:\n \"\"\"\n self.isBomb = True\n\n def hasNum(self):\n if self.text:\n return True\n return False\n\n def contains(self, pixelpoint):\n \"\"\"\n Returns whether the given pixel is inside the tile.\n :param pixelpoint:\n :return:\n \"\"\"\n px, py = pixelpoint\n return self.rect.collidepoint(px, py)\n\n def reveal(self):\n \"\"\"\n Returns whether the tile is concealed or not.\n :return:\n \"\"\"\n self.isVisible = True\n\n\n\n def isRevealed(self):\n \"\"\"Returns whether the tile is revealed.\"\"\"\n self.color = pygame.Color(124, 166, 79)\n return self.isVisible\n\n def setcolors(self, hidden=None, revealed=None):\n if hidden:\n self.colorhidden=pygame.Color(hidden)\n if revealed:\n self.colorrevealed=pygame.Color(revealed)\n\n def highlight(self, surface):\n pygame.draw.rect(surface, (255, 255, 0), self.border, 4)\n\n def draw(self, surface):\n \"\"\"\n Draws the tile.\n :param surface:\n :return:\n \"\"\"\n pygame.draw.rect(surface, self.bordercolor, self.border, 4)\n if self.isVisible:\n pygame.draw.rect(surface, self.colorrevealed, self.rect)\n else:\n pygame.draw.rect(surface, self.colorhidden, self.rect)\n\n if self.text:\n pass\n if self.img:\n pass\n\n def setText(self, text):\n self.text = text\n\n def setImage(self, img):\n self.img = img\n\n# main method for unit testing\nif __name__ == \"__main__\":\n t = Tile((0, 0), 10)\n print(t.hasBomb())\n t.setBomb()\n print(t.hasBomb())\n print(t.isRevealed())\n print(t.contains((5, 5)))\n print(t.contains((11, 11)))\n print(t.contains((1, 1)))\n print(t.contains((-1, -1)))\n print(t.getLeftTop())\n print(t.hasNum())","sub_path":"Tile.py","file_name":"Tile.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"613115212","text":"from hw2skeleton import cluster\nfrom hw2skeleton import io\nimport os\nimport numpy as np\ndef test_similarity():\n filename_a = os.path.join(\"data\", \"276.pdb\")\n filename_b = os.path.join(\"data\", \"4629.pdb\")\n\n activesite_a = io.read_active_site(filename_a)\n activesite_b = io.read_active_site(filename_b)\n assert cluster.compute_similarity(activesite_a.counts, activesite_b.counts) == np.linalg.norm(activesite_a.counts - activesite_b.counts)\n assert cluster.compute_similarity(activesite_a.counts, activesite_a.counts) == 0\n assert cluster.compute_similarity(activesite_a.counts, activesite_b.counts) == cluster.compute_similarity(activesite_b.counts, activesite_a.counts)\n\ndef test_partition_clustering():\n # tractable subset\n pdb_ids = [276, 4629, 10701]\n\n active_sites = []\n for id in pdb_ids:\n filepath = os.path.join(\"data\", \"%i.pdb\"%id)\n active_sites.append(io.read_active_site(filepath))\n\n\n assert len(cluster.cluster_by_partitioning(active_sites).keys()) >= 2\n\ndef test_hierarchical_clustering():\n # tractable subset\n pdb_ids = [276, 4629, 10701]\n\n active_sites = []\n for id in pdb_ids:\n filepath = os.path.join(\"data\", \"%i.pdb\"%id)\n active_sites.append(io.read_active_site(filepath))\n\n print()\n assert len(cluster.cluster_hierarchically(active_sites).keys()) >=2\n","sub_path":"test/test_cluster.py","file_name":"test_cluster.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"90996350","text":"from itertools import combinations\n\n# def combinations(arr,r):\n# pool = tuple(arr)\n# n = len(pool)\n# if r > n:\n# return\n# indices = list(range(r))\n# yield tuple(pool[i] for i in indices)\n# while True:\n# for i in reversed(range(r)):\n# if indices[i] != i+n-r:\n# break\n# else:\n# return\n# indices[i] += 1\n# for j in range(i+1,r):\n# indices[j] = indices[j-1] + 1\n# yield tuple(pool[i] for i in indices)\n\ndef calcS(A):\n ret = 0\n for sub in combinations(A,2):\n ret += Stable[sub[0]][sub[1]]\n ret += Stable[sub[1]][sub[0]]\n return ret\n\nfor tc in range(1,int(input())+1):\n N = int(input())\n Stable = [list(map(int, input().split())) for _ in range(N)]\n min_anw = float('inf')\n cnt = 0\n visited = set()\n for A in combinations(range(N),N//2):\n if A in visited:\n break\n B = set(range(N))-set(A)\n B = tuple(B)\n visited.add(A)\n visited.add(B)\n SA = calcS(A)\n SB = calcS(B)\n min_anw = min(min_anw,abs(SA-SB))\n\n print(f'#{tc}', min_anw)","sub_path":"SWEA/bit/4012_요리사_2.py","file_name":"4012_요리사_2.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"505991261","text":"#####################################################################################################################\n#Purpose: this package allows a user to input any factorable quadratic trinomial or binomial into its factored form\n#Programmers: Rena Lu, Pavneet Kapoor, Saad Haq, Alex Nelson\n#Last Modified: May 13, 2014\n#####################################################################################################################\n\nfrom math import *\n\ndef createArray(quadraticTrinomial):\n trinomial = quadraticTrinomial.split(' ')\n return trinomial\n\n#Purpose: To find the number of terms in a given trinomial. Returns either a one or a two.\ndef findNumTerms(array):\n length = len(array)\n terms_in_array = 0\n if length == 3:\n terms_in_array = 2\n elif length == 5:\n terms_in_array = 3\n else:\n print (\"Error, please check your input.\")\n return terms_in_array\n\n\n#Purpose: To Find the coefficients of a, b, and c. If not present in the equation it returns a 0 as the value.\n#(continued) This means if you equation is 10x^2 - 10 it will return a as 10, b as 0 and c as -10).\ndef findCoefficients(array):\n #Sets up the local variables and also defines the coefficents array.\n terms = findNumTerms(array)\n leng_first = len(array[0])\n leng_second = len(array[2])\n coefficents = []\n \n #Finds the coefficent of term one (a)\n if array[0][0] == \"x\":\n a = 1\n elif array[0][0] == \"-\" and array[0][1] == \"x\":\n a = -1\n else:\n a = int(array[0][0 : leng_first - 3])\n coefficents.append(a)\n \n #Finds the coefficent of the second term.\n if array[2][0] == \"x\":\n b = 1\n c = 0\n elif array[2][leng_second - 1] == \"x\":\n b = int(array[2][0 : leng_second - 1])\n c = 0\n else:\n b = 0\n c = int(array[2])\n \n #Checks if the sign infront of the second term is a negative. If it is the number has its value reversed\n if array[1] == \"-\" and b > 0:\n b = -b\n elif array[1] == \"-\":\n c = -c\n \n #Adds the value of b to the array.\n coefficents.append(b)\n \n #Checks if there are 3 terms, if there are then it finds the value of c\n if terms == 3:\n c = int(array[4])\n if array[3] == \"-\":\n c = -c\n coefficents.append(c)\n\n return coefficents\n\n#FINDS GCD BETWEEN TWO NUMBERS\ndef findCommonFactorTwo(numerator, denominator):\n if numerator < 0:\n numeratorNew = -numerator\n else:\n numeratorNew = numerator\n \n if denominator < 0:\n denominatorNew = -denominator\n else:\n denominatorNew = denominator\n \n if numeratorNew > denominatorNew:\n maximum = numeratorNew\n minimum = denominatorNew\n else:\n maximum = denominatorNew\n minimum = numeratorNew\n \n remainder = maximum%minimum\n \n while remainder > 0:\n maximum = minimum\n minimum = remainder\n remainder = maximum%minimum\n\n if numerator > 0:\n return minimum\n else:\n return -minimum\n \ndef findCommonFactorThree(coefficientA, coefficientB, coefficientC):\n\n #FINDS GCD OF GIVEN COEFFICIENTS\n GCDab = findCommonFactorTwo (coefficientA, coefficientB)\n GCDac = findCommonFactorTwo (coefficientA, coefficientC)\n GCDbc = findCommonFactorTwo (coefficientB, coefficientC)\n\n\n #FINDS THE GCD OF ALL PREVIOUS GCDS TO DETERMINE GREATEST COMMON FACTOR\n GCD1 = findCommonFactorTwo (GCDab, GCDac)\n GCD2 = findCommonFactorTwo (GCDab, GCDbc)\n GCD3 = findCommonFactorTwo (GCDac, GCDbc)\n\n commonFactor = min(GCD1, GCD2, GCD3)\n\n return commonFactor\n\n#USE THE QUADRATIC FORMULA TO FIND FACOTRS OF A TRINOMIAL\ndef useQuadraticFormula(coefficientA, coefficientB, coefficientC):\n a = coefficientA\n b = coefficientB\n c = coefficientC\n \n bSqrMinusFourAc = b**2 - 4*a*c\n if bSqrMinusFourAc < 0:\n return \"Not factorable\"\n else:\n sqrtTerm = sqrt(bSqrMinusFourAc)\n if sqrtTerm%1 == 0:\n numeratorA = -b + sqrtTerm\n numeratorB = -b - sqrtTerm\n denom = 2*a\n reducefractionA = findCommonFactorTwo(numeratorA, denom) \n reducefractionB = findCommonFactorTwo(numeratorB, denom)\n \n if reducefractionA < 0:\n reducefractionA = -reducefractionA\n if reducefractionB < 0:\n reducefractionB = -reducefractionB\n reducedNumA = round(numeratorA/reducefractionA)\n reducedDenomA = round(denom/reducefractionA)\n reducedNumB = round(numeratorB/reducefractionB)\n reducedDenomB = round(denom/reducefractionB) \n\n #RETURNS THE FACTORS IN AN ARRAY\n factorTerms = [reducedDenomA, reducedNumA, reducedDenomB, reducedNumB]\n return factorTerms\n else:\n return \"Not factorable\"\n\ndef factorTrinomial (trinomial):\n array = createArray (trinomial)\n NumTerms = findNumTerms(array)\n coefficients = findCoefficients(array)\n\n #IF THE QUADRATIC EXPRESSION HAS THREE TERMS\n if NumTerms == 3:\n commonFactor = findCommonFactorThree(coefficients[0],coefficients[1],coefficients[2])\n newCoeA = coefficients[0]/commonFactor\n newCoeB = coefficients[1]/commonFactor\n newCoeC = coefficients[2]/commonFactor\n\n factors = useQuadraticFormula(newCoeA, newCoeB, newCoeC)\n\n #IF THE QUADRATIC TRINOMIAL CANNOT BE COMMON FACTORED FIRST\n if commonFactor == 1:\n commonFactor=\"\"\n elif commonFactor == -1:\n commonFactor=\"-\"\n else:\n commonFactor=str(commonFactor)\n \n if factors == \"Not factorable\":\n\n #IF THE QUADRATIC TRINOMIAL CANNOT BE FACTORED AT ALL\n if commonFactor == \"\" or commonFactor ==\"-\":\n return \"not factorable\"\n \n #IF THE QUADRATIC TRINOMIAL CANNOT BE FACTORED FURTHUR AFTER COMMON FACTORING\n else:\n if newCoeA == 1:\n aTerm=\"x^2\"\n elif newCoeA == -1:\n aTerm=\"-x^2\"\n else:\n aTerm=str(round(newCoeA))+\"x^2\"\n\n if newCoeB == 1:\n bTerm=\"+x\"\n elif newCoeB==-1:\n bTerm=\"-x\"\n elif newCoeB>0:\n bTerm=\"+\"+str(round(newCoeB))+\"x\"\n elif newCoeB<0:\n bTerm=str(round(newCoeB))+\"x\"\n \n if newCoeC > 0:\n cTerm=\"+\"+str(round(newCoeC))\n else:\n cTerm=str(round(newCoeC))\n\n return commonFactor + \"(\"+ aTerm + bTerm + cTerm + \")\"\n \n #IF THE TRINOMIAL CAN BE FACTORED INTO TWO SETS OF BRACKETS \n else:\n \n if factors[0]==1:\n aTerm=\"x\"\n else:\n aTerm=str(factors[0])+\"x\"\n\n if factors[1]>0:\n bTerm=\"-\"+str(factors[1]) \n elif factors[1]<0:\n lengthB = len(str(factors[1]))\n bTerm=\"+\"+str(factors[1])[1:(lengthB)]\n\n if factors[2]==1:\n cTerm=\"x\"\n else:\n cTerm=str(factors[2])+\"x\"\n\n if factors[3]>0:\n dTerm=\"-\"+str(factors[3]) \n elif factors[3]<0:\n lengthD = len(str(factors[3]))\n dTerm= \"+\" + str(factors[3])[1:(lengthD)]\n \n #PERFECT SQUARE\n if factors[0]==factors[2] and factors[1]==factors[3]:\n return commonFactor+\"(\"+aTerm+bTerm+\")^2\"\n #OTHER CASES\n else:\n return commonFactor+\"(\"+aTerm+bTerm+\")(\"+cTerm+dTerm+\")\"\n\n #IF THE QUADRATIC EXPRESSION HAS TWO TERMS\n elif NumTerms == 2:\n\n #IF THE BINOMIAL IS MISSING THE b-TERM\n if coefficients[1]==0:\n commonFactor = findCommonFactorTwo(coefficients[0],coefficients[2])\n newCoeA = coefficients[0]/commonFactor\n newCoeC = coefficients[2]/commonFactor\n factors = useQuadraticFormula(newCoeA, 0, newCoeC)\n if commonFactor == 1:\n commonFactor=\"\"\n elif commonFactor==-1:\n commonFactor=\"-\"\n else:\n commonFactor=str(commonFactor)\n\n #COMMON FACTOR ONLY\n if factors==\"Not factorable\":\n if commonFactor != \"\" and commonFactor != \"-\":\n\n if newCoeA == 1:\n aTerm=\"x^2\"\n else:\n aTerm=str(round(newCoeA))+\"x^2\"\n \n if newCoeC > 0:\n cTerm=\"+\"+str(round(newCoeC))\n else:\n cTerm=str(round(newCoeC))\n \n return commonFactor+\"(\"+aTerm+cTerm+\")\"\n \n else:\n return \"not factorable\"\n \n #DIFFERENCE OF SQUARES\n else:\n if factors[0] == 1:\n aTerm= \"x\"\n elif factors[0] == -1:\n aTerm= \"-x\"\n else:\n aTerm= str(round(factors[0])) + \"x\"\n \n if factors[1]>0:\n bTerm=str(factors[1])\n \n elif factors[1]<0:\n lengthB = len(str(factors[1]))\n bTerm=str(factors[1])[1:(lengthB)]\n\n return commonFactor + \"(\" + aTerm + \"-\"+bTerm + \")\" + \"(\" + aTerm + \"+\"+bTerm + \")\"\n \n #IF THE BINOMIAL IS MISSING A c-TERM\n elif coefficients[2]==0:\n commonFactor = findCommonFactorTwo (coefficients[0],coefficients[1])\n newCoeA= coefficients[0]/commonFactor\n newCoeB= coefficients[1]/commonFactor\n\n if commonFactor == 1:\n commonFactor=\"\"\n elif commonFactor==-1:\n commonFactor=\"-\"\n else:\n commonFactor=str(commonFactor)\n\n if newCoeA==1:\n newCoeA=\"\"\n else:\n newCoeA=str(round(newCoeA))\n\n return commonFactor + \"x(\" + newCoeA+\"x+\" + str(round(newCoeB))+ \")\" \n","sub_path":"factorTrinomialTools1.py","file_name":"factorTrinomialTools1.py","file_ext":"py","file_size_in_byte":10492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"125991328","text":"#!/usr/bin/python3\nimport os\nfrom models.base_model import BaseModel, Base\nfrom sqlalchemy import Column, String\nfrom sqlalchemy.orm import relationship\n\n\nclass State(BaseModel, Base):\n if os.getenv('HBNB_TYPE_STORAGE') == \"db\":\n __tablename__ = \"states\"\n name = Column(String(128), nullable=False)\n cities = relationship(\"City\", backref=\"state\")\n else:\n name = \"\"\n\n def __init__(self, *args, **kwargs):\n if len(args) > 0:\n super().__init__(*args, **kwargs)\n if len(kwargs) > 0:\n super().__init__(*args, **kwargs)\n else:\n super().__init__()\n","sub_path":"models/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"509790406","text":"import boto3\nimport time\nimport datetime\n\naws_access_key_id = 'AKIA3QZZ6P4BPCBXCTF4'\naws_access_key = '7n5i0ECZfJJ8fhk6z+9O3yw1Whe28DSp8JQrfqgo'\naws_region_name = 'us-east-1'\nclient = boto3.client('dynamodb', region_name=aws_region_name,\n aws_access_key_id=aws_access_key_id,\n aws_secret_access_key=aws_access_key)\n\nlocation_table_name = 'Location'\nestimation_table_name = 'Estimation'\naggr_report_attr_name = 'Aggregated_Report'\nwindow_width_minutes = 60\n\ndef lambda_handler(event, context):\n min_time = min_submitted_time()\n all_location_ids = get_all_location_ids(client)\n\n for location_id in all_location_ids:\n est_response = client.query(\n TableName=estimation_table_name,\n Limit=1000,\n KeyConditionExpression='Location_ID = :location_id AND Time_Submitted > :min_time',\n ExpressionAttributeValues={':location_id': {'N': location_id}, ':min_time': {'N': str(min_time)}}\n )\n \n wait_time = -1\n if est_response['Count'] > 0:\n wait_times = [int(est_response['Items'][i]['Est_Minutes']['N']) for i in range(len(est_response['Items']))]\n wait_time = sum(wait_times) / len(wait_times)\n \n \n loc_response = client.query(\n TableName=location_table_name,\n KeyConditionExpression='Location_ID = :location_id',\n ExpressionAttributeValues={':location_id': {'N': location_id}}\n )\n loc_dic = loc_response['Items'][0]\n \n curr_hour = datetime.datetime.now().hour\n \n if aggr_report_attr_name in loc_dic:\n report_list = loc_dic[aggr_report_attr_name]['L']\n else:\n report_list = [{'N': '-1'}] * 24\n report_list[curr_hour] = {'N': str(wait_time)}\n \n client.update_item(\n TableName=location_table_name,\n Key={\n 'Location_ID': {\n 'N': location_id\n }\n },\n AttributeUpdates={\n aggr_report_attr_name: {\n 'Value': {\n 'L': report_list\n },\n 'Action': 'PUT'\n }\n }\n )\n\ndef get_all_location_ids(client):\n response = client.scan(TableName=location_table_name)\n location_ids = [response['Items'][i]['Location_ID']['N'] for i in range(len(response['Items']))]\n return location_ids\n\ndef min_submitted_time():\n now = time.time()\n min_datetime = datetime.datetime.fromtimestamp(now) - datetime.timedelta(minutes=window_width_minutes)\n min_time = min_datetime.timestamp()\n return min_time\n","sub_path":"lambda/hourly_report.py","file_name":"hourly_report.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"65727317","text":"# -*- coding: utf-8 -*-\nimport json\nimport re\nimport math\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # or any {'0', '1', '2'}\n# 取值 0 : 0也是默认值,输出所有信息\n# 取值 1 : 屏蔽通知信息\n# 取值 2 : 屏蔽通知信息和警告信息\n# 取值 3 : 屏蔽通知信息、警告信息和报错信息\nimport threading\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nimport random\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom keras.utils import plot_model\nfrom sklearn.model_selection import train_test_split\n\nfrom utils.extract_csi import extract_csi, get_scaled_csi\nfrom utils.get_files_info import get_label_data, get_file_list, get_3dconv_cross_test_data, get_3dconv_cross_batch_generator\nfrom utils.models import create_3d_cross_model\n\n# 设置GPU内存按需分配\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\nconfig = ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = InteractiveSession(config=config)\n\nrandom.seed(123)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--data_path\", default='/home/zut_csi/tomding/RCNN/data_processed/test', type=str, help=\"输入数据dir\") # required=True,\nparser.add_argument(\"--image_size\", default=64, type=int, help=\"\")\nparser.add_argument(\"--logs_path\", default='./logs', type=str, help=\"模型存储在何处\")\nparser.add_argument(\"--test_mode\", action='store_true', help=\"Whether to run training.\")\nparser.add_argument(\"--do_train\", action='store_true', help=\"Whether to run training.\")\nparser.add_argument(\"--do_eval\", action='store_true', help=\"Whether to run eval on the dev set.\")\nparser.add_argument(\"--batch_size\", default=64, type=int, help=\"Total batch size for training.\")\nparser.add_argument(\"--learning_rate\", default=5e-5, type=float, help=\"The initial learning rate for Adam.\")\nparser.add_argument(\"--epochs\", default=1000, type=int, help=\"Total number of training epochs to perform.\")\nparser.add_argument('--seed', type=int, default=42, help=\"random seed for initialization\")\nargs = parser.parse_args()\n\nif not os.path.exists(args.logs_path): # 判断保存模型的目录是否存在\n os.makedirs(args.logs_path) # 如果不存在,就新建一个\n\nlabel_file_list, wav_file_list = get_file_list(args.data_path)\nif args.test_mode == True:\n label_file_list, wav_file_list = label_file_list[:1000], wav_file_list[:1000]\n print('_________________________________________runing in test_mode_________________________________________')\ntrain_label_file_list, test_label_file_list, train_wav_file_list, test_wav_file_list = train_test_split(label_file_list, wav_file_list, test_size=0.1, random_state=123)\n# 用迭代器的时候需要\ntrain_wav_file_list, validate_wav_file_list, train_label_file_list, validate_label_file_list = train_test_split(train_wav_file_list, train_label_file_list, test_size=0.1, random_state=123)\nvalidate_label_list = get_label_data(train_label_file_list)\n\ntrain_label_list = get_label_data(train_label_file_list)\ntest_label_list = get_label_data(test_label_file_list)\n\ncb = []\n#cb.append(keras.callbacks.ReduceLROnPlateau(monitor='val_accuracy', factor=0.1, patience=50, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0))\n# 当监测值不再改善时,该回调函数将中止训练可防止过拟合\n#cb.append(keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=100, verbose=1, mode='auto'))\ncrnn_cross_model = create_3d_cross_model(input_size=(1, 3, 30, 3641), output_size=4) \nprint(crnn_cross_model.summary())\nprint('train files amount:', len(train_label_file_list), len(train_wav_file_list))#, 'validate files amount:', len(validate_label_list), validate_file_nums,)\nprint('test files amount:', len(test_label_file_list), len(test_wav_file_list))\n# keras.utils.plot_model(base_model, show_shapes=True)\n\n# 用迭代器的时候需要\ntrain_batch_gen = get_3dconv_cross_batch_generator('train', args.batch_size, train_wav_file_list, train_label_list)\nvalidate_batch_gen = get_3dconv_cross_batch_generator('validate', args.batch_size, validate_wav_file_list, validate_label_list)\ntest_batch_gen = get_3dconv_cross_batch_generator('test', args.batch_size, test_wav_file_list, test_label_list)\n\n# input_data = next(train_batch_gen)[0]\n# plt.imshow(input_data['the_inputs'][0].T[0])\n# plt.show()\n# print(input_data['the_inputs'].shape, input_data['the_labels'].shape, input_data['input_length'].shape, input_data['label_length'].shape)\n#his = crnn_cross_model.fit_generator(train_batch_gen, verbose=1, steps_per_epoch=len(train_wav_file_list)//args.batch_size, validation_data=validate_batch_gen, validation_steps=len(validate_wav_file_list)//args.batch_size, epochs=args.epochs, callbacks=cb) \n\n\n# 读入所有数据\n#train_data = get_crnn_cross_train_data(train_wav_file_list, train_label_list, args.image_size)\n# print(train_data[0]['the_inputs'].shape, train_data[1]['the_labels'].shape, 2222222222222222222)\n# # his = crnn_cross_model.fit(train_data[0], train_data[1], validation_split=0.1, batch_size=args.batch_size, epochs=args.epochs, callbacks=cb) # callback的epoch都是对fit里的参数来说\n\n# 保存模型结构及权重\ncrnn_cross_model.save_weights('./train_files/crnn_cross_save_weights1.h5')\nwith open('./train_files/crnn_cross_model_struct1.json', 'w') as f:\n json_string = crnn_cross_model.to_json()\n f.write(json_string) # 保存模型信息\nprint('模型结构及权重已保存')\n\n# 加载权重\nwith open('./train_files/crnn_cross_model_struct1.json') as f:\n model_struct = f.read()\ntest_model = keras.models.model_from_json(model_struct)\ntest_model.load_weights('./train_files/crnn_cross_save_weights1.h5')\n# model = keras.models.load_model('all_model.h5')\nprint('模型已加载')\n\nloss, acc = crnn_cross_model.evaluate_generator(test_batch_gen)\nprint(loss, acc)\n\n# 对模型进行评价\ndef evaluate(kind, wavs, labels):\n data_num = len(wavs)\n error_cnt = 0\n for i in range(data_num):\n result = list(test_model.predict(wavs[i][np.newaxis, :, :, :, :]))\n pre_label = result.index(max(result))+1 # (1, 20, 11)\n label = int(labels[i])\n if label != pre_label:\n error_cnt += 1\n print('真实标签:', label, '预测结果', pre_label)\n print('{}:样本数{}错误数{}准确率:{:%}'.format(kind, data_num, error_cnt, (1-error_cnt/data_num)))\n\n\n# 训练集\ntrain_wavs, train_labels = get_3dconv_cross_test_data(train_wav_file_list, train_label_list)\n# 测试集\ntest_wavs, test_labels = get_3dconv_cross_test_data(test_wav_file_list, test_label_list)\n# print(train_wavs['the_inputs'].shape, train_labels['the_labels'].shape)\n\nevaluate('trian', train_wavs, train_labels)\nevaluate('test', test_wavs, test_labels)\n","sub_path":"code/3d_conv.py","file_name":"3d_conv.py","file_ext":"py","file_size_in_byte":6791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"273477955","text":"#import modules2\nimport arcpy\n\n#set workspace\narcpy.env.workspace = r\"C:\\EsriTraining\\PythEveryone\\RunningScripts\\Polk_County\\OregonPolk.gdb\"\n\n#set up a describe object for each fc in geodatabase\nfcList = arcpy.ListFeatureClasses()\nfor fc in fcList:\n desc = arcpy.Describe(fc)\n print (desc.spatialReference.name)\n\nprint (\"Script completed\")","sub_path":"Solutions/SpatialRef.py","file_name":"SpatialRef.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"145259418","text":"\"\"\" Short Interest View \"\"\"\n__docformat__ = \"numpy\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom pandas.core.frame import DataFrame\n\nfrom gamestonk_terminal.helper_funcs import get_user_agent\n\n\ndef get_low_float() -> DataFrame:\n \"\"\"Returns low float DataFrame\n\n Returns\n -------\n DataFrame\n Low float DataFrame with the following columns:\n Ticker, Company, Exchange, ShortInt, Float, Outstd, Industry\n \"\"\"\n url_high_short_interested_stocks = \"https://www.lowfloat.com\"\n\n text_soup_low_float_stocks = BeautifulSoup(\n requests.get(\n url_high_short_interested_stocks, headers={\"User-Agent\": get_user_agent()}\n ).text,\n \"lxml\",\n )\n\n a_low_float_header = []\n for low_float_header in text_soup_low_float_stocks.findAll(\n \"td\", {\"class\": \"tblhdr\"}\n ):\n a_low_float_header.append(low_float_header.text.strip(\"\\n\").split(\"\\n\")[0])\n df_low_float = pd.DataFrame(columns=a_low_float_header)\n df_low_float.loc[0] = [\"\", \"\", \"\", \"\", \"\", \"\", \"\"]\n\n stock_list_tr = text_soup_low_float_stocks.find_all(\"tr\")\n\n low_float_data = []\n for a_stock in stock_list_tr:\n a_stock_txt = a_stock.text\n\n if a_stock_txt == \"\":\n continue\n\n low_float_data = a_stock_txt.split(\"\\n\")\n\n if len(low_float_data) == 8:\n df_low_float.loc[len(df_low_float.index)] = low_float_data[:-1]\n\n low_float_data = []\n\n return df_low_float\n\n\ndef get_today_hot_penny_stocks() -> DataFrame:\n \"\"\"Returns today hot penny stocks\n\n Returns\n -------\n DataFrame\n Today hot penny stocks DataFrame with the following columns:\n Ticker, Price, Change, $ Volume, Volume, # Trades\n \"\"\"\n url_penny_stock_stocks = \"https://www.pennystockflow.com\"\n\n text_soup_penny_stock_stocks = BeautifulSoup(\n requests.get(\n url_penny_stock_stocks,\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.10; rv:86.1) Gecko/20100101 Firefox/86.1\"\n },\n ).text,\n \"lxml\",\n )\n\n a_penny_stock_header = list()\n for penny_stock_header in text_soup_penny_stock_stocks.findAll(\n \"td\", {\"class\": \"tblhdr\"}\n ):\n a_penny_stock_header.append(penny_stock_header.text)\n\n l_stocks = list()\n for penny_stock in text_soup_penny_stock_stocks.find_all(\"a\", href=True):\n if penny_stock.text:\n l_stocks.append(penny_stock.text)\n\n a_penny_stock = list()\n penny_idx = 0\n d_stocks = {}\n for penny_stock in text_soup_penny_stock_stocks.findAll(\"td\", {\"align\": \"right\"}):\n a_penny_stock.append(penny_stock.text)\n\n if len(a_penny_stock) == 5:\n d_stocks[l_stocks[penny_idx]] = a_penny_stock\n penny_idx += 1\n a_penny_stock = list()\n\n df_penny = pd.DataFrame.from_dict(d_stocks).T\n df_penny.columns = a_penny_stock_header[1:]\n\n return df_penny\n","sub_path":"gamestonk_terminal/stocks/discovery/shortinterest_model.py","file_name":"shortinterest_model.py","file_ext":"py","file_size_in_byte":2965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"650382776","text":"import numpy as np\nimport pickle\nimport pandas as pd\nimport argparse\n\n# 定义要执行的数据集文件\ncmd_opt = argparse.ArgumentParser(description='Argparser for data process')\ncmd_opt.add_argument('-dataset', type=str, default=\"yelp\", help='choose rsc, tb, or yelp')\ncmd_args = cmd_opt.parse_args()\nprint(cmd_args)\n\n\n# The format of processed data:\n# data_behavior[user][0] is user_id\n# data_behavior[user][1][t] is displayed list at time t\n# data_behavior[user][2][t] is picked id at time t\n\nfilename = './'+cmd_args.dataset+'.txt'\n\n# 只选取数据集中的[Time, is_click, session_new_index, tr_val_tst, item_new_index]这5cols\n# usecols选择列,但是好像没有顺序而言,虽然是7, 6,但是最终结果还是按照13567排列的\nraw_data = pd.read_csv(filename, sep='\\t', usecols=[1, 3, 5, 7, 6], dtype={1: int, 3: int, 7: int, 5:int, 6:int})\n\n# drop_duplicates: 将subset对应的重复列去重,默认保留第一个\nraw_data.drop_duplicates(subset=['session_new_index','Time','item_new_index','is_click'], inplace=True)\n# sort_values按照by进行排序, inplce=True,在原数据上修改\nraw_data.sort_values(by='is_click',inplace=True)\n# drop_duplicates: keep=’last‘保留最后一项,删除前面的重复项,默认是first\nraw_data.drop_duplicates(keep='last', subset=['session_new_index','Time','item_new_index'], inplace=True)\n\n# 2019-7-30 modify the error that dataframe has no attribute nuique()\nsize_user = raw_data['session_new_index'].nunique()\nsize_item = raw_data['item_new_index'].nunique()\n\n# 按照session_new_index进行分组\ndata_user = raw_data.groupby(by='session_new_index')\n# 建立了一个存放list的list,内部list的数量和user_size一样\ndata_behavior = [[] for _ in range(size_user)]\n\ntrain_user = []\nvali_user = []\ntest_user = []\n\nsum_length = 0\nevent_count = 0\n\n# size_user=user的数量\nfor user in range(size_user):\n data_behavior[user] = [[], [], []]\n data_behavior[user][0] = user\n # 实际上在这里user就代替了sessionId了,\n data_u = data_user.get_group(user)\n # 将user对应的是train或者是valid或者是test对应的标号取出\n split_tag = list(data_u['tr_val_tst'])[0]\n if split_tag == 0:\n train_user.append(user)\n elif split_tag == 1:\n vali_user.append(user)\n else:\n test_user.append(user)\n\n data_u_time = data_u.groupby(by='Time')\n # time_set就是由几种时间, 使用set能够去重\n time_set = list(set(data_u['Time']))\n # 排个序,小在前大在后\n time_set.sort()\n\n true_t = 0\n for t in range(len(time_set)):\n # 把时间一样的分成一组display_set\n display_set = data_u_time.get_group(time_set[t])\n event_count += 1\n sum_length += len(display_set)\n\n # 每个display_set中is_click等于1的为当前sessiond的点击商品\n data_behavior[user][1].append(list(display_set['item_new_index']))\n data_behavior[user][2].append(int(display_set[display_set.is_click==1]['item_new_index']))\n\n# 生成对角矩阵\nnew_features = np.eye(size_item)\n\nfilename = './'+cmd_args.dataset+'.pkl'\nfile = open(filename, 'wb')\n# pickle.dump, 将对象保存到pickle中, protocol是存储格式\npickle.dump(data_behavior, file, protocol=pickle.HIGHEST_PROTOCOL)\npickle.dump(new_features, file, protocol=pickle.HIGHEST_PROTOCOL)\nfile.close()\n\nfilename = './'+cmd_args.dataset+'-split.pkl'\nfile = open(filename, 'wb')\npickle.dump(train_user, file, protocol=pickle.HIGHEST_PROTOCOL)\npickle.dump(vali_user, file, protocol=pickle.HIGHEST_PROTOCOL)\npickle.dump(test_user, file, protocol=pickle.HIGHEST_PROTOCOL)\nfile.close()\n","sub_path":"dropbox/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"57508511","text":"import torch \r\nfrom torch.utils.data import Dataset, DataLoader\r\nfrom PIL import Image\r\nimport pandas as pd \r\nimport os\r\n\r\n\r\nclass CustomDataset(Dataset):\r\n \r\n def __init__(self, dataset_list, root_dir,transform=None, isTrain=True):\r\n\r\n self.original_csv=dataset_list\r\n self.root_dir=root_dir\r\n self.dataset_list=dataset_list\r\n self.transform=transform\r\n self.isTrain=isTrain\r\n \r\n\r\n def __getitem__(self, idx):\r\n \r\n if torch.is_tensor(idx):\r\n idx=idx.tolist()\r\n\r\n csv_content=self.original_csv.iloc[idx]\r\n\r\n #file_name\r\n \r\n file_name= csv_content['file_name']\r\n\r\n #digit\r\n digit= csv_content['digit']\r\n\r\n #letter\r\n letter= ord(csv_content['letter'])\r\n\r\n #letter->array로 변환 (tuple로 저장되는 문제가 있음)\r\n\r\n\r\n if self.isTrain:\r\n \r\n img_path=os.path.join(self.root_dir+'/'+str(digit)+'/', file_name )\r\n \r\n else:\r\n \r\n\r\n img_path=os.path.join(self.root_dir+'/', file_name )\r\n \r\n\r\n \r\n image=Image.open(img_path)\r\n\r\n image=image.convert('RGB')\r\n\r\n if self.transform is not None:\r\n image=self.transform(image)\r\n \r\n return image, digit, letter\r\n \r\n\r\n\r\n def __len__(self):\r\n return len(self.original_csv)\r\n ","sub_path":"SJ/CustomDataset.py","file_name":"CustomDataset.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"439775529","text":"from pygame import *\n\ninit()\nWIDTH = 1280\nHEIGHT = 1024\nSCROLL = True\nscreen = display.set_mode((WIDTH, HEIGHT))\nscrollpos = [0, 0]\n\nclass Object(object):\n\tdef disp(self):\n\t\tscreen.blit(self.sprite, self.rect)\n\nprint(\"Hawk picture from: \" + \"http://commons.wikimedia.org/wiki/File:Black_Eagle_in_Kaggalipura.JPG\")\nclass Enemy(Object):\n\tdef __init__(self, pos, flight_pattern_size, speed):\n\t\tself.sprite = image.load(\"hawk.jpg\")\n\t\tself.rect = self.sprite.get_rect()\n\t\tself.rect.centerx = pos[0]\n\t\tself.rect.centery = pos[1]\n\t\tself.fp = flight_pattern_size\n\t\tself.leg = 1\n\t\tself.speed = speed\n\t\tself.ip = pos\n\t\tself.dead = False\n\n\tdef update(self):\n\t\t# Added after class, to keep the enemies in place while scrolling\n\t\t# \"ip\" is the self.ip, but adjusted to account for previous scrolling\n\t\tip = self.ip[0] + scrollpos[0], self.ip[1] + scrollpos[1]\n\t\tif self.dead and self.rect.centery < 4000:\n\t\t\tself.rect.centery += 20\n\t\t\treturn\n\t\t#sets flight path size\n\t\tif self.leg == 1:\n\t\t\tself.rect.centery += self.speed\n\t\t\tif self.rect.centery > ip[1] + self.fp[1]:\n\t\t\t\tself.leg = 2\n\t\telif self.leg == 2:\n\t\t\tself.rect.centerx += self.speed\n\t\t\tif self.rect.centerx > ip[0] + self.fp[0]:\n\t\t\t\tself.leg = 3\n\t\telif self.leg == 3:\n\t\t\tself.rect.centery -= self.speed\n\t\t\tif self.rect.centery < ip[1]:\n\t\t\t\tself.leg = 4\n\t\telif self.leg == 4:\n\t\t\tself.rect.centerx -= self.speed\n\t\t\tif self.rect.centerx < ip[0]:\n\t\t\t\tself.leg = 1\n\n\tdef killed(self):\n\t\tself.dead = True\n\nclass Block(Object):\n\tdef __init__(self):\n\t\tself.sprite = image.load(\"block.bmp\")\n\t\tself.rect = self.sprite.get_rect()\n\n\tdef __init__(self, x, y):\n\t\tself.sprite = image.load(\"block.bmp\")\n\t\tself.rect = self.sprite.get_rect()\n\t\tself.rect.centerx = x\n\t\tself.rect.centery = y\n\nwall = []\nfor i in range(20):\n\twall.append(Block(100 + 30*i, 300))\nfor i in range(50):\n\twall.append(Block(700 + 30*i, 800))\nfor i in range(10):\n\twall.append(Block(1000 + 30*i, 650))\n\nenemies = []\ndef mkenemies():\n\tglobal enemies\n\tenemies = [Enemy((700, 100), (100, 100), 3), Enemy((100, 600), (400, 100), 5), Enemy((1000, 100), (100, 300), 7)]\n\tenemies.extend([Enemy((1400, 300), (500, 200), 10), Enemy((1500, 300), (500, 200), 10)])\nmkenemies()\n\nclass Squirrel(Object):\n\tdef __init__(self):\n\t\tself.sprite = image.load(\"squirrel.bmp\")\n\t\tself.rect = self.sprite.get_rect()\n\t\tself.rect.centerx = 100\n\t\tself.rect.centery = 100\n\t\tself.s_movement = 0\n\t\tself.v_movement = 0\n\n\tdef startright(self):\n\t\tself.sprite = image.load(\"squirrel.bmp\")\n\t\tself.s_movement = 10\n\n\tdef startleft(self):\n\t\tself.sprite = image.load(\"squirrel_left.bmp\")\n\t\tself.s_movement = -10\n\n\tdef stop(self):\n\t\tself.s_movement = 0\n\n\tdef jump(self):\n\t\tonwall, cb = self.check_wall_collide()\n\t\tif onwall:\n\t\t\tself.v_movement += -30\n\n\tdef check_wall_collide(self):\n\t\tonwall = False\n\t\tcollideblock = 0\n\t\tfor block in wall + enemies:\n\t\t\tif self.rect.colliderect(block.rect):\n\t\t\t\tonwall = True\n\t\t\t\tcollideblock = block\n\t\treturn onwall, collideblock\n\n\tdef update(self): # Expect this to be called during the main loop\n\t\t# Check for collisions with enemies\n\n\t\tfor e in enemies:\n\t\t\tif e.rect.colliderect(self.rect):\n\t\t\t\tif e.dead:\n\t\t\t\t\tcontinue\n\t\t\t\telif self.rect.centery > e.rect.centery:\n\t\t\t\t\tself.rect.centerx = 100\n\t\t\t\t\tself.rect.centery = 0\n\t\t\t\telse:\n\t\t\t\t\t# we win\n\t\t\t\t\te.killed()\n\n\t\tself.rect.y += self.v_movement\n\n\t\tonwall, collideblock = self.check_wall_collide()\n\n\t\tif not onwall:\n\t\t\tself.v_movement += 1\n\t\telse:\n\t\t\tself.v_movement = 0\n\t\t\tif collideblock.rect.centery < self.rect.centery:\n\t\t\t\tself.rect.y = collideblock.rect.centery + 15\n\t\t\telse:\n\t\t\t\tself.rect.y = collideblock.rect.y - self.rect.height + 1\n\n\t\tself.rect.x += self.s_movement\n\n\t\t# if the squirrel is near the edge\n\t\tif self.rect.centerx < 300:\n\t\t\tscroll(300 - self.rect.centerx, 0)\n\n\t\tif self.rect.centery < 300:\n\t\t\tscroll(0, 300 - self.rect.centery)\n\n\t\tif WIDTH - self.rect.centerx < 300:\n\t\t\tscroll(-(300 - (WIDTH - self.rect.centerx)), 0)\n\n\t\tif HEIGHT - self.rect.centery < 300:\n\t\t\tscroll(0, -(300 - (HEIGHT - self.rect.centery)))\n\n\t\tif self.v_movement > 40:\n\t\t\tscroll(-scrollpos[0], -scrollpos[1])\n\t\t\tself.v_movement = 0\n\t\t\tself.rect.centerx = 100\n\t\t\tself.rect.centery = 0\n\t\t\tmkenemies()\n\nsq = Squirrel()\n\ndef scroll(x, y):\n\tif SCROLL:\n\t\tscrollpos[0] += x\n\t\tscrollpos[1] += y\n\t\tfor o in wall + enemies + [sq]:\n\t\t\to.rect.centerx += x\n\t\t\to.rect.centery += y\n\n\nwhile True:\n\tfor e in event.get():\n\t\tif e.type == KEYDOWN:\n\t\t\tif e.key == K_RIGHT:\n\t\t\t\tsq.startright()\n\t\t\tif e.key == K_LEFT:\n\t\t\t\tsq.startleft()\n\t\t\tif e.key == K_SPACE:\n\t\t\t\tsq.jump()\n\t\tif e.type == KEYUP:\n\t\t\tif e.key == K_RIGHT or e.key == K_LEFT:\n\t\t\t\tsq.stop()\n\t\tif e.type == QUIT:\n\t\t\tprint(\"Ok, time to quit\")\n\t\t\tquit()\n\t\t\tfrom sys import exit\n\t\t\texit()\n\n\tscreen.fill((255, 255, 255))\n\tfor block in wall:\n\t\tblock.disp()\n\tfor e in enemies:\n\t\te.update()\n\t\te.disp()\n\tsq.update()\n\tsq.disp()\n\tdisplay.flip()\n","sub_path":"old-cs111/cs111/examples/game/game_improved.py","file_name":"game_improved.py","file_ext":"py","file_size_in_byte":4812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"436897276","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@version: ??\n@author: 'AD'\n@license: Apache Licence \n@time: 2018/6/15 21:06\nDescribe:\n\n\n\"\"\"\nfrom __future__ import division\nimport os\nimport numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n# print(df1)\n# print(df1.AX)\n\nN_COLUMNS = ['AXA', 'AYA', 'AZA', 'AXC', 'AYC', 'AZC', 'AXK', 'AYK', 'AZK', 'AXS', 'AYS', 'AZS',\n 'WXA', 'WYA', 'WZA', 'WXC', 'WYC', 'WZC', 'WXK', 'WYK', 'WZK', 'WXS', 'WYS', 'WZS',\n 'HXA', 'HYA', 'HZA', 'HXC', 'HYC', 'HZC', 'HXK', 'HYK', 'HZK', 'HXS', 'HYS', 'HZS']\n# A 均值,C 协方差,K 峰度,S 偏度, F 快速傅里叶(FFT值)\n# K_COLUMNS = ['AA', 'AC', 'AK', 'AS', 'WA', 'WC', 'WK', 'WS', 'HA', 'HC', 'HK', 'HS']\nN_COLUMNS_SPE = ['AXA', 'AYA', 'AZA', 'AXC', 'AYC', 'AZC', 'AXK', 'AYK', 'AZK', 'AXS', 'AYS', 'AZS',\n 'WXA', 'WYA', 'WZA', 'WXC', 'WYC', 'WZC', 'WXK', 'WYK', 'WZK', 'WXS', 'WYS', 'WZS',\n 'HXA', 'HYA', 'HZA', 'HXC', 'HYC', 'HZC', 'HXK', 'HYK', 'HZK', 'HXS', 'HYS', 'HZS', 'SPE']\n\n\ndef kmeans_process():\n df = DataFrame(pd.read_csv('../../ActionRecogintion/src/pre/all_data_X.csv'), columns=N_COLUMNS_SPE)\n\n spe_columns = []\n for index in np.arange(len(df.SPE)):\n if index % 5 == 0:\n # np.append(spe_columns,df.SPE[index])\n spe_columns.append(df.SPE[index])\n # print(spe_columns)\n\n df = df.drop(['SPE'], axis=1)\n df = np.array(df)\n\n from sklearn.cluster import KMeans\n # 8*5 =40\n kmeans = KMeans(n_clusters=40)\n kmeans.fit(df)\n label_pred = kmeans.labels_ # 获取聚类标签\n centroids = kmeans.cluster_centers_ # 获取聚类中心\n inertia = kmeans.inertia_ # 获取聚类准则的总和\n\n datamat = label_pred.reshape(int(len(label_pred) / 5), 5)\n data_k = DataFrame(datamat, columns=['state0', 'state1', 'state2', 'state3', 'state4'])\n data_k['SPE'] = spe_columns\n # print(data_k)\n # 保存文件\n data_k.to_csv('src/hmmpre/action_data_k.csv')\n print('kmeans 处理完成...')\n return data_k\n\n\nif __name__ == '__main__':\n # 数据获取以及处理\n # readDataAndPropressing(n_components=5)\n data_k = kmeans_process()\n df1 = data_k[:21].drop(['SPE'], axis=1)\n\n # print(data_k)\n from hmmlearn import hmm\n\n # 状态——>隐藏状态\n states = ['state0', 'state1', 'state2', 'state3', 'state4']\n n_states = len(states)\n # 所有可能观测到的序列8个动作\n observations = ['act1', 'act2', 'act3', 'act4', 'act5', 'act6', 'act7', 'act8']\n n_observations = len(observations)\n\n # start_prob = np.full(40, 0)\n # start_prob[0] = 1\n\n start_prob = np.array([1, 0, 0, 0, 0])\n transition_mat = np.array(\n [[0.5, 0.5, 0, 0, 0], [0, 0.5, 0.5, 0, 0], [0, 0, 0.5, 0.5, 0], [0, 0, 0, 0.5, 0.5], [0.5, 0, 0, 0, 0.5]])\n # 3个状态\n emission_prob = np.full((8, 40), (1 / 40))\n # 构造隐马尔科夫模型\n hmm_model = hmm.GaussianHMM(n_components=n_states, covariance_type='full')\n hmm_model.startprob_ = start_prob\n hmm_model.transmat_ = transition_mat\n hmm_model.emissionprob_ = emission_prob\n\n seen = np.array([[22, 33, 7, 8, 29]])\n # 在给定观测条件下, 最可能出现的观测状态所对应的隐藏状态序列\n hmm_model.decode(df1, algorithm='viterbi')\n\n print(hmm_model)\n # print(hmm_model.score(seen))\n # print(hmm_model)\n # 训练HMM\n # print(\"\\n正在训练隐马尔科夫模型....\")\n # hmm_model.fit(df)\n","sub_path":"study/easyHmm/myTest.py","file_name":"myTest.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"650025214","text":"import bs4\r\nimport re\r\nimport requests\r\nimport json\r\n\r\nres = requests.get('https://www.goavidhansabha.gov.in/member.php')\r\nsoup = bs4.BeautifulSoup(res.text,'html.parser')\r\n\r\ncontantTable = soup.find('div', {\"class\":\"mla-list\"})\r\nrows = contantTable.find_all('div',{\"class\":\"details-blk\"})\r\ncount=0\r\nresult=[]\r\nfor text in rows :\r\n if count<40:\r\n dict={}\r\n a=(' '.join(text.text.split()))\r\n b=a[a.index('-')+1:a.index('Constituency :')]\r\n try :\r\n b=b[b.index('Shri.')+5:]\r\n\r\n except ValueError:\r\n try:\r\n b = b[b.index('Smt.') + 4:]\r\n except ValueError:\r\n b=b\r\n\r\n dict['name']=b\r\n c=a[a.index('Constituency :')+15:a.index('Party :')]\r\n dict['area']=c\r\n d=a[a.index('Party :')+8:]\r\n dict['party']=d\r\n count=count+1\r\n print(b)\r\n result.append(dict)\r\n\r\nc=0\r\nlist1=[]\r\nfor i in result:\r\n dict={}\r\n dict['uid']=\"\"\r\n dict['Name']=i['name']\r\n a=i['name'].split()\r\n c=str(a[-1])+' '+str(a[0])\r\n\r\n dict['alias_name']=c\r\n dict['country']=\"India\"\r\n dict['list_type']=\"\"\r\n dict['address']=i['area']\r\n dict['last_updated']=\"\"\r\n dict2={}\r\n\r\n dict2['comment']=''\r\n dict2['Date of Imposition of Sanction']=\"\"\r\n dict2['Sanction Imposed']=''\r\n dict['entity_details']=dict2\r\n dict3={}\r\n dict3['passport']=\"\"\r\n dict3['ssn']=''\r\n dict3['other_id']=''\r\n dict['documents']=dict3\r\n dict4={}\r\n dict4['sl_source']='7th GOA Legislative Assembly '\r\n dict4['sl_type']=''\r\n dict4['sl_url']='https://www.goavidhansabha.gov.in/member.php'\r\n dict4['sl_authority']=''\r\n dict4['sl_host_country']='India'\r\n dict['sanctions_list']=dict4\r\n list1.append(dict)\r\nlist1=json.dumps(list1)\r\nprint(list1)\r\n","sub_path":"goa.py","file_name":"goa.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"102189508","text":"#!/usr/bin/env python\n\nfrom pylab import *\nimport jlab\nimport itertools\nimport re\n\n_prob_regex = re.compile('Ch *(?P[0-9]+): *(?P[.0-9]*) *: *(?P[0-9]*)')\ndef get_ratio(line):\n m = _prob_regex.search(line)\n return int(m.group('ch')), float(m.group('n')) / int(m.group('d'))\n\ndef _csv_line_iter(line):\n return (f.strip() for f in line.split(','))\n\ndef load_pump_fh(fh):\n axis = next(fh)\n unit = next(fh)\n data = []\n for line in fh:\n try:\n line = [float(f) for f in _csv_line_iter(line)]\n if len(line) <= 1:\n raise ValueError\n except:\n break\n data.append(line)\n data = array(data).T\n it = itertools.chain([line], fh)\n for line in it:\n if not line.endswith('Probe'):\n continue\n for line in it:\n try:\n ch, ratio = get_ratio(line)\n data[ch] *= ratio\n except:\n break\n return data\n\ndef load_pump(fname):\n with open(fname) as fh:\n return load_pump_fh(fh)\n\nif __name__ == '__main__':\n import sys\n iname = sys.argv[1]\n data = load_pump(iname)\n if iname.lower().endswith('.csv'):\n oname = iname[:-4] + '.py'\n else:\n oname = iname + '.py'\n jlab.save_pyfile(jlab.Ret('data'), oname)\n","sub_path":"pumping/loadcsv.py","file_name":"loadcsv.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"368137819","text":"#!/usr/bin/env python\n\n# Behaves like the other estimators but receives the position estimate from the\n# Crazyflie internal EKF instead of calculating the estimate\n\nimport rospy\nfrom geometry_msgs.msg import Point\nfrom crazyflie_driver.srv import UpdateParams\n\nimport tf\n\nfrom crazyflie_driver.msg import GenericLogData\n\n\ndef callback(data):\n pt = Point()\n pt.x = data.values[0]\n pt.y = data.values[1]\n pt.z = data.values[2]\n\n position_pub.publish(pt)\n\n br = tf.TransformBroadcaster()\n br.sendTransform((pt.x, pt.y, pt.z),\n tf.transformations.quaternion_from_euler(0, 0, 0),\n rospy.Time.now(),\n rospy.get_namespace() + \"base_link\",\n \"world\")\n\nif __name__ == \"__main__\":\n rospy.init_node('lps_ekf_bridge')\n\n # Set anchor position according to the position setup in ROS\n rospy.wait_for_service('update_params')\n update_params = rospy.ServiceProxy('update_params', UpdateParams)\n\n rospy.loginfo(\"Setting anchor position ...\")\n\n n_anchors = rospy.get_param(\"n_anchors\")\n for i in range(n_anchors):\n position = rospy.get_param(\"anchor{}_pos\".format(i))\n rospy.loginfo(\"Anchor {} at {}\".format(i, position))\n name = \"anchorpos/anchor{}\".format(i)\n rospy.set_param(name + \"x\", position[0])\n rospy.set_param(name + \"y\", position[1])\n rospy.set_param(name + \"z\", position[2])\n update_params([name + 'x', name + 'y', name + 'z'])\n\n position_pub = rospy.Publisher(\"crazyflie_position\", Point, queue_size=10)\n\n rospy.Subscriber(\"log_kfpos\", GenericLogData, callback)\n\n rospy.spin()\n","sub_path":"scripts/lps_ekf_bridge.py","file_name":"lps_ekf_bridge.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"376353770","text":"import pytest\n\nfrom bson import ObjectId\nimport pymongo\n\nfrom yadm.documents import Document\nfrom yadm.queryset import QuerySet\nfrom yadm.serialize import from_mongo\nfrom yadm import fields\n\n\nclass Doc(Document):\n __collection__ = 'testdocs'\n b = fields.BooleanField()\n i = fields.IntegerField()\n l = fields.ListField(fields.IntegerField())\n\n\ndef test_init(db):\n assert isinstance(db.client, pymongo.mongo_client.MongoClient)\n assert isinstance(db.db, pymongo.database.Database)\n assert db.db.name == 'test'\n assert db.name == 'test'\n\n\ndef test_get_collection(db):\n collection = db._get_collection(Doc)\n\n assert isinstance(collection, pymongo.collection.Collection)\n assert collection.name == 'testdocs'\n\n\ndef test_get_queryset(db):\n queryset = db.get_queryset(Doc)\n\n assert isinstance(queryset, QuerySet)\n assert queryset._db is db\n assert queryset._document_class is Doc\n\n\ndef test_get_document(db):\n col = db.db.testdocs\n ids = [col.insert_one({'i': i}).inserted_id for i in range(10)]\n\n _id = ids[5]\n doc = db.get_document(Doc, _id)\n\n assert doc is not None\n assert doc._id == _id\n assert doc.i == 5\n assert doc.__db__ is db\n\n\ndef test_get_document__not_found(db):\n col = db.db.testdocs\n [col.insert_one({'i': i}).inserted_id for i in range(10)]\n\n doc = db.get_document(Doc, ObjectId())\n\n assert doc is None\n\n\ndef test_get_document__not_found_exc(db):\n col = db.db.testdocs\n [col.insert_one({'i': i}).inserted_id for i in range(10)]\n\n class Exc(Exception):\n pass\n\n with pytest.raises(Exc):\n db.get_document(Doc, ObjectId(), exc=Exc)\n\n\ndef test_insert(db):\n doc = Doc()\n doc.i = 13\n\n db.insert(doc)\n\n assert db.db.testdocs.find().count() == 1\n assert db.db.testdocs.find()[0]['i'] == 13\n assert not doc.__changed__\n assert doc.__db__ is db\n\n\ndef test_save_new(db):\n doc = Doc()\n doc.i = 13\n\n db.save(doc)\n\n assert db.db.testdocs.find().count() == 1\n assert db.db.testdocs.find()[0]['i'] == 13\n assert not doc.__changed__\n assert doc.__db__ is db\n\n\ndef test_save(db):\n col = db.db.testdocs\n col.insert({'i': 13})\n\n doc = from_mongo(Doc, col.find_one({'i': 13}))\n doc.i = 26\n\n col.update({'_id': doc.id}, {'$set': {'b': True}})\n\n db.save(doc)\n\n assert doc.i == 26\n assert doc.b is True\n assert db.db.testdocs.find().count() == 1\n assert db.db.testdocs.find()[0]['i'] == 26\n assert db.db.testdocs.find()[0]['b'] is True\n assert not doc.__changed__\n assert doc.__db__ is db\n\n\ndef test_save_full(db):\n col = db.db.testdocs\n col.insert({'i': 13})\n\n doc = from_mongo(Doc, col.find_one({'i': 13}))\n doc.i = 26\n\n col.update({'_id': doc.id}, {'$set': {'b': True}})\n\n db.save(doc, full=True)\n\n assert doc.i == 26\n assert not hasattr(doc, 'b')\n assert db.db.testdocs.find().count() == 1\n assert db.db.testdocs.find()[0]['i'] == 26\n assert 'b' not in db.db.testdocs.find()[0]\n assert not doc.__changed__\n assert doc.__db__ is db\n\n\n@pytest.mark.parametrize('unset', [['i'], {'i': True}])\ndef test_update_one(db, unset):\n col = db.db.testdocs\n _id = col.insert({'i': 13})\n\n doc = from_mongo(Doc, col.find_one(_id))\n db.update_one(doc, set={'b': True}, unset=unset)\n\n assert doc.b\n assert not hasattr(doc, 'i')\n\n\ndef test_update_one__inc(db):\n col = db.db.testdocs\n _id = col.insert({'i': 12})\n\n doc = from_mongo(Doc, col.find_one(_id))\n db.update_one(doc, inc={'i': 1})\n\n assert doc.i == 13\n assert not hasattr(doc, 'b')\n\n\n@pytest.mark.parametrize('cmd, v, r', [\n ('push', 4, [1, 2, 3, 4]),\n ('pull', 2, [1, 3]),\n])\ndef test_update_one__push_pull(db, cmd, v, r):\n col = db.db.testdocs\n _id = col.insert({'l': [1, 2, 3]})\n\n doc = from_mongo(Doc, col.find_one(_id))\n db.update_one(doc, **{cmd: {'l': v}})\n\n assert doc.l == r\n\n\ndef test_remove(db):\n col = db.db.testdocs\n col.insert({'i': 13})\n\n doc = from_mongo(Doc, col.find_one({'i': 13}))\n\n assert col.count() == 1\n db.remove(doc)\n assert col.count() == 0\n\n\ndef test_reload(db):\n doc = Doc()\n doc.i = 1\n db.insert(doc)\n\n db.db.testdocs.update({'_id': doc.id}, {'i': 2})\n\n assert doc.i == 1\n new = db.reload(doc)\n assert doc.i == 2\n assert doc is new\n\n\ndef test_reload_new_instance(db):\n doc = Doc()\n doc.i = 1\n db.insert(doc)\n\n db.db.testdocs.update({'_id': doc.id}, {'i': 2})\n\n assert doc.i == 1\n new = db.reload(doc, new_instance=True)\n assert doc.i == 1\n assert doc is not new\n assert new.i == 2\n","sub_path":"tests/test_database.py","file_name":"test_database.py","file_ext":"py","file_size_in_byte":4591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"258568683","text":"from Tree.data2 import Data\nimport math\nimport random\nfrom Tree.Identifier import Identifier\nimport copy\n\n\nclass Node:\n __slots__ = 'children', 'identifier', 'data', 'maximumBet'\n\n def __init__(self, identifier: Identifier, data: Data, maximumBet = None):\n self.children = []\n self.identifier = identifier\n self.data = data\n # = None, if no bets available, = \"b1\" if b1 available, = \"b2\" if b1 & b2 available.\n self.maximumBet = maximumBet\n\n \"\"\" Finds a rooted subtree of node \"\"\"\n\n def subtree(self):\n from Tree.Tree import Tree\n\n new_root = copy.copy(self)\n\n T = Tree(new_tree=True, root=new_root)\n child_list = [new_root]\n\n while len(child_list) > 0:\n node = child_list.pop()\n for c in node.children:\n child_list.append(c)\n T.nodes[node.identifier.name] = node\n\n return T\n\n def find_distribution(self, win_probability, thresh=150):\n\n softmax_sum = 0\n softmax_distribution = []\n\n for child in self.children:\n child_split = child.data.find_split(win_probability)\n if child.data.N[child_split] > thresh:\n beta = 1\n else:\n beta = child.data.N[child_split] / thresh\n\n if child.data.fold_node:\n softmax_sum += math.exp(child.data.c_reward[child_split] * beta)\n\n else:\n\n if child.data.N[child_split] != 0:\n softmax_sum += math.exp((child.data.c_reward[child_split] /\n find_denom(child.data.N[child_split])) * beta)\n else:\n softmax_sum += 1\n\n for child in self.children:\n child_split = child.data.find_split(win_probability)\n if child.data.N[child_split] > thresh:\n beta = 1\n else:\n beta = child.data.N[child_split] / thresh\n\n if child.data.fold_node:\n softmax_distribution.append((child,\n math.exp(child.data.c_reward[child_split] * beta) /\n softmax_sum))\n else:\n if child.data.N[child_split] == 0:\n softmax_distribution.append((child, 1 / softmax_sum))\n\n else:\n\n softmax_distribution.append((child, math.exp((child.data.c_reward[child_split] /\n find_denom(child.data.N[\n child_split])) * beta) / softmax_sum))\n\n return softmax_distribution\n\n def select_child(self, win_probability, greedy=True, LOG=None, prob=25):\n # Zips the distribution into: Children, distribution values\n dis = self.find_distribution(win_probability)\n Children, distribution = zip(*dis)\n\n # Some probability of being epsilon-greedy:\n if greedy and random.randint(0, prob) == 1:\n child = random.choice(Children)\n\n if LOG is not None:\n LOG.log(\"E-greedy child selection\")\n\n return child, 1 / len(Children)\n\n # Otherwise use the soft-max distribution\n if LOG is not None:\n LOG.children_log(dis)\n child = random.choices(population=Children, weights=distribution, k=1)[0]\n\n return child, distribution[Children.index(child)]\n\n def is_leaf(self):\n if len(self.children) == 0:\n return True\n else:\n return False\n\n def add_child(self, new_node):\n self.children.append(new_node)\n\n def local_node(self):\n children = []\n for c in self.children:\n children.append(copy.copy(c))\n\n new_node = copy.copy(self)\n new_node.children = children\n for c in new_node.children:\n c.children = []\n\n return new_node\n\n def __str__(self):\n return str((self.identifier.name, self.data.__str__(), self.maximumBet))\n\n\ndef find_denom(n, c=0.998):\n return (c ** n - 1) / (c - 1)\n","sub_path":"Tree/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"616158970","text":"import cv2\nimport numpy as np\nimport math\n\ndef nb_missing(gate):\n nb = 0\n for corner in gate:\n if len(corner) == 0:\n nb += 1\n return nb\n\ndef new_corner(i, gate):\n corner = []\n x, y = gate[:, 0], gate[:, 1]\n if i == 0:\n x, y = np.min(x), np.min(y)\n elif i == 1:\n x, y = np.min(x), np.max(y)\n elif i == 2:\n x, y = np.max(x), np.min(y)\n else:\n x, y = np.max(x), np.max(y)\n return [x, y]\n\ndef calculate_last_corner(data):\n corner = []\n if len(data[2]) == 0:\n corner = [[data[3][0], data[1][1]]]\n elif len(data[3]) == 0:\n corner = [[data[2][0], data[0][1]]]\n elif len(data[0]) == 0:\n corner = [[data[1][0], data[3][1]]]\n elif len(data[1]) == 0:\n corner = [[data[0][0], data[2][1]]]\n else:\n corner = [[-1, -1]]\n\n return corner\n\ndef calculate_2_corners(data):\n corner = []\n # case of top missing\n if len(data[0]) == 0 and len(data[1]) == 0:\n corner = [\n [-1, data[3][1]],\n [-1, data[2][1]],\n ]\n elif len(data[2]) == 0 and len(data[3]) == 0:\n corner = [\n [1, data[1][1]],\n [1, data[0][1]],\n ]\n elif len(data[1]) == 0 and len(data[2]) == 0:\n corner = [\n [data[0][0], 1],\n [data[3][0], 1],\n ]\n elif len(data[0]) == 0 and len(data[3]) == 0:\n corner = [\n [data[1][0], -1],\n [data[2][0], -1],\n ]\n else:\n corner = [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]]\n return corner\n\ndef calculate_3_corners(data):\n if len(data[0]) != 0:\n corner = [\n [1, data[0][1]],\n [1, 1],\n [data[0][0], 1],\n ]\n elif len(data[1]) != 0:\n corner = [\n [1, data[1][1]],\n [data[1][0], -1],\n [1, -1],\n ]\n elif len(data[2]) != 0:\n corner = [\n [-1, -1],\n [data[2][0], -1],\n [-1, data[2][1]],\n ]\n elif len(data[3]) != 0:\n corner = [\n [data[3][0], 1],\n [-1, 1],\n [-1, data[3][1]],\n ]\n else:\n corner = [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]]\n return corner\n\ndef chollet_gate_fix_missing(frame):\n gate_normalized = []\n for gate in frame:\n if gate is None:\n gate = [[], [], [], []]\n if nb_missing(gate) == 1:\n n = 1\n last_corners = calculate_last_corner(gate)\n elif nb_missing(gate) == 2:\n n = 2\n last_corners = calculate_2_corners(gate)\n elif nb_missing(gate) == 3:\n n = 3\n last_corners = calculate_3_corners(gate)\n elif nb_missing(gate) == 4:\n n = 4\n last_corners = [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]]\n else:\n n = 0\n for corner in gate:\n if len(corner) == 0:\n gate_normalized += [last_corners[0][0], last_corners[0][1]]\n del last_corners[0]\n else:\n gate_normalized += [corner[0], corner[1]]\n\n center = np.array(gate_normalized, dtype=np.float32).reshape(4, -1)\n gate_normalized += (np.sum(center, axis=0) / 4.).tolist()\n return gate_normalized, n\n","sub_path":"route_planner/rendu/catkin_ws/src/ai/src/utils/gate_corner.py","file_name":"gate_corner.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"68967479","text":"\r\n# wrt version4,I use subset 1, where training dats is more balanced\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.utils import class_weight\r\nfrom keras.preprocessing.image import ImageDataGenerator, image,load_img\r\nfrom keras import backend as K\r\nfrom keras import models\r\nfrom keras import layers\r\nfrom keras import optimizers\r\nfrom keras.models import load_model\r\nfrom keras.models import model_from_json\r\n# set image dimension for Conv layer etc based on tensor flow or theano\r\nK.set_image_dim_ordering('tf')\r\nfrom keras.applications import InceptionResNetV2\r\nfrom keras.applications.inception_resnet_v2 import preprocess_input\r\nfrom keras.callbacks import ModelCheckpoint\r\nimport os\r\nimport sys\r\nimport glob\r\nimport argparse\r\n#K.clear_session()\r\nfrom keras.callbacks import ReduceLROnPlateau\r\n#************** Define the trainable layers in model****************\r\n# input shape for VGG16, modified for cropped data saved as 512 by 512\r\nW = 299\r\nH = 299\r\nnc = 3\r\nnclass = 2\r\nload_mod = 1\r\nif load_mod:\r\n #model = load_model('diabetic_v9.h5')\r\n json_file = open(\"diabetic_v9.json\", 'r')\r\n loaded_model_json = json_file.read()\r\n json_file.close()\r\n model = model_from_json(loaded_model_json)\r\n model.load_weights(\"diabetic_v9_weights.h5\")\r\n model.summary()\r\nelse:\r\n def Resnet_finetune_model():\r\n Resnet = InceptionResNetV2(weights='imagenet', include_top=False, input_shape=(W, H, nc))\r\n model = models.Sequential()\r\n # add Resnet as the base( no need to specify input size here)\r\n model.add(Resnet)\r\n model.add(layers.Flatten())\r\n model.add(layers.Dropout(0.1))\r\n model.add(layers.Dense(nclass, activation='softmax'))\r\n return model\r\n\r\n model = Resnet_finetune_model()\r\n model.summary()\r\n\r\n # instantiate the Resnet base model\r\n conv_bs = model.get_layer('inception_resnet_v2')\r\n print(\"This is no of trainable weights in base Resnet \"+ str(len(conv_bs.trainable_weights)))\r\n print(\"This is no of trainable weights in base Resnet and added dense layers before freezing\"+ str(len(model.trainable_weights)))\r\n #conv_bs.trainable = False\r\n FREEZE_LAYERS = 2 # freeze the first this many layers for training\\\r\n #conv_bs.summary()\r\n # for layer in conv_bs.layers:\r\n # layer.trainable = False\r\n # for layer in conv_bs.layers[7:10]:\r\n # layer.trainable = True\r\n # for layer in conv_bs.layers[11:14]:\r\n # layer.trainable = True\r\n # for layer in conv_bs.layers[15:18]:\r\n # layer.trainable = True\r\n for layer in conv_bs.layers[:FREEZE_LAYERS]:\r\n layer.trainable = False\r\n for layer in conv_bs.layers[FREEZE_LAYERS:]:\r\n layer.trainable = True\r\n print(\"This is no of trainable weights in base Resnet and added dense layers after freezing\"+ str(len(model.trainable_weights)))\r\n for layer in conv_bs.layers:\r\n print(layer.name + \"Trainable staus: \" + str(layer.trainable) + \"\\n\")\r\n\r\n\r\n #************************************************************\r\n #************ create data generator, load data, and fit the model ********************\r\n\r\nbs_pth = './Glaucoma-Normal_for_Sid/no_resize'\r\ntrain_dir = bs_pth + '/train'\r\nvalidation_dir = bs_pth + '/valid'\r\ntest_dir = bs_pth + '/test'\r\n\r\nbatch_size = 8\r\ndatagen_tr = ImageDataGenerator(preprocessing_function=preprocess_input,rotation_range=40,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.2,zoom_range=0.2,channel_shift_range=10,horizontal_flip=True,fill_mode='nearest')\r\ndatagen_vd = ImageDataGenerator(preprocessing_function=preprocess_input)\r\ntrain_gen = datagen_tr.flow_from_directory(train_dir,target_size=(W, H),batch_size=batch_size,class_mode='categorical',shuffle=True,interpolation=\"bilinear\")\r\nvd_gen = datagen_vd.flow_from_directory(validation_dir,target_size=(W, H),batch_size=batch_size,class_mode='categorical',shuffle=False,interpolation=\"bilinear\")\r\n\r\n#class_weights = class_weight.compute_class_weight('balanced', np.unique(train_gen.classes),train_gen.classes)\r\n\r\nnTrain = np.size(train_gen.classes)\r\nnVal = np.size(vd_gen.classes)\r\nepochs = 40\r\nsteps_per_epoch_tr = int(nTrain/ batch_size)\r\nsteps_per_epoch_val = int(nVal/batch_size)\r\n\r\nif not load_mod :\r\n model.compile(optimizer=optimizers.Adam(lr=1e-5),loss='categorical_crossentropy',metrics=['accuracy'])\r\n #reduce_lr = ReduceLROnPlateau(monitor='val_loss',factor=0.1,patience = 5,min_lr= 1e-7,verbose=1)\r\n # monitoring validation accuracy, and saving only the weights for best epoch\r\n checkpointer = ModelCheckpoint(filepath=\"diabetic_v9_bestWeights.h5\",monitor = 'val_acc',verbose=1,save_best_only=True)\r\n\r\n # show what happened in checkpoint\r\n callbacks_list = [checkpointer]\r\n # mdlfit=model.fit_generator(train_gen,steps_per_epoch = steps_per_epoch_tr,validation_data = vd_gen,\r\n # validation_steps = steps_per_epoch_val,epochs=epochs,class_weight=class_weights,callbacks=callbacks_list)\r\n mdlfit=model.fit_generator(train_gen,steps_per_epoch = steps_per_epoch_tr,validation_data = vd_gen,\r\n validation_steps = steps_per_epoch_val,epochs=epochs,callbacks=callbacks_list)\r\n if not load_mod:\r\n #model.save('diabetic_v9.h5')\r\n model.save_weights('diabetic_v9_weights.h5')\r\n model_json = model.to_json()\r\n with open('diabetic_v9.json', \"w\") as json_file:\r\n json_file.write(model_json)\r\n json_file.close()\r\n\r\n#***********************************************************************\r\n\r\n# ************plot training and validtion accuracy**********************\r\ndef smooth_curve(data,alpha):\r\n smooth_d = []\r\n for point in data:\r\n if smooth_d:\r\n prev = smooth_d[-1]\r\n smooth_d.append((prev * alpha) + point * (1 - alpha))\r\n else:\r\n smooth_d.append(point)\r\n\r\n return smooth_d\r\n\r\nif not load_mod :\r\n trn_acc = mdlfit.history['acc']\r\n val_acc = mdlfit.history['val_acc']\r\n epochs = range(len(trn_acc))\r\n plt.plot(epochs,trn_acc,'b-',label = 'Train accuracy')\r\n plt.plot(epochs,val_acc,'g-',label = 'Valid accuracy')\r\n plt.title('Accuracy')\r\n plt.legend(loc='center right')\r\n plt.savefig('./diabeticRetino/diabetic_v9_acc.png')\r\n plt.show()\r\n plt.plot(epochs,smooth_curve(trn_acc,0.8),'b-',label = 'Smoothed Train accuracy')\r\n plt.plot(epochs,smooth_curve(val_acc,0.8),'g-',label = 'Smoothed Valid accuracy')\r\n plt.title('Smoothed Accuracy')\r\n plt.legend(loc='center right')\r\n plt.savefig('./diabeticRetino/diabetic_v9_smooth_acc.png')\r\n plt.show()\r\n #plot training and validtion loss\r\n trn_loss = mdlfit.history['loss']\r\n val_loss = mdlfit.history['val_loss']\r\n epochs = range(len(trn_loss))\r\n plt.plot(epochs,trn_loss,'b-',label = 'Train Loss')\r\n plt.plot(epochs,val_loss,'g-',label = 'Valid Loss')\r\n plt.title('Loss')\r\n plt.legend(loc='center right')\r\n plt.savefig('./diabeticRetino/diabetic_v9_loss.png')\r\n plt.show()\r\n plt.plot(epochs,smooth_curve(trn_loss,0.8),'b-',label = 'Smoothed Train Loss')\r\n plt.plot(epochs,smooth_curve(val_loss,0.8),'g-',label = 'Smoothed Valid Loss')\r\n plt.title('Smoothed Loss')\r\n plt.legend(loc='center right')\r\n plt.savefig('./diabeticRetino/diabetic_v9_smooth_loss.png')\r\n plt.show()\r\n\r\n #******************************************************************\r\n\r\n# *************evalute on test data ************************************\r\n# methods 1 aS IN PAPER\r\n\r\ndef get_files(path):\r\n if os.path.isdir(path):\r\n files = glob.glob(os.path.join(path, '*'))\r\n elif path.find('*') > 0:\r\n files = glob.glob(path)\r\n else:\r\n files = [path]\r\n\r\n files = [f for f in files if f.endswith('png') or f.endswith('png')]\r\n if not len(files):\r\n sys.exit('No images found by the given path!')\r\n return files\r\nprint(\"***********Test data :predict class 0*************************************\")\r\nfiles = get_files(test_dir + '/0')\r\ncls_list = ['Normal','GandGS']\r\nprint(cls_list)\r\n# 2-d numpy arrray of probabibility of each class for each file\r\npred_c0 = np.empty((0, nclass))\r\nsum_true_class = np.size(files)\r\n\r\nfor f in files:\r\n img = image.load_img(f, target_size=(299,299))\r\n if img is None:\r\n continue\r\n x = image.img_to_array(img)\r\n x = preprocess_input(x)\r\n x = np.expand_dims(x, axis=0)\r\n pred = model.predict(x)[0] # [ [a,b]] so needs .x[0]\r\n pred_c0 = np.append(pred_c0,[pred],axis=0)\r\n # index of max prob\r\n indxmx = np.argmax(pred)\r\n if indxmx != 0:\r\n sum_true_class = sum_true_class - 1\r\n top_inds = pred.argsort()[::-1][:5]\r\n print(f)\r\n for i in top_inds:\r\n print(' {:.3f} {}'.format(pred[i], cls_list[i]))\r\nnp.savetxt('./diabeticRetino/diabetic_v9_predict_c0.txt', pred_c0)\r\nprint(\"calss 0 accuracy = \" + str( (sum_true_class/np.size(files))* 100 ) + '%')\r\n\r\nprint(\"***********Test data :predict class 1*************************************\")\r\n\r\nfiles = get_files(test_dir + '/1')\r\npred_c1 = np.empty((0, nclass))\r\nsum_true_class = np.size(files)\r\nfor f in files:\r\n img = image.load_img(f, target_size=(299,299))\r\n if img is None:\r\n continue\r\n x = image.img_to_array(img)\r\n x = preprocess_input(x)\r\n x = np.expand_dims(x, axis=0)\r\n pred = model.predict(x)[0] # net_final or net\\n\",\r\n # y = 0\r\n # ev = model.evaluate(x,y,batch_size= 1)\r\n pred_c1 = np.append(pred_c1, [pred], axis=0)\r\n # index of max prob\r\n indxmx = np.argmax(pred)\r\n if indxmx != 1:\r\n sum_true_class = sum_true_class - 1\r\n top_inds = pred.argsort()[::-1][:5] # gives indices [0,1]\r\n print(f)\r\n # print probabibily and coressponding class name\r\n for i in top_inds:\r\n print(' {:.3f} {}'.format(pred[i], cls_list[i]))\r\nnp.savetxt('./diabeticRetino/diabetic_v9_predict_c1.txt', pred_c1)\r\nprint(\"calss 1 accuracy = \" + str( (sum_true_class/np.size(files))* 100 ) + '%')\r\n\r\n\r\ntest_gen = datagen_vd.flow_from_directory(test_dir,target_size=(W, H),batch_size=1,class_mode='categorical',shuffle=False,interpolation=\"bicubic\")\r\n# predict on test data, and save differences\r\nfilenames = test_gen.filenames\r\nnTest = len(filenames)\r\ntst_pred = model.predict_generator(test_gen,steps=nTest)\r\ntest_pred = np.argmax(tst_pred,axis=1)\r\ntst_lbls = test_gen.classes\r\n\r\nplt.plot(range(nTest),tst_lbls,'b-',label = 'True Class Labels:Test')\r\nplt.plot(range(nTest),test_pred,'g-',label = 'Predicted Class Lables\"Test')\r\nplt.title('Test Prediction')\r\nplt.legend(loc='center right')\r\nplt.savefig('./diabeticRetino/diabetic_v9_predict.png')\r\n\r\ntst_stat = np.vstack((tst_lbls, test_pred)).T\r\nnp.savetxt('./diabeticRetino/diabetic_v9_predict.txt', tst_stat)\r\ndif = tst_lbls-test_pred\r\n# count number of zeros( where true class natches predicted class)\r\nprint('test_acc_again:' + str(np.count_nonzero(dif==0)/nTest))\r\n\r\n\r\n","sub_path":"diabetic_v9.py","file_name":"diabetic_v9.py","file_ext":"py","file_size_in_byte":10961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"568019615","text":"# function based full dice roller with statistics\r\nfrom random import randint\r\n\r\n\r\ndef xdx_eval(given_str, sign, get_the_avg, minimum_val2, max_val2):\r\n try:\r\n total_val = 0\r\n split_index = given_str.index(\"d\")\r\n num_of_dies = int(given_str[:split_index])\r\n die_val = int(given_str[split_index + 1:])\r\n if num_of_dies != 1:\r\n print(\"\\nrolling {} {} sided dice...\".format(num_of_dies, die_val))\r\n else:\r\n print(\"\\nrolling {} {} sided die...\".format(num_of_dies, die_val))\r\n for _ in range(num_of_dies): # number of times to roll the dice\r\n if get_the_avg: # only used when getting statistics\r\n if sign:\r\n minimum_val2 += 1\r\n max_val2 += die_val\r\n else:\r\n minimum_val2 -= die_val\r\n max_val2 -= 1\r\n current_roll = randint(1, die_val) # most important line\r\n if current_roll == die_val:\r\n print(\"You got the maximum roll of {0}!\".format(current_roll))\r\n else:\r\n print(\"You rolled a {1} out of {0}\".format(die_val, current_roll))\r\n total_val += current_roll\r\n return total_val, minimum_val2, max_val2\r\n except ValueError:\r\n print(\"That input was not valid, try again using notation like 2d8-3d5+5\")\r\n\r\n\r\ndef sign_pls(first_dig):\r\n if first_dig.isdecimal():\r\n return True\r\n elif \"+\" in first_dig:\r\n return True\r\n elif \"-\" in first_dig: # I can't bring myself to turn this into an else\r\n return False\r\n\r\n\r\ndef operator_index(strong): # gets the index of the next required split\r\n pos_incl = \"+\" in strong\r\n neg_incl = \"-\" in strong\r\n if pos_incl:\r\n where_pos = strong.index(\"+\")\r\n if neg_incl:\r\n where_neg = strong.index(\"-\")\r\n if pos_incl and not neg_incl:\r\n return where_pos\r\n elif neg_incl and not pos_incl:\r\n return where_neg\r\n elif pos_incl and neg_incl:\r\n if where_neg < where_pos:\r\n return where_neg\r\n else:\r\n return where_pos\r\n else:\r\n return len(strong)\r\n\r\n\r\ndef number_check(string):\r\n try:\r\n int(string)\r\n except:\r\n return False\r\n return True\r\n\r\n\r\ndef string_sorter(die_choose, get_average=False):\r\n die_choose.replace(\" \", \"\")\r\n grand_tot = max_val = minimum_val = 0 # resets all the values\r\n grp_amt = die_choose.count(\"+\")\r\n neg_amt = die_choose.count(\"-\")\r\n\r\n for i in range(grp_amt + neg_amt + 1): # +1 for if it is just a number\r\n if die_choose. replace(\" \", \"\") == \"\":\r\n break\r\n front_sign = sign_pls(die_choose[0]) # checks if is + or -\r\n if not die_choose[0].isnumeric():\r\n die_choose = die_choose[1:] # gets rid of +- at start of string\r\n next_indx = operator_index(die_choose)\r\n is_negative = 1 if front_sign else -1\r\n if front_sign:\r\n print(\"+\" + die_choose[:next_indx])\r\n else:\r\n print(\"-\" + die_choose[:next_indx])\r\n if number_check(die_choose[:next_indx]): # if the next thing is a number\r\n grand_tot += int(die_choose[:next_indx]) * is_negative\r\n minimum_val += int(die_choose[:next_indx]) * is_negative\r\n max_val += int(die_choose[:next_indx]) * is_negative\r\n else: # if the next thing is not just a number\r\n try:\r\n add_amount = xdx_eval(die_choose[:next_indx], front_sign, get_average, minimum_val, max_val)\r\n grand_tot += add_amount[0] * is_negative\r\n if get_average:\r\n minimum_val += add_amount[1]\r\n max_val += add_amount[2]\r\n except TypeError:\r\n print()\r\n return\r\n die_choose = die_choose[next_indx:] # takes off part that was just used\r\n\r\n if get_average:\r\n return grand_tot, minimum_val, max_val\r\n else:\r\n return grand_tot\r\n\r\n\r\ndef average_calculator(last_string):\r\n if last_string != \"\":\r\n display_result(string_sorter(last_string, True), last_string)\r\n else:\r\n print(\"you need to put in a calculation before finding its average\\n\")\r\n\r\n\r\ndef display_result(result, roll):\r\n if type(result) == tuple:\r\n print(\"\\nthe maximum possible roll for {} is:\".format(roll), result[2])\r\n print(\"the minimum roll is:\", result[1])\r\n print(\"the average roll is:\", (result[2] + result[1]) / 2)\r\n print(\"\\nyour total roll is:\", result[0], \"\\n\")\r\n else:\r\n print(\"\\nyour total roll is:\", result, \"\\n\")\r\n return\r\n\r\n\r\ndef main():\r\n repeat_saver = \"\"\r\n input_die = \"\"\r\n while \"quit\" not in input_die:\r\n input_die = input(\"enter the number and type of dice you would like \"\r\n \"to roll, type 'quit' to quit, hit enter to redo the last roll \"\r\n \"or 'avg' to see the probability of your last roll \\n\")\r\n if \"quit\" in input_die:\r\n continue\r\n input_die.replace(\" \", \"\")\r\n if input_die == \"\":\r\n input_die = repeat_saver\r\n if input_die == \"\":\r\n print(\"you don't have a calculation to redo, try again\\n\")\r\n continue\r\n print(\"redoing\", repeat_saver)\r\n\r\n if \"avg\" in input_die: # add chance of the roll happening\r\n average_calculator(repeat_saver)\r\n continue\r\n repeat_saver = input_die\r\n display_result(string_sorter(input_die, False), repeat_saver)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(\"welcome to dice roller 2018, an example roll is 2d4 + 3d6 - 4\\n\")\r\n main()","sub_path":"dice_roller.py","file_name":"dice_roller.py","file_ext":"py","file_size_in_byte":5667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"172624994","text":"# 给定一个非负整数数组,你最初位于数组的第一个位置。 \n# \n# 数组中的每个元素代表你在该位置可以跳跃的最大长度。 \n# \n# 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 \n# \n# 示例: \n# \n# 输入: [2,3,1,1,4]\n# 输出: 2\n# 解释: 跳到最后一个位置的最小跳跃数是 2。\n#   从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。\n# \n# \n# 说明: \n# \n# 假设你总是可以到达数组的最后一个位置。 \n# Related Topics 贪心算法 数组 \n# 👍 654 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution(object):\n def jump(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \"\"\"\n 贪心算法:通过局部最优得到全局最优解\n 贪心策略:反向查找,选择距离最后一个位置最远的那个位置,下标最小,直到数组的开始位置\n 返回steps\n 时间复杂度为O(N^2),会超时\n 空间复杂度为O(1)\n \"\"\"\n # position = len(nums) - 1\n # steps = 0\n # while position > 0:\n # for i in range(position):\n # if i + nums[i] >= position:\n # position = i\n # steps += 1\n # break\n # return steps\n\n \"\"\"\n 贪心策略:正向查找\n 时间复杂为O(N)\n 空间复杂度为O(1)\n \"\"\"\n max_pos, end, steps = 0, 0, 0\n for i in range(len(nums)-1):\n if max_pos >= i:\n max_pos = max(max_pos, i + nums[i]) # 维护能够达到的最大下标位置,直到被超越\n if i == end: # 这里太巧妙了,需要多理解,对于[2, 3, 1, 2, 4, 2, 3],0,2,4,跳三次\n end = max_pos\n steps += 1\n return steps\n\n\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_03/[45]跳跃游戏 II.py","file_name":"[45]跳跃游戏 II.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"68959939","text":"import argparse\nimport torch\n\n\nclass Options:\n def __init__(self):\n self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n self.initialized = False\n\n def initialize(self):\n self.parser.add_argument('--lr', type=float, default=0.001, help='initial learning rate for adam') # 0.001\n self.parser.add_argument('--gpu_ids', type=str, default='-1',\n help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')\n self.parser.add_argument('--beta1', type=float, default=0.5, help='momentum term of adam')\n self.parser.add_argument('--input_nc', type=int, default=4, help='# input parameters')\n # x1, x2\n self.parser.add_argument('--output_nc', type=int, default=4, help='# of output image channels')\n # y\n self.initialized = True\n self.isTrain = True\n\n def parse(self):\n if not self.initialized:\n self.initialize()\n self.opt = self.parser.parse_args()\n self.opt.isTrain = self.isTrain # train or test\n\n str_ids = self.opt.gpu_ids.split(',')\n self.opt.gpu_ids = []\n for str_id in str_ids:\n id = int(str_id)\n if id >= 0:\n self.opt.gpu_ids.append(id)\n\n # set gpu ids\n if len(self.opt.gpu_ids) > 0:\n torch.cuda.set_device(self.opt.gpu_ids[0])\n\n return self.opt\n","sub_path":"Trust_RL_agent/option/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"54111575","text":"import sys\r\n\r\n\r\ndef getFeatureData(featureFile, bias = 0):\r\n\t\r\n\tx = []\r\n\t\r\n\tdFile = open(featureFile, 'r')\r\n\t\r\n\ti = 0\r\n\t\r\n\tfor line in dFile:\r\n\t\r\n\t\trow = line.split()\r\n\t\t\r\n\t\trVec = [float(item) for item in row]\r\n\t\t\r\n\t\tif bias > 0:\r\n\t\t\r\n\t\t\trVec.insert(0, bias)\r\n\r\n\t\t#print('row {} : {}'.format(i,rVec))\r\n \r\n\t\tx.append(rVec) \r\n\t\t\r\n\t\ti += 1\r\n\t\t\r\n\tdFile.close()\r\n\t\r\n\treturn x\r\n\r\n\r\ndef getLabelData(labelFile, hyperPlaneClass = False):\r\n\r\n\tlFile = open(labelFile, 'r')\r\n\t\r\n\tlDict = {}\r\n\t\r\n\tfor line in lFile:\r\n\t\r\n\t\trow = line.split()\r\n\t\r\n\t#print('label : {}'.format(lDict))\r\n\t\t\r\n\t\tif hyperPlaneClass and int(row[0]) <= 0:\r\n\t\t\r\n\t\t\tlDict[int(row[1])] = -1\r\n\t\t\r\n\t\telse:\r\n\t\t\t\r\n\t\t\tlDict[int(row[1])] = int(row[0])\r\n\t\r\n\tlFile.close()\r\n\t\r\n\treturn lDict\r\n\r\n\r\ndef connectLabels(lsi, n, lsl):\r\n\t\r\n\tcheckList, lstest, lstrain = [i[1] for i in lsl], [], []\r\n\r\n\tfor i in (range(len(lsi))):\r\n\r\n\t\tfor j in range(len(lsl)):\r\n\r\n\t\t\tif lsl[j][1] == i:\r\n\r\n\t\t\t\tlsi[i].append(lsl[j][0])\r\n\t\t\t\r\n\t\tif i not in checkList:\r\n\r\n\t\t\tlstest.append(lsi[i])\r\n\t\t\t\r\n\t\telse:\r\n\r\n\t\t\tlstrain.append(lsi[i])\r\n\r\n\treturn lstrain, lstest\r\ndef sorting(featuresList,labelsList):\r\n\tn, tempL = len(featuresList), []\r\n\tfor i in range(n):\r\n\t\ttempL.append(labelsList[featuresList.index(min(featuresList))])\r\n\t\t\r\n\t\tlabelsList.pop(featuresList.index(min(featuresList)))\r\n\t\tfeaturesList.pop(featuresList.index(min(featuresList)))\r\n\r\n\treturn tempL\r\ndef gini_index(tempLableList,l_l):\r\n\tminimum = 10000000\r\n\tsplit = 0\t\r\n\t#print(tempLableList)\r\n\tfor j in range(1,len(tempLableList)-1,1):\r\n\t\t\r\n\r\n\t\tL_S,R_S = tempLableList[:j],tempLableList[j:]\r\n\t\tans = ((j/len(tempLableList))*(L_S.count(0)/j)*(1-L_S.count(0)/j))+(((len(tempLableList)-j)/len(tempLableList))*(R_S.count(0)/(len(tempLableList)-j))*(1-R_S.count(0)/(len(tempLableList)-j)))\r\n\t\t#print(L_S.count(1),R_S.count(1))\r\n\t\tif anstempLabelList[i][:int(len(tempLabelList[i])/2)].count(1):\r\n\t\tl_l = 0\r\n\t\tr_l = 1\r\n\telse:\r\n\t\tl_l = 1\r\n\t\tr_l =0\r\n\t\r\n\tgini.append(gini_index(tempLabelList[i],l_l)[0])\r\n\tsplit.append(gini_index(tempLabelList[i],l_l)[1])\r\nprint(gini,split)\r\nk = gini.index(min(gini))+1\r\ns = finalList[k][split[k]]\r\n#print('for column {}, gini index is lowest ({}) with condition \"if s < {} ans = {} else ans = {}\"'.format(k,gini[k],s,l_l,r_l))\r\nprint(\"coloumn number k = {} gives best split on s = {}\".format(k,s))","sub_path":"HW6/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"330220247","text":"# prototype a recommender system\n# idea is to combine user preference and popularity\n\ndef loadCosineMatrix():\n cosine = []\n with open('cosine.txt', 'r') as f:\n for line in f:\n if line == '':\n continue\n temp = line[:-1].split(',')\n cosine.append([float(a) for a in temp])\n return cosine\n\ndef loadAverage():\n average = []\n with open('average.txt', 'r') as f:\n for line in f:\n if line == '':\n continue\n temp = line.split(',')\n average.append([float(a) for a in temp])\n return average[0]\n\ndef normalize(l):\n if not l:\n return []\n mean = float(sum(l))/len(l)\n var = sum([(a - mean)**2 for a in l])/len(l)\n if var < 1e-10:\n return [mean]*len(l)\n else:\n return [(a - mean)*var**-0.5 for a in l]\n\ndef recommender(d, num_rec = 5):\n # load cosine\n cosine = loadCosineMatrix()\n average = loadAverage()\n \n distScores = [0]*100\n jokeScores = [0]*100\n \n # rating history\n for joke in d.keys():\n rating = d[joke]\n sign = 1 if rating > 0 else -1\n coeff = sign * (abs(rating)/5.0)**0.5\n for i in range(100):\n distScores[i] += coeff*cosine[joke-1][i]\n \n average = normalize(average)\n distScores = normalize(distScores)\n \n for i in range(len(jokeScores)):\n jokeScores[i] += 0.2*average[i] + 0.8*distScores[i]\n \n jokeScores = sorted([(score, i+1) for i, score in enumerate(jokeScores) if i+1 not in d], reverse = True)\n \n return [t[1] for t in jokeScores[:num_rec]]","sub_path":"my_project/recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377373598","text":"for case in range(1, int(input()) + 1):\n universe, moves = input().split()\n ans = 'IMPOSSIBLE'\n if moves.count('S') <= int(universe):\n ans = 0\n while True:\n strength, damage = 1, 0\n for m in moves:\n if m == 'C':\n strength *= 2\n else:\n damage += strength\n if damage <= int(universe):\n break\n # replace last occurrence of CS\n moves = moves[::-1].replace('SC', 'CS', 1)[::-1] \n ans += 1\n print('Case #{}: {}'.format(case, ans))\n","sub_path":"2018_qualification_round_saving_the_universe_again.py","file_name":"2018_qualification_round_saving_the_universe_again.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"111846256","text":"import pandas as pd\nimport numpy as np\nimport json\n\nfrom tensorflow import keras\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.linear_model import Lasso\nfrom sklearn.linear_model import Ridge\nfrom sklearn.linear_model import ElasticNet\nfrom sklearn.linear_model import HuberRegressor\nfrom sklearn.linear_model import LassoLars\nfrom sklearn.linear_model import PassiveAggressiveRegressor\nfrom sklearn.linear_model import SGDRegressor\n\nfrom sklearn.neighbors import KNeighborsRegressor\n\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.tree import ExtraTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.ensemble import BaggingRegressor\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.ensemble import ExtraTreesRegressor\nfrom sklearn.svm import SVR\nimport xgboost as xgb\nfrom lightgbm import LGBMRegressor\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\n\nfrom statsmodels.tools import eval_measures\nimport statsmodels.formula.api as smf\nimport statsmodels.api as sm\nfrom statsmodels.tsa.api import VAR\nfrom statsmodels.tsa.statespace.varmax import VARMAX\nfrom statsmodels.stats.stattools import durbin_watson\n\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom statsmodels.tsa.arima_model import ARIMA\n\nfrom fbprophet import Prophet\n\nclass learning_reg:\n def __init__ (self, SEED = 222):\n self.SEED = SEED\n\n\n\n\n # ███ ███ ██████ ██████ ███████ ██ ███████\n # ████ ████ ██ ██ ██ ██ ██ ██ ██\n # ██ ████ ██ ██ ██ ██ ██ █████ ██ ███████\n # ██ ██ ██ ██ ██ ██ ██ ██ ██ ██\n # ██ ██ ██████ ██████ ███████ ███████ ███████\n\n\n\n\n def get_models(self, list_chosen):\n \"\"\"Generate a library of base learners\n (Prophet works only if the data have the target in a pandas column named 'y' and a feature column with the tima data named 'ds')\n :param list_chosen: list with the names of the models to load\n :return: models, a dictionary with as index the name of the models, as elements the models\"\"\"\n\n linreg = LinearRegression(normalize=True, fit_intercept=True)\n dtr = DecisionTreeRegressor(random_state=self.SEED, min_samples_split=(0.018), min_samples_leaf= (0.007), max_depth=25)\n svrr = SVR(kernel='linear', epsilon=5)\n br = BaggingRegressor(n_estimators=350, max_samples=0.9, max_features=0.7, bootstrap=False, random_state=self.SEED)\n ada = AdaBoostRegressor(n_estimators=7, loss='exponential', learning_rate=0.01, random_state=self.SEED)\n rf = RandomForestRegressor(n_estimators=1000, max_depth= 30, max_leaf_nodes=1000, random_state=self.SEED)\n gbr = GradientBoostingRegressor(n_estimators=1000, learning_rate=0.01,random_state=self.SEED)\n xgbr1 = xgb.XGBRegressor(random_state=self.SEED)\n mdl = LGBMRegressor(n_estimators=1000, learning_rate=0.01)\n las = Lasso()\n rid = Ridge()\n en = ElasticNet()\n huber = HuberRegressor(max_iter=2000)\n lasl = LassoLars(max_iter=2000, eps = 1, alpha=0.5, normalize=False)\n pa = PassiveAggressiveRegressor(C=1, max_iter=4000, random_state=self.SEED)\n sgd = SGDRegressor(max_iter=2000, tol=1e-3)\n knn = KNeighborsRegressor(n_neighbors=20)\n ex = ExtraTreeRegressor()\n exs = ExtraTreesRegressor(n_estimators=1000)\n pro = Prophet(changepoint_prior_scale = 0.01)\n\n models_temp = {\n 'BaggingRegressor': br,\n 'RandomForestRegressor': rf,\n 'GradientBoostingRegressor': gbr,\n 'XGBRegressor': xgbr1,\n 'LGBMRegressor':mdl,\n 'ExtraTreesRegressor': exs,\n 'LinearRegression': linreg,\n 'SVR': svrr,\n 'AdaBoostRegressor': ada,\n 'LassoLars': lasl,\n 'PassiveAggressiveRegressor': pa,\n 'SGDRegressor': sgd,\n 'DecisionTreeRegressor': dtr,\n 'lasso': las,\n 'ridge': rid,\n 'ElasticNet': en,\n 'HuberRegressor': huber,\n 'KNeighborsRegressor': knn,\n 'ExtraTreeRegressor': ex,\n 'Prophet': pro}\n\n models = dict()\n for model in list_chosen:\n if model in models_temp:\n models[model] = models_temp[model]\n return models\n\n def get_ARIMA_models(self, y, order, x = None, type = 'ARIMA'):\n '''\n :param y: array with the targets, pandas series\n :param order: (p,d,q)\n :param x: matrix with the features, pandas. Used only if exogenous variables are present\n :param type: ARIMA, SARIMAX\n :return: model, ARIMA model\n '''\n if type == 'ARIMA':\n model = ARIMA(y, order = order, exog=x)\n elif type == 'SARIMAX':\n model = SARIMAX(y, order = (order[0], order[1], order[2]), seasonal_order=(order[3], order[4], order[5], order[6]), exog=x)\n return model\n\n def get_VAR_models(self, data, exog_data = None, order = None, type = 'VAR'):\n '''\n generate the model VAR. Vector Autoregression (VAR) is a multivariate forecasting algorithm that is used when two or more time series influence each other.\n You need atleast two time series (variables). The time series should influence each other.\n :param data: matrix with the all data, pandas. The model will try to predict the next value for each of the features.\n :param exog_train: If some features are non strictly influenced can be put in this matrix, pandas\n :param order: (p,q) order of the model for the number of AR and MA parameters to use, needed only with VARMAX\n :param type: VAR, VARMAX\n :return: model\n '''\n if type == 'VAR':\n model = VAR(data, exog=exog_data)\n if type == 'VARMAX':\n model = VARMAX(data, exog=exog_data, order=order)\n return model\n\n def get_deep_learning_model(self, input_dl, output_dl, active = 'linear', lost = 'mse', net_type = 'normal'):\n ''' generate the deep learning model'''\n # model = keras.Sequential()\n # act = 'relu'\n # model.add(keras.layers.Dense(4, activation=act, input_dim = input_dl))\n # model.add(keras.layers.Dense(1, activation = active))\n # opt = keras.optimizers.SGD(lr=0.04,momentum=0.9)\n # model.compile(optimizer = opt, loss = lost, metrics=['mae'])\n # return model\n\n if net_type == 'normal':\n model = keras.Sequential()\n model.add(keras.layers.Dense(256, input_dim=input_dl, activation='relu'))\n model.add(keras.layers.Dense(256, activation='relu'))\n model.add(keras.layers.Dense(128, activation='relu'))\n model.add(keras.layers.Dense(64, activation='relu'))\n model.add(keras.layers.Dense(32, activation='relu'))\n model.add(keras.layers.Dense(output_dl, activation='relu'))\n model.compile(loss='mae', optimizer = 'adam', metrics = ['accuracy'])\n\n if net_type == 'vgg':\n def vgg_block(layer_in, n_filters, n_conv):\n for _ in range(n_conv):\n layer_in = keras.layers.Conv1D(n_filters, 3, padding = 'same', activation = 'relu')(layer_in)\n layer_in = keras.layers.MaxPooling1D(2, strides = 2)(layer_in)\n return layer_in\n visible = keras.layers.Input(shape = (input_dl,1))\n layer = vgg_block(visible, 64, 4)\n layer = keras.layers.Dropout(0.1)(layer)\n layer = vgg_block(layer, 128, 4)\n layer = keras.layers.Dropout(0.2)(layer)\n layer = vgg_block(layer, 256, 8)\n layer = keras.layers.Dropout(0.3)(layer)\n flat1 = keras.layers.Flatten()(layer)\n hidden1 = keras.layers.Dense(512, activation = 'relu')(flat1)\n hidden1 = keras.layers.Dropout(0.4)(hidden1)\n output = keras.layers.Dense(output_dl, activation = 'relu')(hidden1)\n model = keras.models.Model(inputs = visible, outputs = output)\n model.compile(optimizer = 'adam', loss = 'mae', metrics=['accuracy'])\n return model\n\n\n\n # ████████ ██████ █████ ██ ███ ██ ██ ███ ██ ██████\n # ██ ██ ██ ██ ██ ██ ████ ██ ██ ████ ██ ██\n # ██ ██████ ███████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███\n # ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██\n # ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ████ ██████\n\n\n\n\n def train_models(self, models, xtrain, ytrain, epochs = 0, validation_data = None, shuffle = True, batch_size = 32):\n '''training function\n (Prophet works only if the data have the target in a pandas column named 'y' and a feature column with the tima data named 'ds')\n :param models: dictionary with as index the name of the models, as elements the models\n :param xtrain: matrix with the features, pandas or numpy\n :param ytrain: array with the targets, pandas or numpy\n :param epochs: epochs used if deep learning is in the models, or VAR as lag\n :param validation_data: data used to validate if deep learning is used, pandas or numpy\n :param shuffle: Boolean, used to shuffle the data before the training if deep learning is used\n :return: models, a dictionary with as index the name of the models, as elements the models after the training'''\n fitModel = 0\n for i, (name_model, model) in enumerate(models.items()):\n if name_model == 'deep learning normal':\n fitModel = model.fit(xtrain, ytrain, epochs = epochs, verbose = 1, validation_data= validation_data, shuffle = shuffle, batch_size = batch_size)\n elif name_model == 'deep learning vgg':\n xvgg = xtrain.copy()\n xvgg = xvgg.to_numpy()\n xvgg = xvgg.reshape(xvgg.shape[0], xvgg.shape[1], 1)\n validation_data_new = None\n if validation_data:\n xvgg_val = validation_data[0]\n xvgg_val = xvgg_val.to_numpy()\n xvgg_val = xvgg_val.reshape(xvgg_val.shape[0], xvgg_val.shape[1], 1)\n validation_data_new = (xvgg_val,validation_data[1])\n fitModel = model.fit(xvgg, ytrain, epochs = epochs, verbose = 1, validation_data= validation_data_new, shuffle = shuffle, batch_size = batch_size)\n elif name_model == 'ARIMA':\n model.fit(trend = 'nc', disp = 0)\n elif name_model == 'VAR':\n model.fit(epochs)# epochs represent the lag\n elif name_model == 'VARMAX':\n model.fit()\n elif name_model == 'Prophet':\n for col in xtrain.columns:\n if col != 'y' and col != 'ds':\n model.add_regressor(col)\n model.fit(xtrain)\n else:\n model.fit(xtrain, ytrain)\n return models, fitModel\n\n def train_hyperparameters(self, models, xtrain, ytrain, dict_grid, filename = 'param_file'):\n '''Training function for the hyperparameters search, valid only for the standard models\n :param models: dictionary with as index the name of the models, as elements the models\n :param xtrain: matrix with the features, pandas or numpy\n :param ytrain: array with the targets, pandas or numpy\n :param dict_grid: dictionary with the list of the paramters and the limits for the search\n :param filename: str, file name of the list with the resutls\n :return: dict_best_param, dictionary with the best parameters for each model in the models\n '''\n dict_best_param = {}\n for i, (name_model, model) in enumerate(models.items()):\n model_random = GridSearchCV(estimator=model, param_grid=dict_grid[name_model], cv=3, verbose=2, n_jobs=-1)\n model_random.fit(xtrain, ytrain)\n dic_h = model_random.best_params_\n dict_best_param[name_model] = dic_h\n with open(filename, 'w') as f:\n json.dump(dict_best_param, f)\n return dict_best_param\n\n def train_horizontal_ensamble(self, models, xtrain, ytrain, epochs, horizontal_perc = 0.1, shuffle = True):\n '''horizontal ensamble, valid only for the deep learning model\n :param models: dictionary with as index the name of the models, as elements the models\n :param xtrain: matrix with the features, pandas or numpy\n :param ytrain: array with the targets, pandas or numpy\n :param epochs: epochs used if deep learning is in the models\n :param horizontal_perc: from 0 to 1, percentual of epochs used to calculate the ensample\n :param shuffle: Boolean, used to shuffle the data before the training if deep learning is used\n :return: models, a dictionary with as index the name of the models, as elements the models where the deep learning is a list of models\n '''\n\n def load_horizontal_ensamble(model_list, epochs):\n all_models = list()\n for epoc in range(int(epochs - epochs*0.1), epochs):\n sing_model = keras.models.load_model('modelli/model_'+str(epoc)+'.h5')\n all_models.append(sing_model)\n model_list['deep learning'] = all_models\n return model_list\n\n name_model = 'deep learning'\n model = models[name_model]\n\n for epo in range(epochs):\n model.fit(xtrain, ytrain, epochs = 1, verbose = 1, shuffle = shuffle)\n if epo>=int(epochs - epochs*horizontal_perc):\n model.save('modelli/model_'+str(epo)+'.h5')\n\n models = load_horizontal_ensamble(models, epochs)\n return models\n\n def train_rolling_window(self, models, X_tot, Y_tot, frame_perc, epochs = 1, validation = False):\n '''train with rolling window, the function can be expanded to use the validation for checking purposes\n :param models: dictionary with as index the name of the models, as elements the models\n :param X_tot: matrix with the features, pandas or numpy\n :param Y_tot: array with the targets, pandas or numpy\n :param frame_perc: from 0 to 1, percentual of the dataset which create the size of the rolling window\n :param epochs: epochs used if deep learning is in the models\n :param validation: boolean, with True 30% of the data are use to validate if using deep learning model\n '''\n frame_size = int(X_tot.shape[0]*frame_perc)\n last_step = round(X_tot.shape[0]/frame_size)*frame_size - X_tot.shape[0]\n\n for step in range(round(X_tot.shape[0]/frame_size)):\n start_frame = step*frame_size\n end_frame = start_frame + frame_size\n x_frame = X_tot[start_frame:end_frame]\n y_frame = Y_tot[start_frame:end_frame]\n if validation:\n x_train, x_val, y_train, y_val = train_test_split(x_frame, y_frame, shuffle = False, test_size = 0.3)\n xy_val = (x_val, y_val)\n else:\n x_train, y_train = x_frame, y_frame\n xy_val = None\n models, _ = self.train_models(models, x_train, y_train, epochs = epochs, validation_data = xy_val, shuffle = False)\n\n if last_step != 0:\n x_frame = X_tot[last_step:]\n y_frame = Y_tot[last_step:]\n models, _ = self.train_models(models, x_frame, y_frame, epochs = epochs, validation_data = None, shuffle = False)\n return models\n\n def train_negative_binomial_model(self, x_train, y_train, test_size):\n '''generate and train the negative binomial model\n :param xtrain: matrix with the features, pandas or numpy\n :param ytrain: array with the targets, pandas or numpy\n :param test_size: from 0 to 1, percentual of train to use as test in the parameter evaluatio of the model\n :return: negative binomial model fitted\n '''\n x_train_train, x_train_test, y_train_train, y_train_test = train_test_split(x_train, y_train, shuffle = False, test_size = test_size)\n train = x_train_train.copy()\n test = x_train_test.copy()\n train['target'] = y_train_train\n test['target'] = y_train_test\n\n # Step 1: specify the form of the model\n model_formula = train.columns[0]\n for i in range(1, len(train.columns)-1):\n model_formula = model_formula+\" + \"+train.columns[i]\n model_formula = train.columns[-1] + ' ~ ' + model_formula\n\n grid = 10 ** np.arange(-8, -3, dtype=np.float64)\n best_alpha = []\n best_score = 1000\n # Step 2: Find the best hyper parameter, alpha\n for alpha in grid:\n model = smf.glm(formula=model_formula, data=train, family=sm.families.NegativeBinomial(alpha=alpha))\n results = model.fit()\n predictions = results.predict(test).astype(int)\n score = eval_measures.meanabs(predictions, test.total_cases)\n if score < best_score:\n best_alpha = alpha\n best_score = score\n\n # fit the final model\n data = x_train.copy()\n data['target'] = y_train\n model_formula = data.columns[0]\n for i in range(1, len(data.columns)-1):\n model_formula = model_formula+\" + \"+data.columns[i]\n model_formula = data.columns[-1] + ' ~ ' + model_formula\n\n # # Step 4: refit on entire dataset\n model = smf.glm(formula=model_formula, data=data, family=sm.families.NegativeBinomial(alpha=best_alpha))\n fitted_model = model.fit()\n\n return fitted_model\n\n\n\n\n # ███████ ██████ ██████ ███████ ██████ █████ ███████ ████████\n # ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██\n # █████ ██ ██ ██████ █████ ██ ███████ ███████ ██\n # ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██\n # ██ ██████ ██ ██ ███████ ██████ ██ ██ ███████ ██\n\n\n\n\n def predict_matrix_generator(self, models, xtest):\n '''generate the prediction with all the model in the list and add all of them to the same matrix, adding the average prediciton (ensamble)\n :param models: dictionary with as index the name of the models, as elements the models\n :param xtest: matrix with the features, pandas or numpy\n :return: Predict_matrix.shape[0] = xtest.shape[0], Predict_matrix.shape[1] = len(models) + 1, Pandas matrix with the predicion for all the models and the average for the ensamble\n '''\n Predict_matrix = pd.DataFrame()\n cols = list()\n for i, (name_model, model) in enumerate(models.items()):\n if name_model == 'SARIMAX' or name_model == 'ARIMA':\n Predict_matrix[name_model] = model.forecast(xtest.shape[0], exog = xtest).reset_index(drop = True)\n elif name_model == 'AUTOARIMA':\n Predict_matrix[name_model], confint = model.predict(n_periods=xtest.shape[0], return_conf_int=True, exogenous=xtest)\n elif name_model == 'VAR':\n self.forecast_priority = None # rappresenta i valori del training su cui verra proritizzata la predizione per il futuro, di solito sono le ultime entries prima del test_set, pandas\n Predict_matrix[name_model] = model.forecast(steps = xtest.shape[0], y = self.forecast_priority)\n elif name_model == 'VARMAX':\n self.exog_test = None # If some features are non strictly influenced can be put in this matrix, pandas\n Predict_matrix[name_model] = model.forecast(steps = xtest.shape[0], exog = self.exog_test)\n elif name_model == 'deep learning normal':\n Predict_matrix[name_model] = model.predict(xtest)[:,0]\n elif name_model == 'deep learning vgg':\n xvgg = xtest.copy()\n xvgg = xvgg.to_numpy()\n xvgg = xvgg.reshape(xvgg.shape[0], xvgg.shape[1], 1)\n Predict_matrix[name_model] = model.predict(xtest)[:,0]\n elif name_model == 'NegativeBinomial':\n Predict_matrix[name_model] = model.predict(xtest).to_numpy()\n elif name_model == 'Prophet':\n future = pd.DataFrame(xtest['ds'])\n Predict_matrix[name_model] = model.predict(future)['yhat']\n else:\n Predict_matrix[name_model] = model.predict(xtest)\n cols.append(name_model)\n Predict_matrix['Ensamble'] = Predict_matrix.mean(axis=1)\n return Predict_matrix\n\n def predict_rolling_ARIMA(self, ytrain, ytest, order, type):\n '''train ARIMA with rolling, it can be used to forecast as well\n :param ytrain: array with the targets, pandas series\n :param ytest: array with the targets, pandas series. If used to forecast the ytest has to be an empty series with the len of the prediction and the index of the temporal range\n :param order: (p,d,q)\n :param type: ARIMA, SARIMAX\n :return: ypred.shape[0] = ytest.shape[0], pandas series with the index of ytest\n '''\n history = [x for x in ytrain]\n ypred = list()\n models = dict()\n for t in range(ytest.shape[0]):\n models[type] = self.get_ARIMA_model(history, order = order, type=type)\n models[type] = self.train_models(models, 0, 0)\n pred = models[type].forecast()[0]\n ypred.append(pred)\n history.append(pred)\n ypred = pd.Series(ypred)\n ypred.index = ytest.index\n return ypred\n\n def predict_rolling_VAR(self, train, test, lag=0, order = None, type = 'VAR'):\n '''train VAR with rolling, it can be used to forecast as well.\n :param train: matrix with the all data to train, pandas. The model will try to predict the next value for each of the features.\n :param test: matrix with the all data to test and predict, pandas. The model will try to predict the next value for each of the features.\n :param lag: lag in the training for VAR model\n :param order: (p,q) order of the model for the number of AR and MA parameters to use, needed only with VARMAX\n :param type: VAR, VARMAX\n :return: final_pred.shape[0] = test.shape[0], final_pred.shape[1] = train.shape[1], pandas matrix\n '''\n history = train.copy()\n final_pred = pd.DataFrame()\n models = dict()\n for t in range(test.shape[0]):\n models[type] = self.get_VAR_models(history, order = order, type = type)\n models[type] = self.train_models(models, 0, 0, epochs=lag)\n pred = models[type].forecast(steps = 1)\n pred = pd.DataFrame(pred, columns = train.cloumns)\n final_pred = pd.concat([final_pred, pred], ignore_index = True)\n history = pd.concat([history, pred], ignore_index = True)\n return final_pred\n\n\n\n # ███████ ██████ ██████ ██████ ███████\n # ██ ██ ██ ██ ██ ██ ██\n # ███████ ██ ██ ██ ██████ █████\n # ██ ██ ██ ██ ██ ██ ██\n # ███████ ██████ ██████ ██ ██ ███████\n\n\n\n def score_VAR_correlation(self, models, x_train, lag = 0, maxlag=None):\n '''\n durbin_watson test\n the closer the result is to 2 then there is no correlation, the closer to 0 or 4 then correlation implies\n '''\n for i, (name_model, model) in enumerate(models.items()):\n if name_model == 'VAR':\n if maxlag != None:#studio hypersapce sul parametro lag\n vet_aic = []\n vet_bic = []\n vet_fpe = []\n vet_hqic = []\n for i in range(maxlag):\n result = model.fit(i)\n vet_aic.append(result.aic)\n vet_bic.append(result.bic)\n vet_fpe.append(result.fpe)\n vet_hqic.append(result.hqic)\n df_results = pd.DataFrame()\n df_results['AIC'] = vet_aic\n df_results['BIC'] = vet_bic\n df_results['FPE'] = vet_fpe\n df_results['HQIC'] = vet_hqic\n return df_results\n else:# fit diretto su un valore specifico di lag\n result = model.fit(lag)\n out = durbin_watson(result.resid)\n df_results = pd.DataFrame()\n for col, val in zip(x_train.columns, out):\n df_results[col] = [round(val, 2)]\n return df_results.T\n\n elif name_model == 'VARMAX':\n result = model.fit()\n out = durbin_watson(result.resid)\n df_results = pd.DataFrame()\n for col, val in zip(x_train.columns, out):\n df_results[col] = [round(val, 2)]\n return df_results.T\n\n def score_models(self, y_test, Predict_matrix):\n '''\n generate the score with the actual test target\n :param y_test: array with the actual targets, pandas or numpy\n :param Predict_matrix: array with the predicted targets for each model, pandas\n :return: df_score.shape[0] = num of models + 1, df_score.shape[1] = 5 (MAE, MSE, R2, R2 a mano, residual)\n '''\n df_score = pd.DataFrame()\n for name_model in Predict_matrix:\n SS_residual = ((y_test - Predict_matrix[name_model])**2).sum()\n df_y = pd.DataFrame()\n df_y['y_test'] = y_test\n df_y['y_pred'] = Predict_matrix[name_model]\n df_y['diff'] = (y_test - Predict_matrix[name_model])\n\n SS_Total = ((y_test - np.mean(y_test))**2).sum()\n r_square = 1 - (float(SS_residual))/SS_Total\n\n mae = mean_absolute_error(y_test, Predict_matrix[name_model])\n mse = mean_squared_error(y_test, Predict_matrix[name_model])\n r2 = r2_score(y_test, Predict_matrix[name_model])\n df_score[name_model] = [round(mae,3), round(mse,3), round(r2,3), round(r_square,3), round(SS_residual,3)]\n\n df_score = df_score.T\n df_score.columns = ['MAE', 'MSE', 'R2', 'R2 a mano', 'residual']\n return df_score\n","sub_path":"lib_models_regression.py","file_name":"lib_models_regression.py","file_ext":"py","file_size_in_byte":27691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"353723271","text":"# Copyright (c) 2015 Mirantis, Inc.\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 glance.artifacts.domain import proxy\nimport glance.common.artifacts.definitions as definitions\nimport glance.common.exception as exc\nfrom glance import i18n\n\n_ = i18n._\n\n\nclass ArtifactProxy(proxy.Artifact):\n def __init__(self, artifact, repo):\n super(ArtifactProxy, self).__init__(artifact)\n self.artifact = artifact\n self.repo = repo\n\n def set_type_specific_property(self, prop_name, value):\n if prop_name not in self.metadata.attributes.dependencies:\n return super(ArtifactProxy, self).set_type_specific_property(\n prop_name, value)\n # for every dependency have to transfer dep_id into a dependency itself\n if value is None:\n setattr(self.artifact, prop_name, None)\n else:\n if not isinstance(value, list):\n setattr(self.artifact, prop_name,\n self._fetch_dependency(value))\n else:\n setattr(self.artifact, prop_name,\n [self._fetch_dependency(dep_id) for dep_id in value])\n\n def _fetch_dependency(self, dep_id):\n # check for circular dependency id -> id\n if self.id == dep_id:\n raise exc.ArtifactCircularDependency()\n art = self.repo.get(artifact_id=dep_id)\n\n # repo returns a proxy of some level.\n # Need to find the base declarative artifact\n while not isinstance(art, definitions.ArtifactType):\n art = art.base\n return art\n\n\nclass ArtifactRepo(proxy.ArtifactRepo):\n def __init__(self, repo, plugins,\n item_proxy_class=None, item_proxy_kwargs=None):\n self.plugins = plugins\n super(ArtifactRepo, self).__init__(repo,\n item_proxy_class=ArtifactProxy,\n item_proxy_kwargs={'repo': self})\n\n def _check_dep_state(self, dep, state):\n \"\"\"Raises an exception if dependency 'dep' is not in state 'state'\"\"\"\n if dep.state != state:\n raise exc.Invalid(_(\n \"Not all dependencies are in '%s' state\") % state)\n\n def publish(self, artifact, *args, **kwargs):\n \"\"\"\n Creates transitive dependencies,\n checks that all dependencies are in active state and\n transfers artifact from creating to active state\n \"\"\"\n # make sure that all required dependencies exist\n artifact.__pre_publish__(*args, **kwargs)\n # make sure that all dependencies are active\n for param in artifact.metadata.attributes.dependencies:\n dependency = getattr(artifact, param)\n if isinstance(dependency, list):\n for dep in dependency:\n self._check_dep_state(dep, 'active')\n elif dependency:\n self._check_dep_state(dependency, 'active')\n # as state is changed on db save, have to retrieve the freshly changed\n # artifact (the one passed into the func will have old state value)\n artifact = self.base.publish(self.helper.unproxy(artifact))\n\n return self.helper.proxy(artifact)\n\n def remove(self, artifact):\n \"\"\"\n Checks that artifact has no dependencies and removes it.\n Otherwise an exception is raised\n \"\"\"\n for param in artifact.metadata.attributes.dependencies:\n if getattr(artifact, param):\n raise exc.Invalid(_(\n \"Dependency property '%s' has to be deleted first\") %\n param)\n return self.base.remove(self.helper.unproxy(artifact))\n\n\nclass ArtifactFactory(proxy.ArtifactFactory):\n def __init__(self, base, klass, repo):\n self.klass = klass\n self.repo = repo\n super(ArtifactFactory, self).__init__(\n base, artifact_proxy_class=ArtifactProxy,\n artifact_proxy_kwargs={'repo': self.repo})\n\n def new_artifact(self, *args, **kwargs):\n \"\"\"\n Creates an artifact without dependencies first\n and then adds them to the newly created artifact\n \"\"\"\n # filter dependencies\n no_deps = {p: kwargs[p] for p in kwargs\n if p not in self.klass.metadata.attributes.dependencies}\n deps = {p: kwargs[p] for p in kwargs\n if p in self.klass.metadata.attributes.dependencies}\n artifact = super(ArtifactFactory, self).new_artifact(*args, **no_deps)\n # now set dependencies\n for dep_param, dep_value in deps.iteritems():\n setattr(artifact, dep_param, dep_value)\n return artifact\n","sub_path":"glance/artifacts/dependency.py","file_name":"dependency.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"538812157","text":"# -*- coding: utf-8 -*-\nimport json\nimport jellyfish\nimport codecs\nimport re\n\ndef get_by_episode(nom):\n pass\n\ndef get_episode_by_id(ID):\n pass\n\ndef get_ids_same_episode(ID):\n pass\n\ndef get_episodes_by_year(year):\n \"\"\"\n Avec une année, on a touss les épisodes de cette année\n \"\"\"\n year = str(year)\n data = get_json(\"data/chronologie_moreau.json\")\n if year not in data:\n res = {\"Statut\": f\"Année '{year}' non trouvée\", \"Requête\":year, \"Années présentes\":list(data.keys())}\n return res \n etiquettes = [x[\"Etiquette Moreau\"] for x in data[year]]\n res = {\"Statut\": \"OK\", \"Requête\":year, \"Résultat\":etiquettes}\n return res\n\ndef get_all_episodes():\n \"\"\"\n TousAvec une année, on a toutes les Mazarinades datées de cette année\n \"\"\"\n all_years = get_episodes_by_year(000)[\"Années présentes\"]\n etiquettes = []\n for year in all_years:\n etiquettes.append({year : get_episodes_by_year(year)[\"Résultat\"]})\n res = {\"Statut\": \"OK\", \"Requête\":year, \"Résultat\":etiquettes}\n return res\n\ndef get_chronological():\n pass\n\n\ndef get_json(path):\n \"\"\" Ouvre un fichier JSON\"\"\"\n f = open(path)\n liste = json.load(f)\n f.close()\n return liste\ndef get_closest_v2(title, number = 10, lowercase=True, \n path_compare =\"data/all_burlesque_pages_corrected.json\", word_filter = True,\n seuil_simil = False, javeliser = False):\n \"\"\" \n En entrée, une chaîne de caractère et en option :\n le nombre de titres proches à retourner, par défaut : 10\n mettre en minuscules, par défaut: non\n le chemin des documents à comparer\n word_filter: premier filtre sur le nombre de mots en commun (impact sur le temps de calcul ?)\n seuil_simil: si activé (flottant) on ne donne que les docs au delà du seuil\n En sortie, la liste triée par ordre décroissant de similarité sous forme d'un triplet:\n distance, ID_moreau, titre concerné\n \"\"\"\n liste_depart = get_json(path_compare)\n #all_burlesque_pages_original_ocr.json\n #all_burlesque_pages_ocr_without_linebreak.json\n #all_burlesque_pages_corrected_without_linebreak.json\n #all_burlesque_pages_corrected.json\n #all_burlesque_pages_ocr_without_space.json\n liste=[]\n if lowercase==True:\n for i in liste_depart:\n liste.append(word.lower() for word in i)\n mots_titre = set(title.split())\n filtered_list = []\n for ID, chaine in liste:\n mots_candidat = set(chaine.split())\n inter = mots_titre.intersection(mots_candidat)\n ##Si moins de 5 mots en commun (ou de la moitié) inutile de garder le candidat\n if len(inter)>5 or len(inter)>(len(mots_titre)/2) or word_filter==False:\n filtered_list.append([len(inter), ID, chaine])\n f2 = []\n for len_inter, ID, chaine in filtered_list:\n if javeliser==True:\n title = re.sub(\"\\n| {2,}\", \" \", title)\n chaine = re.sub(\"\\n| {2,}\", \" \", chaine)\n sim = jellyfish.jaro_winkler(title,chaine)\n ## On garde quand la similarité est supérieure à 0.5\n f2.append([sim, ID, chaine])\n if seuil_simil!=False:\n f2 = [x for x in f2 if x[0]>seuil_simil]\n return sorted(f2, reverse=True)[:number]\n\n# old function :\ndef get_closest(title, path_data=\"data/liste_titres_ID.json\", number = 5, lowercase =True):\n \"\"\" \n En entrée, une chaîne de caractère (\n en option:\n le chemin du json du corpus considéré (par défaut: data/liste_titres_ID.json)\n le nombre de titres proches à retourner ( par défaut : 5)\n En sortie, la liste triée par ordre décroissant de similarité sous forme d'un triplet:\n distance, ID_moreau, titre concerné\n \"\"\"\n liste = get_json(path_data)\n if lowercase==True:\n title = title.lower()\n \n mots_titre = set(title.split())\n filtered_list = []\n for ID, chaine in liste:\n if lowercase==True:\n chaine = chaine.lower()\n mots_candidat = set(chaine.split())\n inter = mots_titre.intersection(mots_candidat)\n ##Si moins de 5 mots en commun (ou de la moitié) inutile de garder le candidat\n if len(inter)>3 or len(inter)>=(len(mots_titre)/2):\n filtered_list.append([len(inter), ID, chaine])\n f2 = []\n for len_inter, ID, chaine in filtered_list:\n if lowercase==True:\n chaine = chaine.lower()\n sim = jellyfish.jaro_winkler(title,chaine)\n ## On garde quand la similarité est supérieure à 0.5\n if sim>0.5:\n f2.append([sim, ID, chaine])\n return sorted(f2, reverse=True)[:number]\n\ndef open_utf8(path,lines=False):\n \"\"\"Ouvre un fichier texte\"\"\"\n f = codecs.open(path,'r','utf-8')\n if lines==True:\n out = f.readlines()\n out = [re.sub(\"\\n|\\r\",\"\",x) for x in out]\n else:\n out = f.read()\n f.close()\n return out\n\ndef write_utf8(path, out, verbose =True, is_json = False):\n \"\"\"\n En entrée, un chemin et un contenu (chaîne)\n Ecrit le contenu dans le chemin indiqué \n \"\"\"\n w = codecs.open(path,'w','utf-8')\n if is_json==False:\n w.write(out)\n else:\n w.write(json.dumps(out, indent=2, ensure_ascii=False))\n w.close()\n if verbose:\n print(\"Output written in '%s'\"%path)\n\n# +\n##get_closest(\"reine de france\", number = 2)\n\n# +\n#get_closest(\"Reine de France\", number = 2)\n\n# +\n#get_closest(\"Reine de France\", number = 2, path_data = \"clean.json\")\n#get_closest(\"Reine de France\", number = 2, path_data = \"dirty.json\")\n# -\n\n\n","sub_path":"antono_tools.py","file_name":"antono_tools.py","file_ext":"py","file_size_in_byte":5337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"93899204","text":"# !/usr/bin/python\n# coding:utf-8\nimport pymysql\nimport time\n\nconn = pymysql.connect(host='localhost', user='root', password='123win')\npymysql.charset = 'gbk'\ncur = conn.cursor()\nconn.select_db('xiaozhan')\nvalues = []\nfor i in range(10):\n value = (str(i), 'xiaxuan')\n values.append(value)\nprint(values)\n\nnow = time.strftime(\"%M:%S\")\ntry:\n cur.executemany(\"insert into student values(%s,%s)\", values)\n conn.commit()\nexcept Exception as err:\n print(err)\nfinally:\n cur.close()\n conn.close()\nend = time.strftime(\"%M:%S\")\n\n\n# 原文链接:https: // blog.csdn.net / u012734441 / article / details / 42269705","sub_path":"Mysql5.7.27/python3_mysql/executemany.py","file_name":"executemany.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"344408039","text":"#!/usr/bin/env python3\n\"\"\"\nwrites initial files for file storage\n\"\"\"\nimport datetime\n\ndef initial_files(file_list):\n \"\"\"\n creates temp files to be appended to\n \"\"\"\n FIRST_LINE = \"TIME: {}\\n\".format(str(datetime.datetime.now()))\n for f in file_list:\n with open(f, \"w\", encoding=\"utf-8\") as open_file:\n open_file.write(FIRST_LINE)\n\nif __name__ == \"__main__\":\n \"\"\"\n MAIN APP\n \"\"\"\n print('usage: import initial_files from file_io.write')\n","sub_path":"modules/file_io/write.py","file_name":"write.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"268422012","text":"# pylint: disable=no-self-use,invalid-name\nimport numpy\n\nfrom allennlp.data.vocabulary import Vocabulary\nfrom allennlp.data.fields import LabelField\nfrom allennlp.common.testing import AllenNlpTestCase\n\n\nclass TestLabelField(AllenNlpTestCase):\n\n def test_pad_returns_one_hot_array(self):\n label = LabelField(5, num_labels=10)\n array = label.as_array(label.get_padding_lengths())\n numpy.testing.assert_array_almost_equal(array, numpy.array([0, 0, 0, 0, 0, 1, 0, 0, 0, 0]))\n\n def test_label_field_can_index_with_vocab(self):\n vocab = Vocabulary()\n vocab.add_token_to_namespace(\"entailment\", namespace=\"labels\")\n vocab.add_token_to_namespace(\"contradiction\", namespace=\"labels\")\n vocab.add_token_to_namespace(\"neutral\", namespace=\"labels\")\n\n label = LabelField(\"entailment\")\n label.index(vocab)\n array = label.as_array(label.get_padding_lengths())\n numpy.testing.assert_array_almost_equal(array, numpy.array([1, 0, 0]))\n","sub_path":"tests/data/fields/label_field_test.py","file_name":"label_field_test.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"213051938","text":"import os.path\n\nfrom flask import Blueprint\nfrom flask import render_template\nfrom flask import send_from_directory\n\nfrom backend.locator import get_frontend_root\n\n\nstaticapi = \\\n Blueprint('static_api', __name__, template_folder='templates')\n\n\n@staticapi.route('/', methods=['GET'])\ndef serve_frontend():\n return render_template('webui.html',\n scripts=get_urls_for_frontend_resources(extension='.js'),\n stylesheets=get_urls_for_frontend_resources(extension='.css'))\n\n\n@staticapi.route('/static//', methods=['GET'])\ndef serve_static_content(directory, filename):\n if directory == 'lib':\n directory = 'node_modules'\n\n return send_from_directory(os.path.join(get_frontend_root(), directory), filename)\n\n\ndef get_urls_for_frontend_resources(extension: str) -> list:\n for dirpath, dirnames, filenames in os.walk(get_frontend_root()):\n for filename in [f for f in filenames if f.endswith(extension)]:\n url = os.path.join('static', os.path.relpath(os.path.join(dirpath, filename), get_frontend_root()))\n if 'node_modules' not in dirpath:\n yield url\n","sub_path":"backend/blueprints/staticapi.py","file_name":"staticapi.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"346832043","text":"import tensorflow as tf\nimport sys\nimport os\nimport subprocess\n\ntry:\n assert len(sys.argv) == 2\n version = [\"-buggy\", \"-fix\"][int(sys.argv[1])]\nexcept:\n print(\n \"Please run 'python test_script 0' for testing the buggy-version and \"\n \"'python test_script 1' for testing the fix-version.\\nAborted...\")\n exit(1)\n\ninterpreter_path = sys.executable\nprint(\"Running at: \", interpreter_path)\n\nassert tf.__version__ == \"1.8.0\"\n\n\ndef get_target_dir():\n for x in os.listdir(os.path.dirname(os.path.abspath(__file__))):\n if version in x:\n return x\n raise ValueError(\"No dir ends with %s!\" % version)\n\n\nsubprocess.call([interpreter_path, \"./%s/download.py\" % get_target_dir(), \"celebA\"])\nsubprocess.call(\n [interpreter_path, \"./%s/main.py\" % get_target_dir(), \"--is_train\", \"True\", \"--dataset\", \"celebA\", \"--is_crop\",\n \"True\", \"--batch_size\", \"10\", \"--checkpoint_dir\", \"checkpoint/%s\" % get_target_dir(), \"--sample_dir\",\n \"samples/%s\" % get_target_dir()])\n","sub_path":"Github/IPS-4/test_script.py","file_name":"test_script.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615183956","text":"import scrapy\nimport re\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapySchool_England.clearSpace import clear_space, clear_lianxu_space\nfrom scrapySchool_England.items import ScrapyschoolEnglandItem1\nfrom scrapySchool_England.getItem import get_item1\nfrom scrapySchool_England.getTuition_fee import getTuition_fee\nfrom scrapySchool_England.getIELTS import get_ielts\nfrom scrapySchool_England.getStartDate import getStartDate\nfrom scrapySchool_England.remove_tags import remove_class\nfrom scrapySchool_England.getDuration import getIntDuration, getTeachTime\n\nclass UniversityOfPlymouth_PSpider(CrawlSpider):\n name = \"UniversityOfPlymouth_P\"\n start_urls = [\"https://www.plymouth.ac.uk/courses?course_index=A&course_type=postgraduate\"]\n\n rules = (\n Rule(LinkExtractor(allow=r\"\\?course_index=[A-Z]&course_type=postgraduate\", allow_domains='www.plymouth.ac.uk'), follow=True, callback=\"parse_pagelist\"),\n # Rule(LinkExtractor(restrict_xpaths=r\"//ul[@class='course-list']/li/a\"), follow=False, callback=\"parse_data\"),\n Rule(LinkExtractor(restrict_xpaths=r\"//ul[@class='course-list']/li/a\", deny=r\"course_index=[A-Z]&partner=y\"), follow=False, callback=\"parse_data\"),\n )\n\n # def parse_pagelist(self, response):\n # print(response.url, \"**********\")\n\n def parse_data(self, response):\n item = get_item1(ScrapyschoolEnglandItem1)\n # item['country'] = \"England\"\n # item[\"website\"] = \"https://www.plymouth.ac.uk/\"\n item['university'] = \"University of Plymouth\"\n item['url'] = response.url\n # 授课方式\n item['teach_type'] = 'taught'\n # 学位类型\n item['degree_type'] = 2\n print(\"===============================\")\n print(response.url)\n try:\n # //span[@class='course-title']\n programme = response.xpath(\n \"//span[@class='course-title']//text()\").extract()\n clear_space(programme)\n item['programme_en'] = ''.join(programme).strip()\n # print(\"item['programme_en'] = \", item['programme_en'])\n\n degree_type = response.xpath(\n \"//h1[@class='hero-heading']/text()\").extract()\n clear_space(degree_type)\n item['degree_name'] = ''.join(degree_type).strip()\n # print(\"item['degree_name'] = \", item['degree_name'])\n\n degree_name_lower = item['degree_name'].lower()\n # print(\"degree_name_lower: \", degree_name_lower)\n if \"phd\" in degree_name_lower:\n item['teach_type'] = 'phd'\n item['degree_type'] = 3\n elif \"res\" in degree_name_lower:\n item['teach_type'] = 'research'\n item['degree_type'] = 3\n # print(\"item['teach_type'] = \", item['teach_type'])\n # print(\"item['degree_type'] = \", item['degree_type'])\n\n department = response.xpath(\n \"//h2[@class='school-title']//text()\").extract()\n clear_space(department)\n item['department'] = ''.join(department)\n # print(\"item['department'] = \", item['department'])\n\n # 课程长度\n duration = response.xpath(\"//td[contains(text(),'Duration')]/following-sibling::td//text()\").extract()\n clear_space(duration)\n # print(duration)\n duration_list = getIntDuration(''.join(duration))\n # print(\"duration_list: \", duration_list)\n if len(duration_list) == 2:\n item['duration'] = duration_list[0]\n item['duration_per'] = duration_list[-1]\n # print(\"item['duration'] = \", item['duration'])\n # print(\"item['duration_per'] = \", item['duration_per'])\n\n # mode\n mode = response.xpath(\"//td[contains(text(),'Course type')]/following-sibling::td//text()\").extract()\n clear_space(mode)\n # print(\"mode: \", mode)\n item['teach_time'] = getTeachTime(''.join(mode))\n # print(\"item['teach_time'] = \", item['teach_time'])\n\n # location\n location = response.xpath(\"//td[contains(text(),'Location')]/following-sibling::td//text()\").extract()\n clear_space(location)\n item['location'] = ''.join(location).strip()\n # print(\"item['location'] = \", item['location'])\n\n # overview\n overview1 = response.xpath(\"//div[@class='overview']\").extract()\n overview2 = response.xpath(\"//div[@id='key-features-accordion']\").extract()\n overview = remove_class(clear_lianxu_space(overview1)) + remove_class(clear_lianxu_space(overview2))\n item['overview_en'] = overview\n # print(\"item['overview_en'] = \", item['overview_en'])\n\n # modules\n modules = response.xpath(\"//div[@id='structure-accordion']\").extract()\n item['modules_en'] = remove_class(clear_lianxu_space(modules))\n # print(\"item['modules_en'] = \", item['modules_en'])\n\n # entry_requirements\n entry_requirements = response.xpath(\"//div[@id='entry-requirements-accordion']//text()\").extract()\n item['rntry_requirements'] = clear_lianxu_space(entry_requirements)\n # print(\"item['rntry_requirements'] = \", item['rntry_requirements'])\n\n # .{1,150}IELTS.{1,150}\n IELTS = re.findall(r\"(.{1,80}IELTS.{1,80})|(.{1,80}ILETS.{1,80})|(.{1,80}IELTs.{1,80})\", item['rntry_requirements'])\n # print(IELTS)\n if len(IELTS) != 0:\n ielts = ''.join(list(IELTS[0])).strip()\n item['ielts_desc'] = ielts\n print(\"item['ielts_desc'] = \", item['ielts_desc'])\n\n ieltsDict = get_ielts(item['ielts_desc'])\n item['ielts'] = ieltsDict.get(\"IELTS\")\n item['ielts_l'] = ieltsDict.get(\"IELTS_L\")\n item['ielts_s'] = ieltsDict.get(\"IELTS_S\")\n item['ielts_r'] = ieltsDict.get(\"IELTS_R\")\n item['ielts_w'] = ieltsDict.get(\"IELTS_W\")\n if item['ielts'] != None:\n item['ielts'] = item['ielts'].strip(\".\").strip()\n if item['ielts_l'] != None:\n item['ielts_l'] = item['ielts_l'].strip(\".\").strip()\n if item['ielts_s'] != None:\n item['ielts_s'] = item['ielts_s'].strip(\".\").strip()\n if item['ielts_r'] != None:\n item['ielts_r'] = item['ielts_r'].strip(\".\").strip()\n if item['ielts_w'] != None:\n item['ielts_w'] = item['ielts_w'].strip(\".\").strip()\n print(\"item['IELTS'] = %sitem['IELTS_L'] = %sitem['IELTS_S'] = %sitem['IELTS_R'] = %sitem['IELTS_W'] = %s==\" % (\n item['ielts'], item['ielts_l'], item['ielts_s'], item['ielts_r'], item['ielts_w']))\n\n # how_to_apply\n how_to_apply = response.xpath(\"//div[@id='how-to-apply-accordion']\").extract()\n item['apply_proces_en'] = remove_class(clear_lianxu_space(how_to_apply))\n # print(\"item['apply_proces_en'] = \", item['apply_proces_en'])\n\n # //html//div[@class='course-accordions']//tr[3]/td[3]\n # how_to_apply\n tuition_fee = response.xpath(\"//strong[contains(text(),'International')]/../following-sibling::*[2]//text()\").extract()\n clear_space(tuition_fee)\n # print(tuition_fee)\n tuition_fee_str = ''.join(tuition_fee)\n if tuition_fee_str == \"To be confirmed\" or tuition_fee_str == \"\":\n item['tuition_fee'] = None\n else:\n item['tuition_fee'] = int(tuition_fee_str.replace(\"£\", \"\").replace(\",\", \"\").strip())\n item['tuition_fee_pre'] = \"£\"\n # print(\"item['tuition_fee'] = \", item['tuition_fee'])\n # print(\"item['tuition_fee_pre'] = \", item['tuition_fee_pre'])\n\n # https://www.plymouth.ac.uk/international/study/international-students-country-guides/asia/china\n item['require_chinese_en'] = \"\"\"

Postgraduate

For postgraduate programmes, you'll need either a bachelor's degree (with high grades), a masters degree from a ranked Chinese university or a good honours degree from a British university. 

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Chinese degree classification - prestigious institutionChinese degree classification - non-prestigious institutionChinese degree classification - college institutionUK degree equivalent
80%85%90%1st
75%80%85%2:1
70%75%80%2:2
\"\"\"\n yield item\n except Exception as e:\n with open(item['university'] + str(item['degree_type']) + \".txt\", 'a', encoding=\"utf-8\") as f:\n f.write(str(e) + \"\\n\" + response.url + \"\\n========================\")\n print(\"异常:\", str(e))\n print(\"报错url:\", response.url)\n\n","sub_path":"yyx_crawler/scrapySchool_England/scrapySchool_England/spiders/UniversityOfPlymouth_P.py","file_name":"UniversityOfPlymouth_P.py","file_ext":"py","file_size_in_byte":9184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"325971666","text":"#!/usr/bin/env python3.5\n# -*- coding: utf-8 -*-\n\"\"\"\n@project: occurrence-abundance pattern (make data for Fig 6)\n@author: Roman Zapien-Campos - 2021\n\"\"\"\n\n# Import packages\n\nfrom sc_gillespie import gillespie\n\nimport numpy as np\n\n\n### Compute Data ###\n\n# Please comment/uncomment the following lines according to your needs\n\n# Fig6B.1\npanel = '6B.1'\ni = 11\nfrom par_gillespie_fig5C import *\n\n# # Fig6B.2\n# panel = '6B.2'\n# i = 37\n# from par_gillespie_fig5C import *\n\n# # Fig6C.1\n# panel = '6C.1'\n# i = 11\n# from par_gillespie_fig5C import *\n\n# # Fig6C.2\n# panel = '6C.2'\n# i = 37\n# from par_gillespie_fig5C import *\n\n# # Fig6D.1\n# panel = '6D.1'\n# i = 11\n# from par_gillespie_fig5C import *\n\n# # Fig6D.2\n# panel = '6D.2'\n# i = 37\n# from par_gillespie_fig5C import *\n\n\n# Values of migration, growth, death rate to test\np_change = np.logspace(-3,0,11)[:-1]\ngR_change = np.linspace(0.8,1.2,10)\ndR_change = np.linspace(0.8,1.2,10)\n\n# Vectors to store the computed values\nP0_nneutral = np.zeros(10)\nmean_freq_nneutral = np.zeros(10)\n\np_ = np.copy(p)\n\n# Compute the observables of each type\nfor k in range(10):\n\n # Specific parameter to test\n if panel[:2] == '6B':\n p = p_ / (1. - p_[i]) * (1. - p_change[k])\n p[i] = p_change[k]\n \n elif panel[:2] == '6C':\n gR[i] = gR_change[k] \n \n elif panel[:2] == '6D':\n dR[i] = dR_change[k]\n \n # Arguments for the gillespie simulation\n args = (N, m, time_sim, N_taxa, N_hosts, n_timepoints, p, gR, dR)\n \n # Gillespie simulation\n timeseries_time, timeseries_data = gillespie(args)\n \n # Mean frequency at equilibrium\n mean_freq_nneutral[k] = timeseries_data[:,-1,i].sum(0)/(N_hosts * N)\n \n # Probability of occurrence at equilibrium\n P0_nneutral[k] = (timeseries_data[:,-1,i]>0).sum(0)/N_hosts\n\n# Save data according to its kind\nif panel[:2] == '6B': np.savez_compressed('../data/%s.npz'%panel, N = N, m = m, time_sim = time_sim, S = N_taxa, N_hosts = N_hosts, n_timepoints = n_timepoints, gR = gR, dR = dR, P0_nneutral = P0_nneutral, mean_freq_nneutral = mean_freq_nneutral, p_change = p_change)\nelif panel[:2] == '6C': np.savez_compressed('../data/%s.npz'%panel, N = N, m = m, time_sim = time_sim, S = N_taxa, N_hosts = N_hosts, n_timepoints = n_timepoints, p = p, dR = dR, P0_nneutral = P0_nneutral, mean_freq_nneutral = mean_freq_nneutral, gR_change = gR_change)\nelif panel[:2] == '6D': np.savez_compressed('../data/%s.npz'%panel, N = N, m = m, time_sim = time_sim, S = N_taxa, N_hosts = N_hosts, n_timepoints = n_timepoints, p = p, gR = gR, P0_nneutral = P0_nneutral, mean_freq_nneutral = mean_freq_nneutral, dR_change = dR_change)","sub_path":"simulation/make_fig6_data.py","file_name":"make_fig6_data.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"590596012","text":"import datetime\n\n# 1 to summerTime, 0 to winterTime\nseasonAdjustmentTime = 1\n\ndef dateFromTimeZoneStr(a):\n\t# taking 20170117T123000Z as example\n\treturn datetime.date(int(a[:4]), int(a[4:6]), int(a[6:8]))\n\t\ndef timeFromTimeZoneStr(a):\n\treturn datetime.time(int(a[9:11]) +1 +seasonAdjustmentTime, int(a[11:13]))\n\nclass Event:\n\tdef __init__(self, summary, location, description, start, end):\n\t\tself.summary = summary\n\t\tself.location = location\n\t\tself.description = description\n\t\tself.start_date = dateFromTimeZoneStr(start)\n\t\tself.start_time = timeFromTimeZoneStr(start)\n\t\tself.end_date = dateFromTimeZoneStr(end)\n\t\tself.end_time = timeFromTimeZoneStr(end)\n\n\tdef weekDay(self):\n\t\tweek = ['Sunday',\n\t\t\t\t'Monday',\n\t\t\t\t'Tuesday',\n\t\t\t\t'Wednesday',\n\t\t\t\t'Thursday',\n\t\t\t\t'Friday',\n\t\t\t\t'Saturday']\n\t\tweekDayNumber = self.start_date.weekday()\n\t\treturn week[weekDayNumber]\n\n\tdef __repr__(self):\n\t\treturn \"start: \" + str(self.start_time)[:-3] + \\\n\t\t\t \" ~ \" + str(self.end_time)[:-3] + \\\n\t\t\t \"\\nroom: \" + self.location + \\\n\t\t\t \"\\ntheme: \" + self.summary\n","sub_path":"event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"121810807","text":"import selenium.webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom bs4 import BeautifulSoup\n\n\nclass TargetScraper:\n def __init__(self, product_model):\n self.price = \"\"\n self.product_model = product_model\n self.product_address = 'https://www.target.com/s?searchTerm={}'.format(product_model, product_model)\n self.headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0',\n }\n options = Options()\n options.add_argument('--headless')\n self.driver = selenium.webdriver.Chrome(options=options)\n self.data = self.driver.get(self.product_address)\n\n def retrieve_product_price(self):\n try:\n print(self.data.page_source)\n soup = BeautifulSoup(self.data.page_source, \"lxml\")\n print(soup)\n\n except AttributeError:\n self.price = \"Could Not Find Price\"\n\n\ntarget = TargetScraper(\"xbox\")\ntarget.retrieve_product_price()\n","sub_path":"target_scraper/target_scraper.py","file_name":"target_scraper.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"409217199","text":"from flask import Flask, render_template, request\nfrom flask_assets import Bundle, Environment\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.orm import backref\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///proyek.db'\ndb = SQLAlchemy(app)\n\nassets = Environment(app)\ncss = Bundle(\"src/main.css\", output=\"dist/main.css\", filters=\"postcss\")\n\nassets.register(\"css\", css)\ncss.build()\n\nclass sektorTable(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n alias_sektor = db.Column(db.String(length=1024), nullable=False)\n nama_sektor = db.Column(db.String(length=1024), nullable=False)\n pembangunan = db.relationship('pembangunanSektorTable', backref='relasi_antarsektor')\n\n def __repr__(self):\n return f'{self.id}'\n\nclass pembangunanSektorTable(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n kodeTender = db.Column(db.Integer())\n nilaiHps = db.Column(db.Integer())\n namaPembangunan = db.Column(db.String(length=2048), nullable=False)\n statusPembangunan = db.Column(db.String(length=1024), nullable=False)\n kualifikasiUsaha = db.Column(db.String(length=1024), nullable=False)\n syaratKualifikasi = db.Column(db.String(length=4096), nullable=False)\n relasi_sektor = db.Column(db.Integer(), db.ForeignKey('sektor_table.id'))\n\n def __repr__(self):\n return f'{self.kodeTender}'\n\nclass kerjasamaTable(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n aliasInstansi = db.Column(db.String(length=1024), nullable=False)\n namaInstansi = db.Column(db.String(length=1024), nullable=False)\n\n def __repr__(self):\n return f'{self.aliasInstansi}'\n\n@app.route(\"/home\")\ndef home():\n sektor = sektorTable.query.all()\n instansi = kerjasamaTable.query.all()\n return render_template(\"index.html\", sektor = sektor, instansi = instansi)\n\n@app.route(\"/sektor/\")\ndef sektor(sektor):\n sektor = sektorTable.query.filter_by(id = sektor).first()\n return render_template(\"sektor.html\", sektor = sektor)\n\n@app.route(\"/detail/\")\ndef detail(kodeTender):\n detail = pembangunanSektorTable.query.filter_by(kodeTender = kodeTender).first()\n return render_template(\"detail.html\", detail = detail)\n\n@app.route('/faq')\ndef faq():\n return render_template(\"faq.html\")\n\n@app.route('/laporkan')\ndef laporkan():\n return render_template(\"laporkan.html\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"85130833","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n p1 = l1\n p2 = l2\n result = ListNode(0)\n p3 = result\n\n value = 0\n while p1 is not None or p2 is not None or value:\n if p1 is not None:\n value += p1.val\n p1 = p1.next\n if p2 is not None:\n value += p2.val\n p2 = p2.next\n\n p3.next = ListNode(value % 10)\n p3 = p3.next\n value = value / 10\n\n return result.next\n","sub_path":"add_two_numbers.py","file_name":"add_two_numbers.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"246226043","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2/20/18 11:37 AM \n\n@author: Hantian Liu\n\"\"\"\n\nimport os, csv, transforms3d, pickle\nfrom UKF import UKF, init\nfrom utils import quart2mat\nimport numpy as np\nfrom sklearn.cluster import KMeans\n\nfoldername=\"./train_data\"\nchoice=\"w\"\n\ndef filter(ts, omgx, omgy, omgz, accx, accy, accz):\n\t\"\"\"\n\tprocess data with UKF, to get filtered data in the form of Euler angles\n\t:param ts: [float] n\n\t:param omgx: [float] n angular velocity\n\t:param omgy: [float] n\n\t:param omgz: [float] n\n\t:param accx: [float] n\n\t:param accy: [float] n\n\t:param accz: [float] n\n\t:return: data [float] n*3\n\t\"\"\"\n\tmu, sigma = init()\n\tdata = np.zeros([len(ts), 3])\n\tfor i in range(len(ts)):\n\t\tmu, sigma, q_ukf = UKF(omgx, omgy, omgz, ts, i, mu, sigma, True, accx, accy, accz)\n\t\t# q.append(q_ukf)\n\t\tmy_mat = quart2mat(q_ukf)\n\t\ty, p, r = transforms3d.euler.mat2euler(my_mat, axes = 'szyx')\n\t\tdata[i, 0] = y\n\t\tdata[i, 1] = p\n\t\tdata[i, 2] = r\n\treturn data\n\n\ndef txttoData(foldername, choice, is_beat3, is_beat4):\n\t\"\"\"\n\tread txt files, i.e. training data, under certain motion of interest,\n\tto get data representing orientations in Euler angles (if filtered), or in original form (if not filtered)\n\t:param foldername: [str] folder name\n\t:param choice: [str] initial of the motion name\n\t:param is_beat3: [boolean] to distinguish beat3 and beat4\n\t:param is_beat4: [boolean]\n\t:return: data_choice [float] n*6\n\t length [float] n : record corresponding length of the data\n\t\"\"\"\n\t#add first row for future stack\n\tdata_choice = np.zeros([1,6]) #TODO\n\tlength= []\n\tfor filename in os.listdir(foldername):\n\t\t#find the motion of interest via initial\n\t\tif filename[0]==choice:\n\t\t\t# distinguish beat3 and beat4 in \"b\"\n\t\t\tif is_beat3==False and is_beat4==False:\n\t\t\t\ta = []\n\t\t\t\twith open(os.path.join(foldername, filename)) as f:\n\t\t\t\t\t#read lines in file\n\t\t\t\t\tfor line in f:\n\t\t\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\t\t\tline = line.split(\"\\t\")\n\t\t\t\t\t\ta.append(np.asarray(line))\n\t\t\t\ta = np.asarray(a)\n\t\t\t\ta = a.astype(np.float)\n\t\t\t\tts = a[:, 0]\n\t\t\t\taccx = a[:, 1]\n\t\t\t\taccy = a[:, 2]\n\t\t\t\taccz = a[:, 3]\n\t\t\t\tomgx = a[:, 4]\n\t\t\t\tomgy = a[:, 5]\n\t\t\t\tomgz = a[:, 6]\n\n\t\t\t\tdata = a[:,1:]\n\t\t\t\t#filter data using UKF\n\t\t\t\t#data=filter(ts, omgx, omgy, omgz, accx, accy, accz) #TODO\n\t\t\t\t#append it to list of all data\n\t\t\t\tdata_choice=np.vstack((data_choice, data))\n\t\t\t\tlength.append(len(data))\n\n\t\t\t#distinguish beat3 and beat4 in \"b\"\n\t\t\telif is_beat3==True:\n\t\t\t\tif filename[4]==\"3\":\n\t\t\t\t\ta = []\n\t\t\t\t\twith open(os.path.join(foldername, filename)) as f:\n\t\t\t\t\t\t# read lines in file\n\t\t\t\t\t\tfor line in f:\n\t\t\t\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\t\t\t\tline = line.split(\"\\t\")\n\t\t\t\t\t\t\ta.append(np.asarray(line))\n\t\t\t\t\ta = np.asarray(a)\n\t\t\t\t\ta = a.astype(np.float)\n\t\t\t\t\tts = a[:, 0]\n\t\t\t\t\taccx = a[:, 1]\n\t\t\t\t\taccy = a[:, 2]\n\t\t\t\t\taccz = a[:, 3]\n\t\t\t\t\tomgx = a[:, 4]\n\t\t\t\t\tomgy = a[:, 5]\n\t\t\t\t\tomgz = a[:, 6]\n\n\t\t\t\t\tdata = a[:, 1:]\n\t\t\t\t\t# filter data using UKF\n\t\t\t\t\t#data = filter(ts, omgx, omgy, omgz, accx, accy, accz)\n\t\t\t\t\t# append it to list of all data\n\t\t\t\t\tdata_choice = np.vstack((data_choice, data))\n\t\t\t\t\tlength.append(len(data))\n\n\t\t\t# distinguish beat3 and beat4 in \"b\"\n\t\t\telif is_beat4==True:\n\t\t\t\tif filename[4] == \"4\":\n\t\t\t\t\ta = []\n\t\t\t\t\twith open(os.path.join(foldername, filename)) as f:\n\t\t\t\t\t\t# read lines in file\n\t\t\t\t\t\tfor line in f:\n\t\t\t\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\t\t\t\tline = line.split(\"\\t\")\n\t\t\t\t\t\t\ta.append(np.asarray(line))\n\t\t\t\t\ta = np.asarray(a)\n\t\t\t\t\ta = a.astype(np.float)\n\t\t\t\t\tts = a[:, 0]\n\t\t\t\t\taccx = a[:, 1]\n\t\t\t\t\taccy = a[:, 2]\n\t\t\t\t\taccz = a[:, 3]\n\t\t\t\t\tomgx = a[:, 4]\n\t\t\t\t\tomgy = a[:, 5]\n\t\t\t\t\tomgz = a[:, 6]\n\n\t\t\t\t\tdata = a[:, 1:]\n\t\t\t\t\t# filter data using UKF\n\t\t\t\t\t#data = filter(ts, omgx, omgy, omgz, accx, accy, accz)\n\t\t\t\t\t# append it to list of all data\n\t\t\t\t\tdata_choice = np.vstack((data_choice, data))\n\t\t\t\t\tlength.append(len(data))\n\t#delete first row\n\tdata_choice = data_choice[1:,:]\n\t#turn the list to array\n\tlength=np.asarray(length)\n\n\treturn data_choice, length\n\n\ndef cluster(foldername, M):\n\t\"\"\"\n\tread all data under folder, cluster and assign label as the observation sequence for all the data sets\n\t:param foldername: [str]\n\t:param M: # of observation classes i.e. # of clusters\n\t:return: each motion is saved as a list, consists of all corresponding observance sequences as array\n\t\"\"\"\n\t#read all data from txt\n\tdata_w, len_w = txttoData(foldername, \"w\", False, False)\n\tdata_i, len_i = txttoData(foldername, \"i\", False, False)\n\tdata_e, len_e = txttoData(foldername, \"e\", False, False)\n\tdata_b3, len_b3 = txttoData(foldername, \"b\", True, False)\n\tdata_b4, len_b4 = txttoData(foldername, \"b\", False, True)\n\tdata_c, len_c = txttoData(foldername, \"c\", False, False)\n\t#stack sequence = label sequence\n\tall_data=np.vstack((data_w,data_i,data_e, data_b3, data_b4, data_c))\n\n\t#cluster\n\tkmeans=KMeans(n_clusters=M).fit(all_data)\n\tlabels=kmeans.labels_\n\n\t# save the model to disk\n\tfilename = 'kmeans_model.sav'\n\tpickle.dump(kmeans, open(filename, 'wb'))\n\n\t#assign labels to each type of motion\n\t#obtain discreted observation sequence\n\tobs_w=[]\n\tcounter=0\n\tfor i in range(len(len_w)):\n\t\tobs_w.append(labels[counter:counter+len_w[i]])\n\t\tcounter=counter+len_w[i]\n\tobs_i = []\n\tfor i in range(len(len_i)):\n\t\tobs_i.append(labels[counter:counter + len_i[i]])\n\t\tcounter = counter + len_i[i]\n\tobs_e = []\n\tfor i in range(len(len_e)):\n\t\tobs_e.append(labels[counter:counter + len_e[i]])\n\t\tcounter = counter + len_e[i]\n\tobs_b3 = []\n\tfor i in range(len(len_b3)):\n\t\tobs_b3.append(labels[counter:counter + len_b3[i]])\n\t\tcounter = counter + len_b3[i]\n\tobs_b4 = []\n\tfor i in range(len(len_b4)):\n\t\tobs_b4.append(labels[counter:counter + len_b4[i]])\n\t\tcounter = counter + len_b4[i]\n\tobs_c = []\n\tfor i in range(len(len_c)):\n\t\tobs_c.append(labels[counter:counter + len_c[i]])\n\t\tcounter = counter + len_c[i]\n\n\treturn obs_w, obs_i, obs_e, obs_b3, obs_b4, obs_c\n\n\nif __name__ == '__main__':\n\tM = 90\n\tobs_w, obs_i, obs_e, obs_b3, obs_b4, obs_c=cluster(foldername, M)\n\tnp.save('obs_w.npy', np.asarray(obs_w))\n\tnp.save('obs_i.npy', np.asarray(obs_i))\n\tnp.save('obs_e.npy', np.asarray(obs_e))\n\tnp.save('obs_b3.npy', np.asarray(obs_b3))\n\tnp.save('obs_b4.npy', np.asarray(obs_b4))\n\tnp.save('obs_c.npy', np.asarray(obs_c))\n\n\n\n\n","sub_path":"readTxt.py","file_name":"readTxt.py","file_ext":"py","file_size_in_byte":6177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"255345774","text":"\n\nfrom xai.brain.wordbase.nouns._tanner import _TANNER\n\n#calss header\nclass _TANNERS(_TANNER, ):\n\tdef __init__(self,): \n\t\t_TANNER.__init__(self)\n\t\tself.name = \"TANNERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"tanner\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_tanners.py","file_name":"_tanners.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"497382501","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('catalog', '0004_auto_20151204_1258'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Option',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('key', models.CharField(verbose_name='Key', max_length=255)),\n ('value', models.CharField(verbose_name='Value', max_length=255)),\n ],\n ),\n ]\n","sub_path":"catalog/migrations/0005_option.py","file_name":"0005_option.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"121455082","text":"from SqlHelper import MsSqlHelper\nimport pandas as pd\nimport time\n\nmssql = MsSqlHelper(host='192.168.0.99', user='sa', passwd='comfortgroup2016{', database='COMFORT')\n\n\ndef CpSelect(pinhao, pinhao2=None):\n\tif pinhao2 is None:\n\t\tpinhao2 = pinhao\n\n\tsqlStr = r\"SELECT '{1}' 材料品号,RTRIM(MB025) 品号属性, RTRIM(MB001) 上阶, RTRIM(MB002) 品名, RTRIM(MB003) 规格 \" \\\n\t\t\t r\"FROM INVMB WHERE MB025='M' AND MB109='Y' AND MB001 = '{0}' \"\n\t# print(sqlStr.format(pinhao2, pinhao))\n\tget = mssql.sqlWork(sqlStr=sqlStr.format(pinhao2, pinhao))\n\n\tif get is not None:\n\t\trtnList.append(get[0])\n\t\treturn rtnList\n\telse:\n\t\treturn None\n\n\ndef Select(pinhao, pinhao2=None):\n\tglobal sqlCount\n\tif pinhao2 is None:\n\t\tpinhao2 = pinhao\n\n\tsqlStr = r\"SELECT '{1}' 材料品号, RTRIM(MB025) 品号属性, RTRIM(CB001) 上阶, RTRIM(MB002) 品名, RTRIM(MB003) 规格 \" \\\n\t\t r\"FROM BOMCB INNER JOIN INVMB ON MB001 = CB001 AND MB109 = 'Y' \" \\\n\t\t r\"WHERE (ISNULL(RTRIM(CB014), '') = '' OR CB014 >= CONVERT(VARCHAR(8), GETDATE(), 112)) AND CB005 = '{0}' \" \\\n\t\t\t r\"ORDER BY CB001 \"\n\n\t# print(sqlStr.format(pinhao2))\n\n\tget = mssql.sqlWork(sqlStr=sqlStr.format(pinhao2, pinhao))\n\tsqlCount += 1\n\tif get is not None:\n\t\tfor row_tmp in get:\n\t\t\tshuxing = row_tmp[1]\n\t\t\tshangjie = row_tmp[2]\n\n\t\t\tif shuxing == 'M':\n\t\t\t\trtnList.append(row_tmp)\n\t\t\t\t# print(row_tmp)\n\t\t\telse:\n\t\t\t\tSelect(pinhao, shangjie)\n\n\treturn rtnList\n\n\ndef getPh():\n\tdf0 = pd.read_excel('000.xlsx')\n\tlist2 = []\n\tfor index in range(len(df0)):\n\t\tph = str(df0.at[index, '主件品号'])\n\t\tlist2.append(ph.rstrip())\n\n\treturn list2\n\n\nif __name__ == '__main__':\n\t# getPh()\n\tsqlCount = 1\n\tstartdate = time.ctime()\n\tpinhao = ['24004481', '24000728', '24000695']\n\t# pinhao = getPh()\n\trtnList = []\n\tfor p_tmp in pinhao:\n\t\tif CpSelect(p_tmp) is None:\n\t\t\tr = Select(p_tmp)\n\n\tdf = pd.DataFrame(columns=['材料品号', '品号属性', '成品品名', '成品品号', '成品规格'], data=rtnList)\n\t# 删除列\n\tdf2 = df.drop(['材料品号', '品号属性'], axis=1)\n\t# # 去重\n\tdf2.drop_duplicates(keep='first', inplace=True)\n\tdf.to_excel('成品0.xlsx', sheet_name='Sheet1', index=False)\n\n\tenddate = time.ctime()\n\tprint('开始时间:' + startdate)\n\tprint('结束时间:' + enddate)\n\t# print(sqlCount)\n\t# print(len(rtnList))\n","sub_path":"SQLTest/BOM_Up.py","file_name":"BOM_Up.py","file_ext":"py","file_size_in_byte":2265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"265688064","text":"import copy\nfrom collections import namedtuple, OrderedDict\nfrom typing import Optional\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\n\nfrom ctools.pysc2.lib.static_data import BUILD_ORDER_REWARD_ACTIONS, UNIT_BUILD_ACTIONS, EFFECT_ACTIONS, RESEARCH_ACTIONS\nfrom ctools.data.collate_fn import diff_shape_collate\nfrom ctools.envs.common import EnvElement\nfrom ctools.torch_utils import levenshtein_distance, hamming_distance, to_device\n\n\nclass AlphaStarReward(EnvElement):\n _name = 'AlphaStarReward'\n BattleValues = namedtuple('BattleValues', ['last_h', 'cur_h', 'last_a', 'cur_a'])\n\n # override\n def _init(self, agent_num, pseudo_reward_type: str, pseudo_reward_prob: float) -> None:\n self.agent_num = agent_num\n self.pseudo_reward_prob = pseudo_reward_prob\n self.pseudo_reward_type = pseudo_reward_type\n assert self.pseudo_reward_type in ['global', 'immediate']\n self.last_behaviour_z = None\n self.batch_size = self.agent_num\n self.device = torch.device('cpu')\n self.build_order_location_max_limit = 2\n self.build_order_location_rescale = 0.8\n self.battle_range = 5000\n self._reward_key = ['winloss', 'build_order', 'built_unit', 'upgrade', 'effect', 'battle']\n self._shape = {k: (1, ) for k in self._reward_key}\n begin_num = 20\n self._value = {\n 'winloss': {\n 'min': -1,\n 'max': 1,\n 'dtype': float,\n 'dinfo': '-1, 0, 1'\n },\n 'build_order': {\n 'min': -begin_num,\n 'max': 0,\n 'dtype': float,\n 'dinfo': 'float'\n },\n 'built_unit': {\n 'min': -len(UNIT_BUILD_ACTIONS),\n 'max': 0,\n 'dtype': float,\n 'dinfo': 'int value'\n },\n 'upgrade': {\n 'min': -len(RESEARCH_ACTIONS),\n 'max': 0,\n 'dtype': float,\n 'dinfo': 'int value'\n },\n 'effect': {\n 'min': -len(EFFECT_ACTIONS),\n 'max': 0,\n 'dtype': float,\n 'dinfo': 'int value'\n },\n 'battle': {\n 'min': -self.battle_range,\n 'max': self.battle_range,\n 'dtype': float,\n 'dinfo': 'float'\n }\n }\n self._to_agent_processor = self.get_pseudo_rewards\n self._from_agent_processor = None\n\n # override\n def _details(self) -> str:\n return '\\t'.join(self._reward_key)\n\n def get_pseudo_rewards(\n self,\n rewards: list,\n action_types: list,\n episode_stats: list,\n loaded_eval_stats: list,\n game_loop: int,\n battle_values: 'AlphaStarReward.BattleValues',\n return_list: Optional[bool] = False\n ) -> dict:\n\n def check(t) -> bool:\n return isinstance(t, list) and len(t) == self.agent_num\n\n assert check(rewards) and check(action_types) and check(episode_stats) and check(loaded_eval_stats)\n assert isinstance(battle_values, self.BattleValues) or battle_values is None\n game_second = game_loop // 22\n # single player pseudo rewards\n\n ori_rewards = copy.deepcopy(rewards)\n behaviour_zs = []\n human_target_zs = []\n for i in range(self.agent_num):\n if self.pseudo_reward_type == 'global':\n behaviour_z = episode_stats[i].get_reward_z(use_max_bo_clip=True)\n # bo_length = len(behaviour_z['build_order']['type'])\n bo_length = 20\n human_target_z = loaded_eval_stats[i].get_reward_z_by_game_loop(\n game_loop=None, build_order_length=bo_length\n )\n elif self.pseudo_reward_type == 'immediate':\n behaviour_z = episode_stats[i].get_reward_z(use_max_bo_clip=False)\n human_target_z = loaded_eval_stats[i].get_reward_z_by_game_loop(game_loop=game_loop)\n else:\n raise ValueError(f\"{self.pseudo_reward_type} unknown!\")\n behaviour_zs.append(behaviour_z)\n human_target_zs.append(human_target_z)\n game_seconds = [game_second] * self.agent_num\n behaviour_zs = diff_shape_collate(behaviour_zs)\n human_target_zs = diff_shape_collate(human_target_zs)\n masks = self._get_reward_masks(action_types, behaviour_zs, self.last_behaviour_z)\n\n rewards, dists = self._compute_pseudo_rewards(behaviour_zs, human_target_zs, rewards, game_seconds, masks)\n self.last_behaviour_z = copy.deepcopy(behaviour_zs)\n\n if loaded_eval_stats[0].excess_max_game_loop(game_loop): # differnet agents have the same game_loop\n rewards = self._get_zero_rewards(ori_rewards)\n\n # multi players pseudo rewards\n if self.agent_num > 1:\n rewards = self._compute_battle_reward(rewards, battle_values)\n if return_list:\n rewards = [{k: rewards[k][i].unsqueeze(0) for k in rewards.keys()} for i in range(self.agent_num)]\n dists = [{k: dists[k][i].unsqueeze(0) for k in dists.keys()} for i in range(self.agent_num)]\n return rewards, dists\n\n def _get_zero_rewards(self, ori_rewards: list) -> dict:\n rewards = {}\n rewards['winloss'] = torch.FloatTensor(ori_rewards)\n for k in ['build_order', 'built_unit', 'upgrade', 'effect']:\n rewards[k] = torch.zeros(self.batch_size)\n rewards = to_device(rewards, self.device)\n return rewards\n\n def _get_reward_masks(self, action_type: list, behaviour_z: dict, last_behaviour_z: dict) -> dict:\n cum_stat_list = ['built_unit', 'effect', 'upgrade']\n action_map = {'built_unit': UNIT_BUILD_ACTIONS, 'effect': EFFECT_ACTIONS, 'upgrade': RESEARCH_ACTIONS}\n masks = {}\n mask_build_order = torch.zeros(self.batch_size)\n for i in range(self.batch_size):\n mask_build_order[i] = 1 if action_type[i] in BUILD_ORDER_REWARD_ACTIONS else 0\n masks['build_order'] = mask_build_order\n if last_behaviour_z is None:\n last_behaviour_z = {k: torch.zeros_like(v) for k, v in behaviour_z.items() if k in cum_stat_list}\n for k in cum_stat_list:\n mask = torch.zeros(self.batch_size)\n for i in range(self.batch_size):\n if action_type[i] in action_map[k]:\n mask[i] = 1\n masks[k] = mask\n else:\n for k in cum_stat_list:\n ne_num = behaviour_z[k].ne(last_behaviour_z[k]).sum(dim=1)\n masks[k] = torch.where(ne_num > 0, torch.ones(self.batch_size), torch.zeros(self.batch_size))\n masks = to_device(masks, self.device)\n return masks\n\n def _compute_pseudo_rewards(\n self, behaviour_z: dict, human_target_z: dict, rewards: list, game_seconds: int, masks: dict\n ) -> dict:\n \"\"\"\n Overview: compute pseudo rewards from human replay z\n Arguments:\n - behaviour_z (:obj:`dict`)\n - human_target_z (:obj:`dict`)\n - rewards (:obj:`list`)\n - game_seconds (:obj:`int`)\n - masks (:obj:`dict`)\n Returns:\n - rewards (:obj:`dict`): a dict contains different type rewards\n \"\"\"\n\n def loc_fn(p1, p2, max_limit=self.build_order_location_max_limit):\n p1 = p1.float().to(self.device)\n p2 = p2.float().to(self.device)\n dist = F.l1_loss(p1, p2, reduction='sum')\n dist = dist.clamp(0, max_limit)\n dist = dist / max_limit * self.build_order_location_rescale\n return dist.item()\n\n def get_time_factor(game_second):\n if game_second < 8 * 60:\n return 1.0\n elif game_second < 16 * 60:\n return 0.5\n elif game_second < 24 * 60:\n return 0.25\n else:\n return 0\n\n factors = torch.FloatTensor([get_time_factor(s) for s in game_seconds]).to(self.device)\n\n new_rewards = OrderedDict()\n new_rewards['winloss'] = torch.FloatTensor(rewards).to(self.device)\n # build_order\n p = np.random.uniform()\n build_order_reward = []\n dists = {'build_order': []}\n for i in range(self.batch_size):\n # only proper action can activate\n mask = masks['build_order'][i]\n # only some prob can activate\n mask = mask if p < self.pseudo_reward_prob else 0\n # if current the length of the behaviour_build_order is longer than that of human_target_z, return zero\n bo_dist = -levenshtein_distance(\n behaviour_z['build_order']['type'][i][:20], human_target_z['build_order']['type'][i][:20],\n behaviour_z['build_order']['loc'][i][:20], human_target_z['build_order']['loc'][i][:20], loc_fn\n )\n dists['build_order'].append(-bo_dist)\n if (len(behaviour_z['build_order']['type'][i]) > 20\n and self.pseudo_reward_type == 'global'):\n mask = 0\n build_order_reward.append(bo_dist * mask / 20)\n new_rewards['build_order'] = torch.FloatTensor(build_order_reward).to(self.device)\n dists['build_order'] = torch.FloatTensor(dists['build_order']).to(self.device)\n # built_unit, effect, upgrade\n # p is independent from all the pseudo reward and the same in a batch\n for k in ['built_unit', 'effect', 'upgrade']:\n mask = masks[k]\n p = np.random.uniform()\n mask_factor = 1 if p < self.pseudo_reward_prob else 0\n mask *= mask_factor\n hamming_dist = -hamming_distance(behaviour_z[k], human_target_z[k], factors)\n new_rewards[k] = hamming_dist * mask\n hamming_dist = -hamming_distance(behaviour_z[k], human_target_z[k])\n dists[k] = -hamming_dist\n for k in new_rewards.keys():\n new_rewards[k] = new_rewards[k].float()\n for k in dists.keys():\n dists[k] = dists[k].float()\n return new_rewards, dists\n\n def _compute_battle_reward(self, rewards: dict, battle_values: 'AlphaStarReward.BattleValues') -> dict:\n last_h, cur_h, last_a, cur_a = battle_values\n v = (cur_h - last_h) - (cur_a - last_a)\n v = torch.FloatTensor([v]).to(self.device)\n rewards['battle'] = torch.cat([v, -v])\n return rewards\n","sub_path":"distar/envs/reward/alphastar_reward.py","file_name":"alphastar_reward.py","file_ext":"py","file_size_in_byte":10669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"26109265","text":"import os\nimport json\nimport requests\n\nfrom google.cloud import storage\nfrom google.auth import app_engine\nfrom google.cloud.storage.bucket import Bucket\nfrom google.cloud.exceptions import NotFound\n\n\nPROJECT_NAME = 'hyperion'\nSTORAGE_BUCKET_NAME = 'hyperion_bucket'\n\n\ndef get_oauth2_token():\n credentials = app_engine.Credentials()\n return credentials.token\n\n\ndef get_or_create_storage_bucket():\n\n client = storage.Client()\n try:\n bucket = client.get_bucket(STORAGE_BUCKET_NAME)\n except NotFound:\n bucket = client.create_bucket(STORAGE_BUCKET_NAME)\n assert isinstance(bucket, Bucket)\n return bucket\n\n\nbucket = get_or_create_storage_bucket()\n\n\ndef create_or_update_blob(bucket, gae_file_path, **kwargs):\n\n file = bucket.blob(gae_file_path)\n if file.exists():\n\n if gae_file_path == 'cron.yaml':\n data = file.download_as_string()\n base_path = os.path.abspath('../gae_hyperion')\n file_path = os.path.join(base_path, 'cron_partial.yaml')\n with open(file_path, 'r') as f:\n data = f.read()\n cron_kwargs = {\n 'url': kwargs.get('url'),\n 'status': kwargs.get('status'),\n 'email': kwargs.get('email'),\n 'schedule': kwargs.get('schedule'),\n }\n new_cron_data = data.format(**cron_kwargs)\n data = '\\n'.join([data, new_cron_data])\n\n blob = storage.Blob(gae_file_path, bucket)\n blob.upload_from_string(data)\n else:\n base_path = os.path.abspath('../gae_hyperion')\n file_path = os.path.join(base_path, gae_file_path)\n with open(file_path, 'r') as f:\n data = f.read()\n if gae_file_path == 'main.py':\n SENDGRID_API_KEY = os.environ['SENDGRID_API_KEY']\n data = data.replace('', SENDGRID_API_KEY)\n elif gae_file_path == 'cron.yaml':\n cron_kwargs = {\n 'url': kwargs.get('url'),\n 'status': kwargs.get('status'),\n 'email': kwargs.get('email'),\n 'schedule': kwargs.get('schedule'),\n }\n data = data.format(**cron_kwargs)\n blob = storage.Blob(gae_file_path, bucket)\n blob.upload_from_string(data)\n return file\n\n\ndef get_app_json(files_data):\n bucket = \"\"\n app_json = {\n \"deployment\": {\n \"files\": {}\n },\n \"id\": \"v1\",\n \"handlers\": [{\n \"urlRegex\": \"/.*\",\n \"script\": {\n \"scriptPath\": \"main.app\"\n }\n },\n ],\n \"runtime\": \"python27\",\n \"threadsafe\": True,\n }\n\n for file_name, kwargs in files_data.items():\n file_name_data = {\n \"sourceUrl\": \"https://storage.googleapis.com/%s/%s\" % (bucket.id, file_name)\n }\n create_or_update_blob(bucket, file_name, **kwargs)\n app_json[\"deployment\"][\"files\"][file_name] = file_name_data\n\n return json.dumps(app_json)\n\n\ndef deploy_to_google_app_engine(files_data):\n\n proj_id = os.environ.get('PROJECT_ID', 1)\n app_json = get_app_json(files_data)\n token = get_oauth2_token()\n\n base_url = 'https://appengine.googleapis.com/v1'\n deployment_url = '%s/apps/{proj_id}/services/default/versions' % (base_url)\n deployment_url = deployment_url.format(proj_id=proj_id)\n\n headers = {\n \"Authorization\": \"Bearer %s\" % token,\n \"Content-Type\": \"application/json\",\n }\n files = {\n \"app.json\": app_json\n }\n r1 = requests.post(deployment_url, headers=headers, files=files)\n r1_conform_url = r1.json()['name']\n r2 = requests.get(r1_conform_url, headers=headers)\n\n return r2.json()['done']\n","sub_path":"hyperion/gae_utils.py","file_name":"gae_utils.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"649606046","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.2 (3180)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: D:\\Personal Movie Manager\\pyFiles\\unable.py\n# Compiled at: 2013-01-09 08:54:55\nfrom PySide import QtCore, QtGui\n\nclass Ui_Dialog(object):\n\n def setupUi(self, Dialog):\n Dialog.setObjectName('Dialog')\n Dialog.resize(400, 145)\n self.frame = QtGui.QFrame(Dialog)\n self.frame.setGeometry(QtCore.QRect(20, 10, 351, 131))\n self.frame.setFrameShape(QtGui.QFrame.StyledPanel)\n self.frame.setFrameShadow(QtGui.QFrame.Raised)\n self.frame.setObjectName('frame')\n self.buttonBox = QtGui.QDialogButtonBox(self.frame)\n self.buttonBox.setGeometry(QtCore.QRect(90, 90, 161, 32))\n self.buttonBox.setOrientation(QtCore.Qt.Horizontal)\n self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok)\n self.buttonBox.setObjectName('buttonBox')\n self.label = QtGui.QLabel(self.frame)\n self.label.setGeometry(QtCore.QRect(28, 20, 301, 61))\n font = QtGui.QFont()\n font.setFamily('Lucida Console')\n font.setPointSize(9)\n font.setWeight(50)\n font.setBold(False)\n self.label.setFont(font)\n self.label.setFrameShape(QtGui.QFrame.Box)\n self.label.setFrameShadow(QtGui.QFrame.Sunken)\n self.label.setWordWrap(True)\n self.label.setObjectName('label')\n self.retranslateUi(Dialog)\n QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL('accepted()'), Dialog.accept)\n QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL('rejected()'), Dialog.reject)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n Dialog.setWindowTitle(QtGui.QApplication.translate('Dialog', 'Unable to find Film', None, QtGui.QApplication.UnicodeUTF8))\n self.label.setText(QtGui.QApplication.translate('Dialog', 'Unable to find film. To try once more mentioning Year or IMDB id press Cancel. Else press OK to open search page in Web Browser', None, QtGui.QApplication.UnicodeUTF8))\n return","sub_path":"pycfiles/PersonalMovieManager-1.0/unable.cpython-32.py","file_name":"unable.cpython-32.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"306047165","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[66]:\n\n\n# Import the modules we will use\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport csv\n\n\n# In[67]:\n\n\n# Set the file name and path to where you have stored the data\nfilename = 'streamflow_week5.txt'\nfilepath = os.path.join('Documents\\Has_Tools_git\\homework-akahler03\\data', filename)\nprint(os.getcwd())\nprint(filepath)\n\n\n# In[68]:\n\n\n#Read the data into a pandas dataframe\ndata=pd.read_table(filepath, sep = '\\t', skiprows=30,\n names=['agency_cd', 'site_no', 'datetime', 'flow', 'code']\n )\n\n# Expand the dates to year month day\ndata[[\"year\", \"month\", \"day\"]] =data[\"datetime\"].str.split(\"-\", expand=True)\ndata['year'] = data['year'].astype(int)\ndata['month'] = data['month'].astype(int)\ndata['day'] = data['day'].astype(int)\n\n\n# Hints - you will need the functions: describe, info, groupby, sort, head and tail.\n# \n\n# In[69]:\n\n\nlast_jul=data[(data['year']==2019) & (data['month']==7)]\nthis_jul=data[(data['year']==2020) & (data['month']==7)]\n\n\n# In[70]:\n\n\nplt.plot(this_jul['day'], this_jul['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('Jul. 2020')\nplt.show()\n\nplt.plot(last_jul['day'], last_jul['flow'])\nplt.plot(this_jul['day'], this_jul['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('July 2019, 2020(orange)')\nplt.show()\n\n\n# In[71]:\n\n\nlast_aug=data[(data['year']==2019) & (data['month']==8)]\nthis_aug=data[(data['year']==2020) & (data['month']==8)]\n\n\n# In[72]:\n\n\nplt.plot(this_aug['day'], this_aug['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('Aug. 2020')\nplt.show()\n\nplt.plot(last_aug['day'], last_aug['flow'])\nplt.plot(this_aug['day'], this_aug['flow'])\n#labelstr=2019\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('August 2019(blue), 2020(orange)')\n#plt.legend()\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n\n# In[73]:\n\n\nlast_sept=data[(data['year']==2019) & (data['month']==9)]\nthis_sept=data[(data['year']==2020) & (data['month']==9)]\n\n\n# In[74]:\n\n\nplt.plot(this_sept['day'], this_sept['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('September 2020')\nplt.show()\n\nplt.plot(last_sept['day'], last_sept['flow'])\nplt.plot(this_sept['day'], this_sept['flow'])\nlabelstr=2019\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('September 2019, 2020(orange)')\nplt.legend()\nplt.show()\n\n#plt.xlabel('Days')\n#plt.ylabel('Flow (cfs)')\n#plt.title('September 2020')\n#plt.show()\n\n\n# Plotting weekly comparisons for Sept 2019 and 2020\n\n# In[75]:\n\n\nfirst_week19=data[(data['year']==2019) & (data['month']==9) & (data['day']<=7)]\nfirst_week20=data[(data['year']==2020) & (data['month']==9) & (data['day']<=7)]\n\n\n# In[76]:\n\n\nplt.plot(first_week19['day'], first_week19['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('first week 2019')\nplt.show()\n\nplt.plot(first_week19['day'], first_week19['flow'])\nplt.plot(first_week20['day'], first_week20['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('first week 2019, 2020 (orange)')\nplt.show()\n\n\n# In[77]:\n\n\nsecond_week19=data[(data['year']==2019) & (data['month']==9) & (data['day']>7) & (data['day']<=14)]\nsecond_week20=data[(data['year']==2020) & (data['month']==9) & (data['day']>7) & (data['day']<=14)]\n\n\n# In[78]:\n\n\nplt.plot(second_week19['day'], second_week19['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('second week 2019')\nplt.show()\n\nplt.plot(second_week19['day'], second_week19['flow'])\nplt.plot(second_week20['day'], second_week20['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('second week 2019, 2020 (orange)')\nplt.show()\n\n\n# In[79]:\n\n\nthird_week19=data[(data['year']==2019) & (data['month']==9) & (data['day']>14) & (data['day']<=21)]\nthird_week20=data[(data['year']==2020) & (data['month']==9) & (data['day']>14) & (data['day']<=21)]\n\n\n# In[80]:\n\n\nplt.plot(third_week19['day'], third_week19['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('third week 2019')\nplt.show()\n\nplt.plot(third_week19['day'],third_week19['flow'])\nplt.plot(third_week20['day'], third_week20['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('third week 2019, 2020 (orange)')\nplt.show()\n\n\n# In[81]:\n\n\nfourth_week19=data[(data['year']==2019) & (data['month']==9) & (data['day']>21) & (data['day']<=26)]\nfourth_week20=data[(data['year']==2020) & (data['month']==9) & (data['day']>21) & (data['day']<=26)]\n\n\n# In[82]:\n\n\nplt.plot(fourth_week19['day'], fourth_week19['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('fourth week 2019')\nplt.show()\n\nplt.plot(fourth_week19['day'],fourth_week19['flow'])\nplt.plot(fourth_week20['day'], fourth_week20['flow'])\nplt.xlabel('Days')\nplt.ylabel('Flow (cfs)')\nplt.title('fourth week 2019, 2020 (orange)')\nplt.show()\n\n\n# In[83]:\n\n\nfifth_sept19=data[(data['year']==2019) & (data['month']==9) & (data['day']>21) & (data['day']<=30)]\nfirst_oct19=data[(data['year']==2019) & (data['month']==10) & (data['day']<=7)]\n\n\n# In[84]:\n\n\nplt.plot(fifth_sept19['day'],fifth_sept19['flow'])\n\n\n# In[85]:\n\n\nplt.plot(first_oct19['day'],first_oct19['flow'])\n\n\n# last_ytd=data[(data['year']==2019)]\n# this_ytd=data[(data['year']==2020)]\n\n# plt.plot(last_ytd['day'], last_ytd['flow'])\n# plt.xlabel('Days')\n# plt.ylabel('Flow (cfs)')\n# plt.title('last_ytd')\n# plt.show()\n# \n# plt.plot(last_ytd['day'],last_ytd['flow'])\n# plt.plot(this_ytd['day'], this_ytd['flow'])\n# plt.xlabel('Days')\n# plt.ylabel('Flow (cfs)')\n# plt.title('this_ytd 2019, 2020 (orange)')\n# plt.show()\n# \n# print('Holy wow. Will fix later.')\n\n# In[86]:\n\n\n#Question 2: Summary of Flow min, max, mean, quartiles\ndata['flow'].describe()\n\n\n# Question 2: Summary of flow by month\n\n# In[87]:\n\n\n#For only one month\n#jan_flow=data[data['month']==1]\n\n#To do all the months, by monthly flow\ndata.sort_values(by=['year','month'], inplace=True)\n\n\n# In[88]:\n\n\ntest1=data[data.month==1].describe() \n\n\n# In[90]:\n\n\ntest1\n\n\n# In[91]:\n\n\nall_months=data.month.unique().tolist()\n\n\n# Question 3\n\n# In[92]:\n\n\n#Question 3\nfor i in all_months:\n temp=data[data.month==i]\n print(i,temp.flow.describe())\n\n\n# Question 4 Provide a table with the 5 highest and 5 lowest flow values for the period of record. Include the date,\n# month and flow values in your summary\n\n# In[102]:\n\n\ndata.sort_values(by=['flow'], inplace=True)\n\n\n# In[103]:\n\n\n#test_md=data.sort_values(by=['flow'], inplace=True)\n#print(test_md.to_markdown())\n\n\n# In[105]:\n\n\ndata.head()\n\n\n# In[32]:\n\n\ndata.tail()\n\n\n# In[33]:\n\n\n#Another way\n\n#first_five=data[:][0:5]\n#last_five=data[:][-6:-1]\n#highs_lows=pd.concat([first_five,last_five])\n\n\n# In[34]:\n\n\n#highs_lows\n\n\n# Question 5 Find the highest and lowest flow values for every month of the year \n# (i.e. you will find 12 maxes and 12 mins) and report back what year these occurred in\n\n# In[35]:\n\n\n\nprint(data.groupby('month')['flow'].nsmallest(1))\n#for n in nfive:\n # print(nfive.loc[i])\n#for n in nfive.index:\n # print(nfive['year'].loc[n])\nprint(data.loc[5,'year'])\nprint(data.loc[783,'year'])\nprint(data.loc[83,'year'])\nprint(data.loc[10710,'year'])\nprint(data.loc[5620,'year'])\nprint(data.loc[8581,'year'])\nprint(data.loc[8582,'year'])\nprint(data.loc[11,'year'])\nprint(data.loc[11574,'year'])\nprint(data.loc[8677,'year'])\nprint(data.loc[10167,'year'])\nprint(data.loc[8735,'year'])\n\n\n# In[36]:\n\n\nprint(data.groupby('month')['flow'].nlargest(1))\nprint(data.loc[1468,'year'])\nprint(data.loc[1511,'year'])\nprint(data.loc[2255,'year'])\nprint(data.loc[821,'year'])\nprint(data.loc[1246,'year'])\nprint(data.loc[1247,'year'])\nprint(data.loc[6420,'year'])\nprint(data.loc[1330,'year'])\nprint(data.loc[5742,'year'])\nprint(data.loc[7949,'year'])\nprint(data.loc[5805,'year'])\nprint(data.loc[5842,'year'])\n\n\n# 54.31 Question 6: Provide a list of historical dates with flows that are within 10% of your week 1 forecast value. \n# If there are none than increase the %10 window until you have at leastone other value and report the date \n# and the new window you used\n\n# In[65]:\n\n\ndata[(data['flow']>=54.31*.9) & (data['flow']<=54.31+54.31*.1)]\n\n\n# EVERYTHING BELOW IS JUST TRYING THINGS OUT\n# OR NOTES TO SAVE FOR LATER\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n\n# In[37]:\n\n\ntype(temp.flow.describe())\n\n\n# In[38]:\n\n\n#data[data.flow==maxi]\n\n\n# In[42]:\n\n\n#Create empty dataframe to store results of next cell maybe\n#q5_mm=pd.DataFrame()\n\n\n# In[43]:\n\n\n#Try later\n\n#all_months=data.month.unique().tolist()\n#for i in all_months:\n # temp=data[data.month==i] #kind of like np.where\n # mini=temp.flow.describe()[3]\n # maxi=temp.flow.describe()[7]\n #another1=temp[temp.flow==mini]\n #another2=temp[temp.flow==maxi]\n #frames=[another1,another2]\n #result=pd.concat(frames)\n #print(result)\n \n\n\n# In[ ]:\n\n\n#This will affect everything below\n\n#dataframe.set_index(\"column\")\n#dataframe.loc[[value]]\n#data.set_index(\"year\")\n#data.loc[[2019]]\n\n\n# \n# \n# \n# data = data.set_index(['year'])\n# print(data.loc['2019'])\n\n# In[48]:\n\n\ndata.values\n\n\n# In[49]:\n\n\n#show the first four rows and three columns\ndata.iloc[:3,:2]\n\n\n# In[50]:\n\n\n#data.loc[data.density > 100, ['pop', 'density']]\ndata.loc[data.year>2018,['flow','year']]\n\n\n# In[ ]:\n\n\n#KEEP\n#setting combined conditions\n\ndata.loc[(data['year'] >= 2018) & (data['month'] == 9)]\n\n\n# In[52]:\n\n\ndata.loc[data['month']==(9)]\n\n\n# In[53]:\n\n\nyear_2019=data.groupby([\"month\"])[[\"flow\"]].min()\n\n\n# In[54]:\n\n\nyear_2019\n\n\n# In[57]:\n\n\ndata.sort_values(by='flow', ascending=True)\n\n","sub_path":"Submissions/kahler_HW5.py","file_name":"kahler_HW5.py","file_ext":"py","file_size_in_byte":9360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"497849854","text":"print(__doc__)\n'''\n多元线性回归\n'''\nimport numpy as np\nimport scipy as sp\nfrom matplotlib import pyplot as plt\nfrom sklearn.linear_model import LinearRegression\n# 手工计算\n# y = x * bata,求bata\nx = [[1,6,2],[1,8,1],[1, 10, 0], [1, 14, 2], [1, 18, 0]]\ny = [[7], [9], [13], [17.5], [18]]\nbata = np.dot( np.linalg.inv( np.dot(np.transpose(x),x) ),\n np.dot(np.transpose(x),y) )\nprint(bata)\n# 通过最小二乘法函数来求\nbata1 = np.linalg.lstsq(x,y)\n\n# 通过sklearn\nx = [[6,2],[8,1],[10, 0], [14, 2], [18, 0]]\nmodel = LinearRegression()\nmodel.fit(x,y)\nX_test = [[8, 2], [9, 0], [11, 2], [16, 2], [12, 0]]\ny_test = [[11], [8.5], [15], [18], [11]]\npredictions = model.predict(X_test)\nfor i ,prediction in enumerate(X_test):\n print('Predicted: %s, Target: %s' %(prediction,y_test[i]))\nprint('R-squared: %.2f' % (model.score(X_test,y_test)))\n\n","sub_path":"sklearn_study/02_多元线性回归_01.py","file_name":"02_多元线性回归_01.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"423935409","text":"#!/usr/local/bin/python3\n\n\"\"\"\nSEQUENTIALBOXES\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, radians\n\n\ndef plot_grid(extents, axis_on='on', plot_grid=True):\n plt.axis(extents)\n plt.axis(axis_on)\n plt.grid(plot_grid)\n\n\ndef rotx(xc, yc, zc, xp, yp, zp, Rx):\n a = [xp, yp, zp]\n b = [1, 0, 0] # [cx11, cx12, cx13]\n xpp = np.inner(a, b)\n b = [0, cos(Rx), -sin(Rx)] # [cx21, cx22, cx23]\n ypp = np.inner(a, b)\n b = [0, sin(Rx), cos(Rx)] # [cx31, cx32, cx33]\n zpp = np.inner(a, b)\n [xg, yg, zg] = [xpp + xc, ypp + yc, zpp + zc]\n return [xg, yg, zg]\n\n\ndef roty(xc, yc, zc, xp, yp, zp, Ry):\n a = [xp, yp, zp]\n b = [cos(Ry), 0, sin(Ry)] # [cy11, cy12, cy13]\n xpp = np.inner(a, b)\n b = [0, 1, 0] # [cy21, cy22, cy23]\n ypp = np.inner(a, b)\n b = [-sin(Ry), 0, cos(Ry)] # [cy31, cy32, cy33]\n zpp = np.inner(a, b)\n [xg, yg, zg] = [xpp + xc, ypp + yc, zpp + zc]\n return [xg, yg, zg]\n\n\ndef rotz(xc, yc, zc, xp, yp, zp, Rz):\n a = [xp, yp, zp]\n b = [cos(Rz), -sin(Rz), 0] # [cz11, cz12, cz13]\n xpp = np.inner(a, b)\n b = [sin(Rz), cos(Rz), 0] # [cz21, cz22, cz23]\n ypp = np.inner(a, b)\n b = [0, 0, 1] # [cz31, cz32, cz33]\n zpp = np.inner(a, b)\n [xg, yg, zg] = [xpp + xc, ypp + yc, zpp + zc]\n return [xg, yg, zg]\n\n\ndef plotbox(xc, yc, xg, yg, zg):\n for i in (0, 1, 2):\n plt.plot([xg[i], xg[i + 1]], [yg[i], yg[i+1]],\n linewidth=3, color='k')\n\n plt.plot([xg[3], xg[0]], [yg[3], yg[0]], linewidth=3, color='k')\n\n for i in (4, 5, 6):\n plt.plot([xg[i], xg[i + 1]], [yg[i], yg[i + 1]],\n linewidth=3, color='k')\n\n plt.plot([xg[7], xg[4]], [yg[7], yg[4]], linewidth=3, color='k')\n\n for i in (0, 1, 2, 3):\n plt.plot([xg[i], xg[i - 4]], [yg[i], yg[i - 4]],\n linewidth=1, color='k')\n\n plt.scatter(xc, yc, s=5)\n\n\ndef plotboxx(xc, yc, zc, x, y, z, Rx):\n xg = [0] * 8\n yg = [0] * 8\n zg = [0] * 8\n for i in (0, 1, 2, 3, 4, 5, 6, 7): # Rotate eight corners\n [xg[i], yg[i], zg[i]] = rotx(xc, yc, zc, x[i], y[i], z[i], Rx)\n [x[i], y[i], z[i]] = [xg[i] - xc, yg[i] - yc, zg[i] - zc]\n plotbox(xc, yc, xg, yg, zg)\n\n\ndef plotboxy(xc, yc, zc, x, y, z, Ry):\n xg = [0] * 8\n yg = [0] * 8\n zg = [0] * 8\n for i in (0, 1, 2, 3, 4, 5, 6, 7): # Rotate eight corners\n [xg[i], yg[i], zg[i]] = roty(xc, yc, zc, x[i], y[i], z[i], Ry)\n [x[i], y[i], z[i]] = [xg[i] - xc, yg[i] - yc, zg[i] - zc]\n plotbox(xc, yc, xg, yg, zg)\n\n\ndef plotboxz(xc, yc, zc, x, y, z, Rz):\n xg = [0] * 8\n yg = [0] * 8\n zg = [0] * 8\n for i in (0, 1, 2, 3, 4, 5, 6, 7): # Rotate eight corners\n [xg[i], yg[i], zg[i]] = rotz(xc, yc, zc, x[i], y[i], z[i], Rz)\n [x[i], y[i], z[i]] = [xg[i] - xc, yg[i] - yc, zg[i] - zc]\n plotbox(xc, yc, xg, yg, zg)\n\n\ndef main():\n plot_grid([0, 150, 100, 0], 'on', True)\n\n # Lists\n x = [-10, -10, 10, 10, -10, -10, 10, 10] # un-rotated corner coordinates\n y = [-10, -10, -10, -10, 10, 10, 10, 10] # relative to box's center\n z = [-3, 3, 3, -3, -3, 3, 3, -3]\n\n xg = [0, 1, 2, 3, 4, 5, 6, 7] # Define global coordinates\n yg = [0, 1, 2, 3, 4, 5, 6, 7]\n zg = [0, 1, 2, 3, 4, 5, 6, 7]\n\n Rx = radians(0)\n xc = 25\n yc = 40\n zc = 20\n plotboxx(xc, yc, zc, x, y, z, Rx)\n\n Rx = radians(45)\n xc = 55\n yc = 40\n zc = 20\n plotboxx(xc, yc, zc, x, y, z, Rx)\n\n Ry = radians(30)\n xc = 85\n yc = 40\n zc = 20\n plotboxy(xc, yc, zc, x, y, z, Ry)\n\n Rz = radians(30)\n xc = 115\n yc = 40\n zc = 20\n plotboxz(xc, yc, zc, x, y, z, Rz)\n\n plt.text(23, 63, '(a)')\n plt.text(53, 63, '(b)')\n plt.text(83, 63, '(c)')\n plt.text(112, 63, '(d)')\n plt.text(21, 73, 'R=0')\n plt.text(47, 73, 'Rx=45°')\n plt.text(77, 73, 'Rx=30°')\n plt.text(107, 73, 'Rx=30°')\n plt.arrow(42, 40, 25, 0, head_width=2, head_length=3, color='r')\n plt.arrow(42, 40, 28, 0, head_width=2, head_length=3, color='r')\n plt.arrow(85, 25, 0, 27, head_width=2, head_length=2, color='r')\n plt.arrow(85, 25, 0, 29, head_width=2, head_length=2, color='r')\n plt.plot([8, 130], [8, 8], color='k')\n plt.plot([8, 8], [8, 85], color='k')\n plt.text(120, 6, 'X')\n plt.text(3, 80, 'Y')\n plt.scatter(115, 40, s=30, color='r')\n\n plt.show()\n\n\nmain()\n","sub_path":"ch03/listing_3-2.py","file_name":"listing_3-2.py","file_ext":"py","file_size_in_byte":4363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"527940849","text":"import logging\n\ncert_node_logger = logging.getLogger('cert_node')\n\n\ndef logging_request(response):\n if response.status_code < 300:\n logging_method = cert_node_logger.debug\n else:\n logging_method = cert_node_logger.warning\n\n logging_method('=============== Request Detail ==========================')\n logging_method('{0}: {1}'.format(response.request.method, response.url))\n logging_method('Request Headers:\\n\\t{0}'.format(response.request.headers))\n logging_method('Request Body:\\n\\t{0}'.format(response.request.body))\n logging_method('Response Headers:\\n\\t{0}'.format(response.headers))\n if 'Content-Type' in response.headers and response.headers['Content-Type'] == 'application/json':\n logging_method('Response Body:\\n\\t{0}'.format(response.json()))\n else:\n logging_method('Response Body:\\n\\t{0}'.format(response.content))\n\n\ndef enable_logging():\n console = logging.StreamHandler()\n cert_node_logger.setLevel(logging.DEBUG)\n cert_node_logger.addHandler(console)\n","sub_path":"certnode/debug_log.py","file_name":"debug_log.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"512082496","text":"import xlrd\nimport xlwt\nimport numpy as np\n'''\n业务规则:\n 例如:分红登记日是20160901,我们要找到从一年前(20150902)到年末20161231.这个段里面,持有够一年的股份数,\n 进行退税。如果最大值不够一年,但是假设到2017年一直持有,我们默认持有够一年。\n 需要注意:\n 数据一定要对。分红登记日对应的持仓可能有送股,要去掉。如果有股票融资融券,也要去掉。\n 分红金额要等于 持仓*每股分红。每股分红可以去通达信查公告。\n 涉及到红股:\n 如果一只股票一年多次分红送股。比如20160901 20161001都送股了。\n 那么,在算20150902-20160901的时候,20160901当天持仓不应该包含送股,但是在20161001计算的时候就要加上送股。\n'''\n\n# 根据索引获取Excel表格中的数据 参数:file:Excel文件路径 colnameindex:表头列名所在行的所以 ,by_index:表的索引\ndef excel_table_byindex(file,by_index=1,colnameindex=0):\n data = xlrd.open_workbook(file)\n list = []\n for i in range(by_index):\n table = data.sheets()[i]\n nrows = table.nrows # 行数\n ncols = table.ncols # 列数\n #存放第一行的数据作为表头\n colnames = table.row_values(colnameindex) # 某一行数据\n\n for rownum in range(1, nrows):\n\n row = table.row_values(rownum)\n if row:\n app = {}\n for i in range(len(colnames)):\n app[colnames[i]] = row[i]\n list.append(app)\n print(app)\n\n return list\n\n\n# qxTable=excel_table_byindex(\"D:\\\\2\\\\1QX.xls\")\ndetailTable = excel_table_byindex(\"D:\\\\2\\\\20171218\\\\0-0 chichang.xls\")\nfhTable = excel_table_byindex(\"D:\\\\2\\\\20171218\\\\0-0.xls\")\n'''\n这里是一对测试表格。如果有个别数据有问题,我们可以把个别股票放入里面单独跑,很快就能定位\n'''\n#detailTable = excel_table_byindex(\"D:\\\\2\\\\factory\\\\new2.xls\")\n#fhTable = excel_table_byindex(\"D:\\\\2\\\\factory\\\\new1.xls\")\n\n# 比较此点在一年内,是否是最小值\n'''\n思路:\n如果分红登记日是20160901,那么我们从20150902开始,每一天都往后数一年的时间。查找:在这一个时间段里面,最小的\n持仓的日期,把这个最小值所在的列(仅仅是这一段时间里面的最小值)返回。\n'''\ndef compareYear(row1,towYearHold, dateBegin, dateEnd, minNum,djr1):\n\n min1 = minNum\n minRow = row1\n if int(row1['备份时间'])==djr1:\n min1=float(row1['当前持仓'])-float(row1['分红送股'])\n scode=row1['证券代码']\n for row2 in towYearHold:\n if int(row2['备份时间']) >=int(dateBegin) and int(row2['备份时间']) < int(dateEnd ):\n if int(row2['备份时间'])==djr1:\n if min1 > float(row2['当前持仓'])-float(row2['分红送股']):\n min1 = float(row2['当前持仓'])-float(row2['分红送股'])\n minRow = row2\n else:\n if min1 > float(row2['当前持仓']):\n min1 = float(row2['当前持仓'])\n minRow = row2\n #print(minRow)\n #print(min1,minRow['备份时间'],dateBegin,dateEnd)\n #print('------------------------------',minRow)\n return minRow\n\n\n# 结果表,用于存放结果\nresult = []\n\n# 分红总共条数,用于显示输出\nfhLen = fhTable.__len__()\n'''\n 从这里开始,逐行遍历分红数据。每一行分红数据,对应一个股票。\n 然后,我们把这个股票从20150831到 20160901这段时间里面,最大的退税股票找到。\n\n'''\nfor row in fhTable:\n if float(row['对应持仓数量']) == float(0) :\n fhDetail = {}\n fhDetail['证券代码'] = row['stkcode']\n fhDetail['登记日'] = row['交易日期']\n fhDetail['登记股份'] = 0\n\n fhDetail['红利金额'] = row['红利金额']\n fhDetail['最晚持有日期'] = row['交易日期']\n fhDetail['免税股数'] = 0\n fhDetail['最早持有日期'] = '持仓为0,无意义'\n fhDetail['退税金额'] = 0\n\n result.append(fhDetail)\n continue\n\n stkcode = row['stkcode']\n\n #print(stkcode)\n '''\n fhDetail 用于存放每一条分红记录对应的股票的对应的最终计算结果。\n '''\n fhDetail = {}\n fhDetail['证券代码'] = stkcode\n fhDetail['登记日'] = row['交易日期']\n for temp in detailTable:\n if (temp['证券代码'] == stkcode) and (int(temp['备份时间']) == int(row['交易日期'])):\n fhDetail['登记股份'] = float(temp['当前持仓'])-float(temp['分红送股'])\n #djNum=fhDetail['登记股份']\n fhDetail['红利金额'] = row['红利金额']\n fhDetail['最晚持有日期'] = row['交易日期']\n ksr = (int(fhDetail['登记日']) - 10000)\n djr = int(fhDetail['登记日'])\n # 得到该分红股票的所有持仓数据\n stkList = []\n #=============================================\n fhDetail['退税金额'] = 0\n fhDetail['免税股数'] = 0\n #print(ksr,djr)\n '''\n stkList 里面存放从20150902-20160901每一天的持仓数据\n '''\n for row in detailTable:\n if (row['证券代码'] == stkcode) and (int(row['备份时间']) > ksr) and (int(row['备份时间']) <= djr ) :\n stkList.append(row)\n\n # 获得最理想的那个点\n resultList = {}\n resultList['date'] = 20110000\n resultList['num'] = -1\n '''\n 如果没有持仓,len=0,我们就直接输出结果\n 有持仓,就把stkList里面的每一天往后数一年,去找最小值。\n 再找之前,我们需要把这只股票的2015-16年的持仓数据单独保存下来,提高效率\n '''\n if stkList.__len__()==0:\n resultList['date'] = '>=20160101'\n fhDetail['最晚持有日期'] = '<=20161231'\n fhDetail['最早持有日期'] = '>=20160101'\n fhDetail['登记股份']=0\n fhDetail['免税股数']=0\n fhDetail['免税金额']=0\n fhDetail['退税金额']=0\n fhDetail['红利金额']=0\n fhDetail['登记日'] =0\n result.append(fhDetail)\n continue\n '''\n 保存有关股票的两年的持仓20150902---20161231\n '''\n towYearHold=[]\n for row in detailTable:\n if (row['证券代码'] == stkcode) and (int(row['备份时间']) > ksr) :\n towYearHold.append(row)\n\n '''\n 有持仓,就把stkList里面的每一天往后数一年,去找最小值。\n '''\n for row in stkList:\n minnum=float(row['当前持仓'])\n dateBegin=int(row['备份时间'])\n dateEnd=dateBegin+10000\n djr1=int(fhDetail['登记日'])\n #resultList['end'] = dateEnd\n #resultList['begin'] = dateBegin\n #print(row)\n res=compareYear(row,towYearHold, dateBegin, dateEnd, minnum,djr1)\n\n '''\n 这里得到了每一行的最小值,然后跟最终的退税股份比较:\n 因为这里是从20160901到20160902 365天,365个最小值。我们要从里面找一个最大值,才是\n 利益最大化\n '''\n if int(row['备份时间'])==djr1:\n if resultList['num'] < float(res['当前持仓'])-float(res['分红送股']):\n resultList['num'] = float(res['当前持仓'])-float(res['分红送股'])\n resultList['begin'] = dateBegin\n resultList['end'] = dateEnd\n else:\n if resultList['num']< float(res['当前持仓']):\n resultList['num'] = float(res['当前持仓'])\n resultList['begin'] = dateBegin\n resultList['end'] = dateEnd\n\n #print(resultList,res)\n #print(res, dateBegin)\n #print(row)\n\n fhDetail['免税股数'] = resultList['num']\n fhDetail['最晚持有日期'] = resultList['end']\n fhDetail['最早持有日期'] = resultList['begin']\n if fhDetail['最晚持有日期']>20180000:\n fhDetail['最晚持有日期']=20171231\n #fhDetail['最早持有日期'] = resultList['date']\n if float(fhDetail['登记股份'])==0:\n fhDetail['退税金额']=0\n fhDetail['免税股数']=0\n fhDetail['免税金额'] =0\n else:\n fhDetail['退税金额'] = round((resultList['num'] / float(fhDetail['登记股份'])) * 0.25 * float(fhDetail['红利金额']), 2)\n fhDetail['免税金额'] = round((resultList['num']/float(fhDetail['登记股份']))*float(fhDetail['红利金额']),2)\n result.append(fhDetail)\n\n\n# 输出结果=+++++++++++++++++++++================================================================================================================\nfor row in result:\n #print('证券代码'':,row['证券代码'],row['登记股份'],row['免税股数'],row['退税金额'],row['最早持有日期'],row['最晚持有日期'],row['红利金额'],row['登记日'])\n print(row)\n\nwTable=xlwt.Workbook()\nsheet1=wTable.add_sheet('sheet1')\nfor i in range(result.__len__()):\n\n\n sheet1.write(i, 0, result[i]['证券代码'])\n sheet1.write(i, 1, result[i]['登记股份'])\n sheet1.write(i, 2, result[i]['免税股数'])\n sheet1.write(i, 3, result[i]['免税金额'])\n sheet1.write(i, 4, result[i]['退税金额'])\n sheet1.write(i, 5, result[i]['最早持有日期'])\n sheet1.write(i, 6, result[i]['最晚持有日期'])\n sheet1.write(i, 7, result[i]['红利金额'])\n sheet1.write(i, 8, result[i]['登记日'])\n\n wTable.save(\"D:\\\\2\\\\dai\\\\res1-0.xls\")\n\n\n","sub_path":"work/hongli5.py","file_name":"hongli5.py","file_ext":"py","file_size_in_byte":9623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"17786530","text":"import glob\nimport os\nimport shutil\n\ndir = '/home/dunbar/Research/wolverine/data/cam_weather/images/'\n\nfor file in glob.glob(os.path.join(dir,\"*\")):\n\tif os.path.isdir(file):\n\t\t\n\t\timgs = glob.glob(os.path.join(file,\"*.JPG\"),recursive=True)\n\t\tfor image in imgs:\n\t\t\tprint(image)\n\t\t\tshutil.move(image,dir)","sub_path":"scripts/dataprep/moveimages.py","file_name":"moveimages.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"132863916","text":"def temp_remove(lis, number):\n\tclis = lis.copy()\n\tclis.remove(number)\n\treturn clis\t\n\ndef remove_copies(lis):\n\tclis = []\n\tfor i in lis:\n\t\tif i not in clis:\n\t\t\tclis.append(i)\n\treturn clis\n\ndef find_triplets(lis):\n\treturn remove_copies([(i,j,k) for i in lis for j in temp_remove(lis, i) for k in temp_remove(temp_remove(lis, i), j) if i+j+k == 0 and i <= j <= k])\n\nif __name__ == \"__main__\":\n\tprint(find_triplets([-1,1,0]))\n\tprint(find_triplets([1,1,2]))\n","sub_path":"Desktop/learningprogramming/3sum.py","file_name":"3sum.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"469960410","text":"# SWEA 1983\n\ndef get_grade(arr, N, K):\n grade_gap = N // 10\n grade = ['A+', 'A0', 'A-', 'B+', 'B0', 'B-', 'C+', 'C0', 'C-', 'D0']\n grade_list = []\n student_score = 0\n student_grade = 0\n\n # 입력받은 학생들의 최종점수를 계산해서 리스트에 저장\n for i in range(N):\n final_score = arr[i][0] * 0.35 + arr[i][1] * 0.45 + arr[i][2] * 0.2\n grade_list.append(final_score)\n # 현재 계산중인 점수가 내가 구해야하는 K번째 학생이라면 student_score에 점수를 따로저장\n if i == K - 1:\n student_score = final_score\n final_score = 0\n \n # grade_score에 저장한 점수리스트들을 버블배열로 내림차순 정렬\n for i in range(N):\n for j in range(N - 1):\n if grade_list[j] < grade_list[j + 1]:\n temp = grade_list[j]\n grade_list[j] = grade_list[j + 1]\n grade_list[j + 1] = temp\n \n # K번째 학생의 최종점수가 전체학생중 몇등(몇번째index)인지 구해서 student_grade에 저장\n for i in range(N):\n if student_score == grade_list[i]:\n student_grade = i\n break\n # '학생의 등수'를 '점수별로 줄수있는 학생 수(N // 10)로 나눈 몫'에 \n # 해당하는 grade의 index가 K번째 학생이 받아야하는 등급이다.\n res = grade[student_grade // (grade_gap)]\n\n return res\n\n\nT = int(input())\nfor tc in range(1, T + 1):\n N, K = map(int, input().split())\n arr = [list(map(int, input().split())) for _ in range(N)]\n res = get_grade(arr, N, K)\n\n print('#{} {}'.format(tc, res))","sub_path":"Algo/SWEA/1983_조교의성적매기기.py","file_name":"1983_조교의성적매기기.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"18609952","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n#Importação das bibliotecas\nimport pygtk\npygtk.require('2.0')\nimport gtk\nfrom gtk import glade\n\n#Usando arquivos do projeto\nimport usuarioslista\nimport funcoes as f\nimport usuarioscadastro\n\nclass Programa(gtk.Window):\n#Método construtor \n def __init__(self):\n #Variável de controle do login \n self.matarprograma = 0;\n \n #Inicializa \n super(Programa, self).__init__()\n \n #Carrega arquivo glade \n self.GLADE_FILE = f.CaminhoGlade + 'gfp.glade'\n gui = glade.XML(self.GLADE_FILE, 'winGFP')\n \n #Associa os controles \n self.mnUsuarios = gui.get_widget('mnUsuarios')\n self.mnSair = gui.get_widget('mnSair')\n self.mnSobre = gui.get_widget('mnSobre')\n self.win = gui.get_widget('winGFP')\n self.stbStatus = gui.get_widget('stbStatus')\n\n #Associa eventos dos controles \n self.mnUsuarios.connect('activate', usuarioslista.UsuariosLista)\n self.mnSair.connect('activate', self.Sair, None)\n self.mnSobre.connect('activate', self.MostraSobre)\n self.win.connect('delete_event', self.Sair)\n self.win.connect('show', self.MostraLogin)\n\n #Início do programa \n self.win.show_all()\n\n #Verifica login \n if self.matarprograma == 0:\n #Coloca dados do usuário na barra de status \n self.stbStatus.push(0, ' Usuário: ' + str(f.usuariologadoid) + ' - [' + f.usuariologadouser + '] ' + f.usuariologadonome)\n else:\n #Abre o programa mas deixa tudo inativo \n self.mnUsuarios.set_sensitive(False)\n f.Mensagem(self.win, \"Voc? não está logado.\")\n self.stbStatus.push(0, ' Você não está logado.')\n\n\n#Fechar conexões e sair \n def Sair(self, widget, event):\n if self.matarprograma == 0:\n if f.MsgConfirmacao(self.win, 'Deseja realmente sair do GFP?'):\n f.cnx.close()\n gtk.main_quit()\n return False\n else:\n return True\n else:\n f.cnx.close()\n gtk.main_quit()\n return False \n\n\n#Abre janela sobre o programa \n def MostraSobre(self, widget):\n guiSobre = glade.XML(self.GLADE_FILE, 'winSobre')\n winSobre = guiSobre.get_widget('winSobre')\n winSobre.run()\n winSobre.destroy()\n\n\n#Abre tela de login \n def MostraLogin(self, widget):\n T = 0\n while T == 0:\n #Carrega tela do arquivo glade \n guiLogin = glade.XML(self.GLADE_FILE, 'winLogin')\n\n #Associa os controles \n winLogin = guiLogin.get_widget('winLogin')\n edtUsuario = guiLogin.get_widget('edtUsuario')\n edtSenha = guiLogin.get_widget('edtSenha')\n btnNewUser = guiLogin.get_widget('btnNovoUser')\n lblTitulo = guiLogin.get_widget('lblEntrar')\n\n #Formata controles \n lblTitulo.set_markup(\"Entrar no GFP\")\n lblTitulo.set_justify(gtk.JUSTIFY_LEFT)\n\n def AbreCadastroUsu(widget):\n try:\n usuarioscadastro.UsuariosCadastro(widget, True, 0, winLogin, self)\n winLogin.set_focus(edtUsuario)\n except:\n pass\n\n #Associa eventos \n edtUsuario.connect(\"changed\", lambda *a: f.StrToMais(edtUsuario))\n edtSenha.connect(\"changed\", lambda *a: edtSenha.set_text(f.TiraAspa(edtSenha.get_text())))\n edtUsuario.connect(\"focus_out_event\", lambda *a: f.StrToTrim(edtUsuario))\n btnNewUser.connect(\"clicked\", AbreCadastroUsu)\n\n #Abre a janela \n self.matarprograma = winLogin.run()\n \n #Inverte valores \n if self.matarprograma == 0:\n self.matarprograma = -1\n else:\n self.matarprograma = 0\n\n #Fecha janela sem verificação \n if self.matarprograma == -1:\n T = 1\n\n #Verifica dados digitados \n if (edtUsuario.get_text() != '' and edtSenha.get_text() != '') or self.matarprograma == -1:\n if self.matarprograma != -1:\n#Verifica usuário no banco \n f.query.execute(\"SELECT id, user, nome FROM usuarios WHERE\\\n user = '\" + edtUsuario.get_text() + \"' and\\\n senha = '\" + edtSenha.get_text() + \"'\")\n T = 0\n\n for row in f.query:\n #Usuário encontrado \n f.usuariologadoid = row[0]\n f.usuariologadouser = row[1]\n f.usuariologadonome = row[2]\n T = 1\n\n if T == 0:\n f.Mensagem(winLogin, 'Usuário ou senha inválidos!')\n else:\n T = 1\n else:\n f.Mensagem(winLogin, 'Você deve informar o usuário e a senha!')\n winLogin.destroy()\n\n\nPrograma()\ngtk.main()","sub_path":"gfp.py","file_name":"gfp.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"349035297","text":"import os\nimport socket\nimport time\nimport unittest\n\nimport greenhouse\nimport greenhouse.poller\n\nfrom test_base import TESTING_TIMEOUT, StateClearingTestCase\n\n\nport = lambda: 8000 + os.getpid() # because i'm running multiprocess nose\n\nclass ScheduleTestCase(StateClearingTestCase):\n def test_schedule(self):\n l = []\n\n def f1():\n l.append(1)\n greenhouse.schedule(f1)\n\n @greenhouse.schedule\n def f2():\n l.append(2)\n\n @greenhouse.schedule(args=(3,))\n def f3(x):\n l.append(x)\n\n @greenhouse.schedule(kwargs={'x': 4})\n def f4(x=None):\n l.append(x)\n\n @greenhouse.compat.greenlet\n def f5():\n l.append(5)\n greenhouse.schedule(f5)\n\n greenhouse.pause_for(TESTING_TIMEOUT)\n\n l.sort()\n assert l == [1, 2, 3, 4, 5], l\n\n def test_schedule_at(self):\n at = time.time() + (TESTING_TIMEOUT * 2)\n l = []\n\n def f1():\n l.append(1)\n greenhouse.schedule_at(at, f1)\n\n @greenhouse.schedule_at(at)\n def f2():\n l.append(2)\n\n @greenhouse.schedule_at(at, args=(3,))\n def f3(x):\n l.append(x)\n\n @greenhouse.schedule_at(at, kwargs={'x': 4})\n def f4(x=None):\n l.append(x)\n\n @greenhouse.compat.greenlet\n def f5():\n l.append(5)\n greenhouse.schedule_at(at, f5)\n\n greenhouse.pause()\n assert not l\n\n greenhouse.pause_for(TESTING_TIMEOUT * 2)\n assert time.time() >= at\n greenhouse.pause()\n\n l.sort()\n assert l == [1, 2, 3, 4, 5], l\n\n def test_schedule_in(self):\n l = []\n\n def f1():\n l.append(1)\n greenhouse.schedule_in(TESTING_TIMEOUT, f1)\n\n @greenhouse.schedule_in(TESTING_TIMEOUT)\n def f2():\n l.append(2)\n\n @greenhouse.schedule_in(TESTING_TIMEOUT, args=(3,))\n def f3(x):\n l.append(x)\n\n @greenhouse.schedule_in(TESTING_TIMEOUT, kwargs={'x': 4})\n def f4(x=None):\n l.append(x)\n\n @greenhouse.compat.greenlet\n def f5():\n l.append(5)\n greenhouse.schedule_in(TESTING_TIMEOUT, f5)\n\n greenhouse.pause()\n assert not l\n\n time.sleep(TESTING_TIMEOUT)\n greenhouse.pause()\n\n l.sort()\n assert l == [1, 2, 3, 4, 5], l\n\n def test_schedule_recurring(self):\n l = []\n\n def f1():\n l.append(1)\n greenhouse.schedule_recurring(TESTING_TIMEOUT, f1, maxtimes=2)\n\n greenhouse.pause_for(TESTING_TIMEOUT * 3)\n assert l == [1, 1], l\n\n l = []\n @greenhouse.schedule_recurring(TESTING_TIMEOUT, maxtimes=2)\n def f2():\n l.append(2)\n\n greenhouse.pause_for(TESTING_TIMEOUT * 3)\n assert l == [2, 2], l\n\n l = []\n @greenhouse.schedule_recurring(TESTING_TIMEOUT, maxtimes=2, args=(3,))\n def f3(x):\n l.append(x)\n\n greenhouse.pause_for(TESTING_TIMEOUT * 3)\n assert l == [3, 3], l\n\n l = []\n @greenhouse.schedule_recurring(TESTING_TIMEOUT, maxtimes=2,\n kwargs={'x': 4})\n def f4(x=None):\n l.append(x)\n\n greenhouse.pause_for(TESTING_TIMEOUT * 3)\n assert l == [4, 4], l\n\n l = []\n @greenhouse.compat.greenlet\n def f5():\n l.append(5)\n greenhouse.schedule_recurring(TESTING_TIMEOUT, f5, maxtimes=2)\n\n greenhouse.pause_for(TESTING_TIMEOUT * 3)\n assert l == [5, 5], l\n\n def test_schedule_recurring_rejects_dead_grlet(self):\n @greenhouse.compat.greenlet\n def f():\n pass\n\n while not f.dead:\n f.switch()\n\n self.assertRaises(TypeError, greenhouse.schedule_recurring,\n TESTING_TIMEOUT, f, maxtimes=2)\n\n def test_deleted_sock_gets_cleared(self):\n dmap = greenhouse._state.state.descriptormap\n fno = greenhouse.Socket().fileno()\n\n import gc\n gc.collect()\n\n assert all(x() is None for x in dmap[fno]), [x() for x in dmap(fno)]\n\n client = greenhouse.Socket()\n server = greenhouse.Socket()\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server.bind((\"\", port()))\n server.listen(5)\n client.connect((\"\", port()))\n handler, addr = server.accept()\n\n handler.send(\"howdy\")\n client.recv(5)\n\n assert all(x() for x in dmap[fno]), [x() for x in dmap[fno]]\n\n handler.close()\n client.close()\n server.close()\n\n def test_socketpolling(self):\n client = greenhouse.Socket()\n server = greenhouse.Socket()\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server.bind((\"\", port()))\n server.listen(5)\n client.connect((\"\", port()))\n handler, addr = server.accept()\n l = [False]\n\n @greenhouse.schedule\n def f():\n client.recv(10)\n l[0] = True\n\n greenhouse.pause()\n greenhouse.pause()\n assert not l[0]\n\n handler.send(\"hi\")\n greenhouse.pause()\n assert l[0]\n\nclass PausingTestCase(StateClearingTestCase):\n def test_pause(self):\n l = [False]\n\n @greenhouse.schedule\n def f():\n l[0] = True\n\n assert not l[0]\n\n greenhouse.pause()\n assert l[0]\n\n def test_pause_for(self):\n start = time.time()\n greenhouse.pause_for(TESTING_TIMEOUT)\n assert TESTING_TIMEOUT + 0.03 > time.time() - start >= TESTING_TIMEOUT\n\n def test_pause_until(self):\n until = time.time() + TESTING_TIMEOUT\n greenhouse.pause_until(until)\n assert until + 0.03 > time.time() >= until\n\nclass ExceptionsTestCase(StateClearingTestCase):\n class CustomError(Exception): pass\n\n def test_exceptions_raised_in_grlets(self):\n l = [False]\n\n @greenhouse.schedule\n def f():\n raise self.CustomError()\n l[0] = True\n\n greenhouse.pause()\n greenhouse.pause()\n greenhouse.pause()\n greenhouse.pause()\n\n assert not l[0]\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_scheduler.py","file_name":"test_scheduler.py","file_ext":"py","file_size_in_byte":6233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"526170027","text":"#!/usr/bin/env python3\n\nimport os.path\nimport json\nimport logging\nfrom time import mktime\nfrom datetime import date, datetime, timedelta\n\nimport csv\nimport requests\n\nimport argparse\nfrom sys import argv\n\nimport xlrd\n\nfrom model.model import *\nfrom collector.stockcollector import *\nfrom collector.sentimentscollector import *\n\nfrom storage.mongo import MongoDriver\nfrom settings import *\nfrom model.session import *\nfrom model.sentiments import * \n\ndef saveSentiment(sentimentRecord):\n if sentimentRecord:\n with sessionContext() as sess:\n for s in sentimentRecord:\n a = Aaii(date = s['_id'].date(),\n neutral = s['neutral'],\n bullish = s['bullish'],\n bearish = s['bearish'])\n sess.merge(a)\n sess.commit()\n\n\ndef updateputcallratios():\n url = 'http://www.cboe.com/publish/ScheduledTask/MktData/datahouse/indexPC.csv'\n r = requests.get(url)\n table = r.text\n data = csv.reader(table.splitlines(), quoting=csv.QUOTE_ALL)\n\n\n with sessionContext() as sess:\n # skip first three line\n next(data)\n next(data)\n next(data)\n for line in data:\n s= {\n '_id' : datetime.strptime(line[0], \"%m/%d/%Y\"),\n 'call' : line[1],\n 'put' : line[2],\n 'total' : line[3],\n 'ratio' : line[4]\n }\n # save pcraito and put value\n a = Pcratio(date = s['_id'].date(),\n ratio = s['ratio'],\n put = s['put'],\n call = s['call'],\n total = s['total'],)\n sess.merge(a)\n sess.commit() \n\ndef updatesentiment():\n sr = downloadAAIISentiment()\n saveSentiment(sr)\n\n\ndef main(args):\n updatesentiment()\n updateputcallratios()\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.WARNING)\n\n parser = argparse.ArgumentParser(prog = 'updatesentiments',\n description='A utility of updating sentimental indicators',\n epilog=\"Enjoy\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n \n #parser.add_argument('symbols', help='symbols list name')\n parser.set_defaults(func=main) \n\n args = parser.parse_args()\n args.func(args)\n \n \n","sub_path":"scripts/updatesentiments.py","file_name":"updatesentiments.py","file_ext":"py","file_size_in_byte":2440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202632578","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 6 12:35:21 2020\r\n\r\n@author: gogliom\r\n\"\"\"\r\n\r\n'''\r\nDoc = convert_pdf_to_txt( r\"D:\\Altro\\RPA\\Energy\\IREN\\TEST CTE\\CTE\\esempi cte\\EnelLuce30.pdf\")\r\nDoc = Doc.upper()\r\n \r\n'''\r\n\r\n##### BISOGNA IMPORTARE FUNZIONE CONVERT_PDF_TO_TEXT DA ALTRO PROGRAMMA!\r\n\r\nimport pandas as pd\r\nimport re\r\nfrom ProvePDF import convert_pdf_to_txt\r\nimport numpy as np\r\n\r\ndef Durata(Doc):\r\n\r\n PossiblePrice = []\r\n Base = []\r\n \r\n #Doc = convert_pdf_to_txt(Doc)\r\n #Doc = Doc.upper()\r\n \r\n #le inserisco come regular expression perchè mettendo . come any character (spezi,\"E\", a capo..)\r\n r1 = 'DURATA'\r\n r2 = 'VALIDIT'\r\n r3 = 'RINNOV'\r\n r4 = 'PER.{,5}MESI'\r\n r5 = 'PER.{,5}ANN'\r\n \r\n regex = [r1,r2,r3,r4,r5]\r\n \r\n regex = re.compile('|'.join(regex))\r\n \r\n \r\n Base = [m.start() for m in regex.finditer(Doc)]\r\n Base = pd.DataFrame(Base, columns = ['PositionBase'])\r\n \r\n \r\n #prendo numeri interi (mesi o anni)\r\n d1 = r'\\s\\d{1,2}\\s' \r\n \r\n \r\n d = [d1] #le regex potrebbero essere sovrapposte,metto prima \r\n #le più lunghe così se prende quelle si ferma a quella --> SI DOVREBBE GESTIRE MEGLIO\r\n regexNum = re.compile('|'.join(d))\r\n NumberPos = [m.start() for m in regexNum.finditer(Doc)]\r\n NumberValue = regexNum.findall(Doc)\r\n NumberTuples = list(zip(NumberValue,NumberPos))\r\n \r\n \r\n PossiblePrice = pd.DataFrame(NumberTuples, columns=['Price', 'Position'])\r\n PossiblePrice['Price'] = PossiblePrice['Price'].str.extract('(\\d+)').astype(int)\r\n PossiblePrice = PossiblePrice[PossiblePrice['Price'].isin(['1', '2', '3', '4', '6','12','18','24','36'])]\r\n \r\n \r\n '''\r\n APPROCCIO IN BASE AL QUALE CERCO €/KWH E PRENDO PAROLA PRECEDENTE, MA IN ALCUNI CASI NELLE TABELLE NON E ESPLICITATA\r\n EURO/KWH VICINO AL NUMERO\r\n ii = 0\r\n for ww in Doc.split():\r\n if \"€/KWH\" in ww or \"EURO/KWH\" in ww:\r\n pw = Doc.split()[ii-1]\r\n po = Doc.find(Doc.split()[ii-1]+\" \"+Doc.split()[ii])\r\n nn = pd.DataFrame({'Price': [pw], 'Position': [po]})\r\n PossiblePrice = PossiblePrice.append(nn) \r\n #Positions = Positions + list(ii-1) \r\n ii = ii + 1 \r\n #estraggo i numeri \r\n PossiblePrice['Price'] = PossiblePrice.apply(lambda row: re.findall('-?\\d*\\,.?\\d+', str(row.Price)), axis=1)\r\n #elimino eventuali stringe vuote\r\n PossiblePrice = PossiblePrice[PossiblePrice['Price'].apply(lambda row: len(row)) > 0]\r\n '''\r\n \r\n \r\n \r\n Base['key'] = 0\r\n PossiblePrice['key'] = 0\r\n \r\n Durata = Base.merge(PossiblePrice, how='outer')\r\n Durata['dist'] = Durata.apply(lambda row: row.Position - row.PositionBase, axis = 1)\r\n #FILTRO PER LE DISTANZE POSITIVE (IL NUMERO VIENE DOPO LA PAROLA, OPPURE NEGATIVE MOLTO PICCOLE DOVE QUINDI LA BASE VIENE IMMEDIATAMENTE DOPO )\r\n Durata = Durata[(Durata['dist'] > - 30) & (Durata['dist'] < 300)]\r\n \r\n #verifico se nei 40 caratteri prima o dopo c'è riferimento a mese o anno \r\n dur1_m = r'\\bMESE\\b'\r\n dur2_m = r'\\bMESI\\b'\r\n dur_m = [dur1_m, dur2_m] \r\n regexDur_m = re.compile('|'.join(dur_m))\r\n\r\n dur1_a = r'\\bANNO\\b'\r\n dur2_a = r'\\bANNI\\b'\r\n dur_a = [dur1_a, dur2_a] \r\n regexDur_a = re.compile('|'.join(dur_a))\r\n\r\n\r\n Durata['Intorno'] = Durata.apply(lambda row: Doc[row.Position-40:row.Position+40], axis = 1)\r\n Durata['Mese'] = np.where(Durata['Intorno'].str.contains(regexDur_m),1,0)\r\n Durata['Anno'] = np.where(Durata['Intorno'].str.contains(regexDur_a),1,0)\r\n \r\n #filtro per le durata possibili (6, 12, 18, 24 mesi -- 1, 2 anni)\r\n Dm = Durata[(Durata['Mese'] == 1) & (Durata['Price'].isin(['6','12','18','24']))]\r\n Da = Durata[(Durata['Anno'] == 1) & (Durata['Price'].isin(['1','2']))]\r\n Durata = Dm.append(Da)\r\n \r\n Durata = Durata.nsmallest(1, 'dist')\r\n \r\n if Durata['Anno'].all() == 1:\r\n Durata['Price'] = Durata['Price'].apply(str) + ' anno' \r\n elif Durata['Mese'].all() == 1:\r\n Durata['Price'] = Durata['Price'].apply(str) + ' mesi'\r\n else:\r\n Durata['Price'] = Durata['Price'].apply(str) + ' anno'\r\n\r\n #print(Prezzo)\r\n return Durata['Price']","sub_path":"ProveDurata.py","file_name":"ProveDurata.py","file_ext":"py","file_size_in_byte":4248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"380986199","text":"# Slay the Spire Arena: Pit mobs vs one another and fight it out to the death!\nimport random\nglobal_rng = random.Random()\nfrom copy import deepcopy as dcpy\n# Defines power API\nfrom powers import *\n\"\"\"\n\tTODO: Make Monster.Alive a property or lambda or something?\n\"\"\"\n\n\"\"\"\n#0 MonsterMove (Abstract)\n\tDefines a particular monster move\n\tGiven a class, callback, and string-able attributes\n\"\"\"\nclass MonsterMove():\n\tdef __init__(self, affectClass, callback, description=\"\"):\n\t\tself.affectClass = affectClass\n\t\tself.callback = callback\n\t\tself.ID = callback.__name__\n\t\tself.description = description\n\n\tdef __str__(self):\n\t\treturn f\"{self.ID} defined as {self.description}\"\n\n\"\"\"\n#1 Monster (Abstract)\n\tDefines a particular Spire abomination\n\n\tSubclasses are named entities that fully implement their particular movesets, stats, patterns, ascension behaviors, etc\n\"\"\"\nclass Monster():\n\tdef __init__(self, ID=\"\", Arena=None, Friendlies=None):\n\t\t\"\"\"\n\t\t\tATTRIBUTES:\n\t\t\t\t* ID (str, debug)\n\t\t\t\t* Arena (arena.Arena reference)\n\t\t\t\t* Friendlies (arena.MonsterGroup reference for allied block)\n\t\t\t\t* rng (random.RandomState for RNG)\n\t\t\t\t* Name (str, flavor)\n\t\t\t\t* Act (int, flavor)\n\t\t\t\t* Abilities (list of callable functions to perform attacks)\n\t\t\t\t* Pattern (list of weights to probabilistically sample an action from)\n\t\t\t\t* Ascension (int: this monster is at ascension X)\n\t\t\t\t* MaxHealth, Health, Block, Strength, Dexterity (integers)\n\t\t\t\t* Alive (bool)\n\t\t\t\t\t* When this gets flipped off, tell Friendly group to -= 1 it's fight_on\n\t\t\t\t\t* When this gets turned back on, tell Friendly group to += 1 it's fight_on\n\t\t\t\t* PowerPool (list of callable PowerObjects that implement listeners to adjust effects)\n\t\t\t\t\t* All PowerPool'd objects can be called before, during, and after doing basically anything\n\t\t\t\t* History (list of Ability usages to enforce intent rules)\n\t\t\"\"\"\n\t\tself.ID = ID\n\t\tself.Arena = Arena\n\t\tself.Friendlies = Friendlies\n\t\tglobal global_rng\n\t\tself.rng = global_rng\n\t\tself.Name, self.Act, self.ascension = \"\", 0, 0\n\t\tself.MaxHealth, self.Health, self.Block = 0, 0, 0\n\t\tself.PowerPool, self.Pattern, self.Abilities, self.Callbacks = [], [], [], []\n\t\tself.History, self.HistoryIdx = [], 0\n\t\tself.Alive = True\n\n\tdef __str__(self):\n\t\tstring = f\"{self.Name} {self.ID}\"\n\t\tif self.Friendlies is not None:\n\t\t\tstring = f\"{str(self.Friendlies)}::{string}\"\n\t\tif self.Arena is not None:\n\t\t\tstring = f\"{str(self.Arena)}::{string}\"\n\t\treturn string\n\n\tdef Reset(self):\n\t\tself.Health = self.MaxHealth\n\t\tself.Alive = True\n\t\tself.PowerPool = []\n\t\tself.History = []\n\t\tself.HistoryIdx = 0\n\t\tif not self.Alive and self.Friendlies is not None:\n\t\t\tself.Friendlies.fight_on += 1\n\n\tdef SpecialIntent(self, moveCall, moveAlternatives, moveChances):\n\t\t\"\"\"\n\t\t\tNo special intents by default\n\t\t\"\"\"\n\t\tprint(f\"{self.Name}'s move is not overridden by template class's SpecialIntent()\")\n\t\treturn moveCall, moveAlternatives, moveChances\n\n\tdef MoveSelect(self, move=None):\n\t\t\"\"\"\n\t\t\tReturn the move or result from pruned array if history rejects the intended move\n\t\t\"\"\"\n\t\tif move is None:\n\t\t\tmove = self.rng.choices(self.Abilities, weights=self.Pattern, k=1)[0]\n\t\t# Special History rejection\n\t\t\t# Does not return modified ability/probability list as it is either unchanged\n\t\t\t# (default history check uses this given list) or it was changed (ergo default\n\t\t\t# history check won't trigger)\n\t\tmove_idx = self.Callbacks.index(move.callback)\n\t\tnot_move_sum = sum(self.Pattern) - self.Pattern[move_idx]\n\t\tremainingMoves = [_ for idx, _ in enumerate(self.Abilities) if idx != move_idx]\n\t\tremainingChances = [_/not_move_sum for idx, _ in enumerate(self.Pattern) if idx != move_idx]\n\t\t# This call to be overridden by implementing classes\n\t\tmove = self.SpecialIntent(move, remainingMoves, remainingChances)\n\t\tmove_idx = self.Callbacks.index(move.callback)\n\t\t# Normal History rejection (x3 never allowed)\n\t\tif len(self.History) == 2 and sum(self.History)/2 == float(move_idx):\n\t\t\tmove = self.rng.choices(remainingMoves, weights=remainingChances, k=1)[0]\n\t\t\tmove_idx = self.Callbacks.index(move.callback)\n\t\t# Record history\n\t\tif len(self.History) < 2:\n\t\t\tself.History.append(move_idx)\n\t\telse:\n\t\t\tself.History[self.HistoryIdx] = move_idx\n\t\tself.HistoryIdx = (self.HistoryIdx + 1) % 2\n\t\treturn move\n\n\tdef Turn(self, move=None):\n\t\tif self.Alive:\n\t\t\tmove = self.MoveSelect(move)\n\t\t\t\"\"\"\n\t\t\tprint(f\"{str(self)} performs {str(move)}; history is \"\n\t\t\t\t f\"{[self.Callbacks[self.History[(self.HistoryIdx-_)%2]].__name__ for _ in range(len(self.History),0,-1)]}\")\n\t\t\t\"\"\"\n\t\t\tmove.callback()\n\t\telse:\n\t\t\tprint(f\"{self} is dead. Skipping turn\")\n\n\tdef Empower(self, value, source_class, *trigger_classes, source, target, extras=[]):\n\t\t\"\"\"\n\t\t\tAlter value using self.PowerPool based on trigger_class and source_class\n\t\t\"\"\"\n\t\tpowerQueue = []\n\t\tfor power in self.PowerPool:\n\t\t\tfor trigger in trigger_classes:\n\t\t\t\tif trigger in power.triggers:\n\t\t\t\t\tpowerQueue.append(power)\n\t\t\t\t\tbreak\n\t\t# Sort powerQueue by priority\n\t\tpowerQueue = sorted(powerQueue, key=lambda x: x.priority, reverse=True)\n\t\t# Activate powers\n\t\tfor power in powerQueue:\n\t\t\tnew_value = power.Affect(value, source_class, source, target, extras)\n\t\t\tprint(\"\\t\"+f\"{str(self)}'s {power} updates value from {value} to {new_value}\")\n\t\t\tvalue = new_value\n\t\treturn value\n\n\tdef Select(self, ArenaTargets=1, ArenaSelf=False, ArenaAll=False,\n\t\t\t\tGroupTargets=1, GroupOnlySelf=False, GroupIncludeSelf=False, GroupAll=False, GroupCheckAlive=True):\n\t\t\"\"\"\n\t\t\tUse generator functions Affect() to get monsters affected and for each damage instance, run it through all participants relevant powers\n\t\t\tafter the affect, run through both targets post powers based on the ultimate outcome\n\t\t\"\"\"\n\t\t# Get all the candidate groups\n\t\tarenaGroups = [[val for val in self.Arena.Affect(self.Friendlies, IncludeSelf=ArenaSelf, All=ArenaAll)] for _ in range(ArenaTargets)]\n\t\t# Determine number of targets to pick\n\t\tmaxTargeted = sum([_[0] for _ in arenaGroups])\n\t\tif ArenaTargets is not None:\n\t\t\tmaxTargeted = min(ArenaTargets, maxTargeted)\n\t\t# Make actual groups\n\t\ttargetedGroups = []\n\t\tfor groupList in arenaGroups:\n\t\t\ttargetedGroups.extend(groupList[1:])\n\t\tif ArenaTargets is not None:\n\t\t\t# Randomly target groups up to the number of targets\n\t\t\ttargetedGroups = self.rng.choices(targetedGroups, k=ArenaTargets)\n\n\t\t# Now select group targets in each group\n\t\tmonsterGroups = [[val for val in group.Affect(self, GroupOnlySelf, GroupIncludeSelf, GroupAll, GroupCheckAlive)] for group in targetedGroups]\n\t\t# Refine number of targets to pick\n\t\tmaxTargeted = sum([_[0] for _ in monsterGroups])\n\t\tif GroupTargets is not None:\n\t\t\tmaxTargeted = min(GroupTargets, maxTargeted)\n\t\t# Make actual targets\n\t\ttargetedMonsters = []\n\t\tfor monsterList in monsterGroups:\n\t\t\ttargetedMonsters.extend(monsterList[1:])\n\t\tif GroupTargets is not None:\n\t\t\t# Randomly target monsters across groups up to the number of targets\n\t\t\ttargetedMonsters = self.rng.choices(targetedMonsters, k=GroupTargets)\n\t\t# Return the targeted Monsters\n\t\treturn targetedMonsters\n\n\tdef ApplyPowers(self, *powers, affectClass=SOURCE.SKILL,\n\t\t\t\tArenaTargets=1, ArenaSelf=False, ArenaAll=False,\n\t\t\t\tGroupTargets=1, GroupOnlySelf=False, GroupIncludeSelf=False, GroupAll=False, GroupCheckAlive=True,\n\t\t\t\textras=[]):\n\t\t\"\"\"\n\t\t\tCALL FROM THE OBJECT APPLYING THE POWERS\n\t\t\tpowers = list of Power objects to add to the target Objects\n\t\t\taffectClass is enum for ATTACK/POWER/SKILL/FX to determine if this application triggers any other powers\n\t\t\tothers specify how to locate targets for the power application\n\t\t\"\"\"\n\t\ttargets = self.Select(ArenaTargets=ArenaTargets, ArenaSelf=ArenaSelf, ArenaAll=ArenaAll,\n\t\t\t\tGroupTargets=GroupTargets, GroupOnlySelf=GroupOnlySelf, GroupIncludeSelf=GroupIncludeSelf, GroupAll=GroupAll, GroupCheckAlive=GroupCheckAlive)\n\t\tenemies = self.Select(ArenaTargets=1, ArenaSelf=False, ArenaAll=True,\n\t\t\t\tGroupTargets=1, GroupOnlySelf=False, GroupIncludeSelf=False, GroupAll=True, GroupCheckAlive=GroupCheckAlive)\n\t\tPowers = [[TRIGGER.ON_POWER_GAIN], [TRIGGER.VS_POWER_GAIN]]\n\t\t# Iteratively push powers but push them all at once to allow multipower applications to count as one for power trigger reasons\n\t\tfor target in targets:\n\t\t\ttarget.PowerPool.extend(powers)\n\t\t\t# React to power change\n\t\t\tif target == self:\n\t\t\t\tself.Empower(powers, affectClass, *Powers[0], source=self, target=self)\n\t\t\t\t# Allies and self don't get VS triggers\n\t\t\t\tfor enemy in enemies:\n\t\t\t\t\tenemy.Empower(powers, affectClass, *Powers[1], source=self, target=self, extras=extras)\n\t\t\telse:\n\t\t\t\ttarget.Empower(powers, affectClass, *Powers[0], source=self, target=target, extras=extras)\n\t\t\t\ttargets_enemies = target.Select(ArenaTargets=1, ArenaSelf=False, ArenaAll=True,\n\t\t\t\t\t\t\t\tGroupTargets=1, GroupOnlySelf=False, GroupIncludeSelf=False, GroupAll=True, GroupCheckAlive=GroupCheckAlive)\n\t\t\t\tfor target_enemy in targets_enemies:\n\t\t\t\t\t# Allies of the target and the target itself don't get VS triggers\n\t\t\t\t\ttarget_enemy.Empower(powers, affectClass, *Powers[1], source=self, target=target, extras=extras)\n\t\t# Return targets for logging\n\t\treturn targets\n\n\tdef Damage(self, *amounts, empowerDamage=True, affectClass=SOURCE.ATTACK,\n\t\t\t\tArenaTargets=1, ArenaSelf=False, ArenaAll=False,\n\t\t\t\tGroupTargets=1, GroupOnlySelf=False, GroupIncludeSelf=False, GroupAll=False, GroupCheckAlive=True,\n\t\t\t\textras=[]):\n\t\t\"\"\"\n\t\t\tCALL FROM THE OBJECT DEALING THE DAMAGES\n\t\t\tamounts = list of damage values to produce (affected by powers)\n\t\t\tempowerDamage determines if powers apply to the damage instance (either both ways or no ways)\n\t\t\taffectClass is enum for ATTACK/POWER/SKILL/FX to determine if powers interact differently\n\t\t\tothers specify how to locate targets for the damage instance\n\t\t\"\"\"\n\t\ttargets = self.Select(ArenaTargets=ArenaTargets, ArenaSelf=ArenaSelf, ArenaAll=ArenaAll,\n\t\t\t\tGroupTargets=GroupTargets, GroupOnlySelf=GroupOnlySelf, GroupIncludeSelf=GroupIncludeSelf, GroupAll=GroupAll, GroupCheckAlive=GroupCheckAlive)\n\t\t# Iteratively perform damage\n\t\tdealt = []\n\t\tfor damage in amounts:\n\t\t\tdealt.append(0)\n\t\t\t# Can stop multiattacks early etc if die during the effect\n\t\t\tif self.Alive:\n\t\t\t\tfor target in targets:\n\t\t\t\t\tif empowerDamage:\n\t\t\t\t\t\tPowers = [[TRIGGER.OFFENSE], [TRIGGER.DEFENSE]]\n\t\t\t\t\t\tif affectClass == SOURCE.ATTACK:\n\t\t\t\t\t\t\tPowers[0].append(TRIGGER.ON_ATTACK)\n\t\t\t\t\t\t\tPowers[1].append(TRIGGER.VS_ATTACK)\n\t\t\t\t\t\telif affectClass == SOURCE.SKILL:\n\t\t\t\t\t\t\tPowers[0].append(TRIGGER.ON_SKILL)\n\t\t\t\t\t\t\tPowers[1].append(TRIGGER.VS_SKILL)\n\t\t\t\t\t\telif affectClass == SOURCE.TRIGGER:\n\t\t\t\t\t\t\tPowers[0].append(TRIGGER.ON_POWER_GAIN)\n\t\t\t\t\t\t\tPowers[1].append(TRIGGER.VS_POWER_GAIN)\n\t\t\t\t\t\t# First you get to empower your damage\n\t\t\t\t\t\tdamage = self.Empower(damage, affectClass, *Powers[0], source=self, target=target, extras=extras)\n\t\t\t\t\t\t# Then the target empowers the damage\n\t\t\t\t\t\tdamage = target.Empower(damage, affectClass, *Powers[1], source=self, target=target, extras=extras)\n\t\t\t\t\t# Now that damage has been affected and side effects taken care of by powers, deal the damage\n\t\t\t\t\t# Anything less than 0 damage is 0 damage\n\t\t\t\t\tdamage = max(0, damage)\n\t\t\t\t\ttarget_was_alive = target.Alive\n\t\t\t\t\ttarget.Health -= damage\n\t\t\t\t\tdealt[-1] += damage\n\t\t\t\t\t# Now call post damage powers\n\t\t\t\t\tPowers = [[TRIGGER.AFTER_ATTACK],[TRIGGER.AFTER_ATTACK_ED]]\n\t\t\t\t\tif damage > 0:\n\t\t\t\t\t\tPowers[0].append(TRIGGER.VS_HP_REDUCE)\n\t\t\t\t\t\tPowers[1].append(TRIGGER.ON_HP_REDUCE)\n\t\t\t\t\tif target_was_alive and not target.Alive:\n\t\t\t\t\t\tPowers[0].append(TRIGGER.ON_KILL)\n\t\t\t\t\t\tPowers[1].append(TRIGGER.ON_DEATH)\n\t\t\t\t\tself.Empower(damage, affectClass, *Powers[0], source=self, target=target, extras=extras)\n\t\t\t\t\ttarget.Empower(damage, affectClass, *Powers[1], source=self, target=target, extras=extras)\n\t\t# Return damage dealt for logging\n\t\treturn dealt, targets\n\n\tdef makeMoves(self, *move_tuples):\n\t\tself.Callbacks = []\n\t\tself.Abilities = []\n\t\tfor move in move_tuples:\n\t\t\tself.Callbacks.append(move[1])\n\t\t\tself.Abilities.append(MonsterMove(*move))\n\n\"\"\"\n#2 MonsterGroup (Instanceable)\n\tCollective container for one or more Monsters\n\n\tATTRIBUTES:\n\t\t* Monsters (list of Monsters)\n\t\t* Ephemeral (list of bools to show if Monsters are respawnable or not)\n\t\t* fight_on (Number of monsters ready to fight)\n\tMETHODS:\n\t\t* AddMonster(Monster)\n\t\t* RemoveMonster(Monster) : Some monsters are not removed by dying (ie: DarkSlimes)\n\t\t* Reset() : Respawn all non-ephemeral monsters in the group\n\t\t* Turn() : This group takes a turn\n\t\t* Affect(Monster, OnlySelf, IncludeSelf, All, CheckAlive) : Generator over the group's monsters. If OnlySelf, only yields the Monster if found in the group. IncludeSelf and All work as in the Arena class's Affect(). CheckAlive means the monster needs to respond as alive to be included.\n\"\"\"\nclass MonsterGroup():\n\tdef __init__(self, monsters=[], ID=\"\"):\n\t\tprint(f\"Making monster group out of {monsters}\")\n\t\tself.monsters = monsters\n\t\tself.ID = ID\n\t\tself.ephemeral = [False for _ in monsters]\n\t\tself.fight_on = len(monsters)\n\n\tdef __str__(self):\n\t\treturn f\"{self.ID}\"\n\n\tdef __iter__(self):\n\t\tfor monster in self.monsters:\n\t\t\tyield monster\n\n\tdef AddMonster(self, monster, ephemeral=True):\n\t\tprint(f\"Monster Group is adding monster {monster}\")\n\t\tself.monsters.append(monster)\n\t\tself.ephemeral.append(ephemeral)\n\t\tself.fight_on += 1\n\n\tdef RemoveMonster(self, monster):\n\t\tmonsterIdx = self.monsters.index(monster)\n\t\tself.monsters.remove(monster)\n\t\tdel self.ephemeral[monsterIdx]\n\t\tif monster.Alive:\n\t\t\tself.fight_on -= 1\n\n\tdef Reset(self):\n\t\t\"\"\"\n\t\t\tBrings back all non-empehermal monsters in the group, garbage collector will kill the others\n\t\t\"\"\"\n\t\tself.monsters = [_ for _, ephemeral in zip(self.monsters, self.ephemeral) if not ephemeral]\n\t\tfor monster in self.monsters:\n\t\t\tmonster.Reset()\n\n\tdef Turn(self):\n\t\tfor monster in self.monsters:\n\t\t\tmonster.Turn()\n\t\t# Tick all powers for all monsters after the group's turn\n\t\tfor monster in self.monsters:\n\t\t\tremovePowers = []\n\t\t\tfor power in monster.PowerPool:\n\t\t\t\tremove = power.TurnTick()\n\t\t\t\tif remove:\n\t\t\t\t\tremovePowers.append(power)\n\t\t\t# Remove expired powers\n\t\t\tfor power in removePowers:\n\t\t\t\tmonster.PowerPool.remove(power)\n\n\tdef Affect(self, SourceMonster, OnlySelf=False, IncludeSelf=False, All=False, CheckAlive=True):\n\t\tif OnlySelf:\n\t\t\tif SourceMonster in self.monsters:\n\t\t\t\tyield 1\n\t\t\t\tyield SourceMonster\n\t\telse:\n\t\t\tif IncludeSelf:\n\t\t\t\tgroup = [_ for _ in self.monsters if _.Alive]\n\t\t\telse:\n\t\t\t\tgroup = [_ for _ in self.monsters if _.Alive and _ != SourceMonster]\n\t\t\tyield len(group)\n\t\t\tfor monster in group:\n\t\t\t\tyield monster\n\n\"\"\"\n#3 Arena (Instanceable)\n\tThe Arena holds MonsterGroups to fight one another. MonsterGroups get to fight in the order they are added\n\tATTRIBUTES:\n\t\t* Groups (list of MonsterGroups)\n\t\t* Turn (integer)\n\tMETHODS:\n\t\t* AddGroup(MonsterGroup) : Add a group of monsters to the fight\n\t\t* RemoveGroup(MonsterGroup) : Remove a group of monsters from the fight\n\t\t* Reset() : Respawn all monsters in all groups\n\t\t* Turn() : Execute a turn of combat\n\t\t* Affect(MonsterGroup, IncludeSelf, All) : Generator for included MonsterGroups. Only includes the self-group if IncludeSelf is True, only affects one group at random unless All is True\n\"\"\"\nclass Arena():\n\tdef __init__(self, groups=[], ID=\"\"):\n\t\tself.groups = groups\n\t\tself.turn = 0\n\t\tself.ID = ID\n\t\tglobal global_rng\n\t\tself.rng = global_rng\n\n\tdef __str__(self):\n\t\treturn self.ID\n\n\tdef __iter__(self):\n\t\tfor group in self.groups:\n\t\t\tyield group\n\n\tdef AddGroups(self, *groups):\n\t\tself.groups.extend(groups)\n\n\tdef RemoveGroups(self, *groups):\n\t\tfor group in groups:\n\t\t\tself.groups.remove(group)\n\n\tdef Reset(self):\n\t\tself.turn = 0\n\t\tfor group in self.groups:\n\t\t\tgroup.Reset()\n\n\tdef Turn(self):\n\t\tprint(f\"ARENA BEGINS TURN {self.turn}\")\n\t\tfor group in self.groups:\n\t\t\tgroup.Turn()\n\t\tself.turn += 1\n\n\tdef Affect(self, Friendly, IncludeSelf=False, All=False):\n\t\tif not IncludeSelf:\n\t\t\tgroups = [_ for _ in self.groups if _ != Friendly]\n\t\telse:\n\t\t\tgroups = dcpy(self.groups)\n\t\tif not All:\n\t\t\t# Trim to one group\n\t\t\tgroups = self.rng.choices(groups, k=1)\n\t\t# Iterate over all affected groups\n\t\tyield len(groups)\n\t\tfor group in groups:\n\t\t\tyield group\n\n\tdef Brawl(self, max_turns = None):\n\t\tself.Reset()\n\t\tfight_on = sum([bool(group.fight_on) for group in self.groups])\n\t\twhile fight_on >= 2:\n\t\t\tif max_turns is not None and self.turn >= max_turns:\n\t\t\t\tprint(f\"ARENA TURN LIMIT REACHED\")\n\t\t\t\tbreak\n\t\t\tself.Turn()\n\t\t\tfight_on = sum([bool(group.fight_on) for group in self.groups])\n\t\twinners = []\n\t\tfor group in self.groups:\n\t\t\tif group.fight_on:\n\t\t\t\twinners.append(group)\n\t\treturn winners\n\n","sub_path":"arena.py","file_name":"arena.py","file_ext":"py","file_size_in_byte":16580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"57432843","text":"\"\"\"project URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\n\nfrom calendarapp.views import login_view, home_view, logout_view\n# from apiv2.views import ProjectListView, ProjectDetailView, EventListView, EventDetailView\nfrom api.views import create_project, update_project, get_project, delete_project, create_event, update_event, \\\n delete_event, get_events, archive_project\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n\n # client-side\n url(r'^$', home_view, name='home'),\n url(r'^login/$', login_view, name='login'),\n url(r'^logout/$', logout_view, name='logout'),\n\n # api\n url(r'^api/v1/get-project/$', get_project),\n url(r'^api/v1/create-project/$', create_project),\n url(r'^api/v1/update-project/$', update_project),\n url(r'^api/v1/delete-project/$', delete_project),\n url(r'^api/v1/archive-project/$', archive_project),\n url(r'^api/v1/get-events/$', get_events),\n url(r'^api/v1/create-event/$', create_event),\n url(r'^api/v1/update-event/$', update_event),\n url(r'^api/v1/delete-event/$', delete_event),\n\n # crud api\n # url(r'^api/v2/project/$', ProjectListView.as_view()),\n # url(r'^api/v2/project/(?P[0-9]+)/$', ProjectDetailView.as_view()),\n # url(r'^api/v2/event/$', EventListView.as_view()),\n # url(r'^api/v2/event/(?P[0-9]+)/$', EventDetailView.as_view()),\n]\n","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"637693298","text":"\n\n#calss header\nclass _IMPAIRMENT():\n\tdef __init__(self,): \n\t\tself.name = \"IMPAIRMENT\"\n\t\tself.definitions = [u'the act of spoiling something or making it weaker so that it is less effective', u'deterioration in the functioning of a body part, organ, or system that can be temporary or permanent and can result from injury or disease: ']\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/_impairment.py","file_name":"_impairment.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"505322615","text":"__author__ = 'Bruno'\n\n\"\"\"\nUsing names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names,\nbegin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value\nby its alphabetical position in the list to obtain a name score.\n\nFor example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the\n938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.\n\nWhat is the total of all the name scores in the file?\n\"\"\"\n\nalpha = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13,\n 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25,\n 'Z': 26}\n\na_list = open(\"Files/names.txt\").readlines()\n\na_list = [i.replace('\"', '') for i in a_list[0].split(',')]\na_list.sort()\n\ntotal_letter = 0\ntotal = 0\nfor name in a_list:\n for letter in name:\n total_letter += alpha[letter]\n total += total_letter * (a_list.index(name) + 1)\n total_letter = 0\n\nprint(total)","sub_path":"Problem 22 - Names scores.py","file_name":"Problem 22 - Names scores.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"191145341","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nfrom json import loads, decoder\r\nfrom Settings import header, cookies, soup_type\r\n\r\nclass MasterClass(object):\r\n def __init__(self):\r\n self.header = header\r\n self.cookies = cookies\r\n self.soup_type = soup_type\r\n self.info = ''\r\n self.price = ''\r\n\r\n def extract_data(self, links):\r\n return self.info\r\n\r\n def price_changes(self, links):\r\n return self.price\r\n\r\n def parse_link(self, url):\r\n response = requests.get(url, headers=self.header, cookies=self.cookies)\r\n soup = BeautifulSoup(response.text, str(self.soup_type))\r\n return soup\r\n\r\n\r\nclass OzonSite(MasterClass):\r\n\r\n def extract_data(self, url):\r\n soup = self.parse_link(url)\r\n for h2 in soup.findAll('h2'):\r\n if \"Этот товар закончился\" in str(h2.text).replace(\"\\n\", \"\").replace(\" \", \"\"):\r\n self.info = \"Товар {} закончился, либо остались только некоторые размеры\".format(url)\r\n return self.info\r\n\r\n def price_changes(self, url):\r\n soup = self.parse_link(url)\r\n script_id = str(soup)[\r\n str(soup).find(\"state-webProductMainWidget-\"):str(soup).find(\"state-webProductMainWidget-\") +\r\n len('state-webProductMainWidget-??????-default-1')]\r\n for script in soup.findAll('div',attrs={'id':script_id,}):\r\n try:\r\n old = loads(script['data-state'])['cellTrackingInfo']['product']['price']\r\n new = loads(script['data-state'])['cellTrackingInfo']['product']['finalPrice']\r\n if old == new:\r\n print(loads(script['data-state'])['cellTrackingInfo']['product']['price'])\r\n print(loads(script['data-state'])['cellTrackingInfo']['product']['finalPrice'])\r\n self.price = 'Цена на товар {} составляет {} руб'.format(url, old)\r\n print(self.price)\r\n else:\r\n self.price = 'Цена на товар {} изменилась с {} на {}'.format(url, old, new)\r\n print(self.price)\r\n except KeyError as exp:\r\n print('Error was occurred: ' + str(exp.args[0]))\r\n return self.price\r\n\r\nclass BeruSite(MasterClass):\r\n\r\n def extract_data(self, url):\r\n soup = self.parse_link(url)\r\n for span in soup.findAll('span'):\r\n if 'в наличии на складе' in span.text.lower():\r\n self.info='ok'\r\n if len(self.info) != 0:\r\n self.info = \"Товар {} закончился, либо доставка возможна только позднее\".format(url)\r\n return self.info\r\n\r\n def price_changes(self, url):\r\n soup = self.parse_link(url)\r\n for script in soup.findAll('script',attrs={'type':'application/json'}):\r\n if \"@marketplace/Fink\" in script.string:\r\n try:\r\n fin = loads(script.string)['widgets']['@marketplace/Fink'] \\\r\n ['/content/SkuContent/metrika']['zoneData']['price']\r\n old = loads(script.string)['widgets']['@marketplace/Fink'] \\\r\n ['/content/SkuContent/metrika']['zoneData']['oldPrice']\r\n print(loads(script.string)['widgets']['@marketplace/Fink']\r\n ['/content/SkuContent/metrika']['zoneData']['oldPrice'])\r\n self.price = 'Цена на товар {} изменилась с {} на {}'.format(url, old, fin)\r\n except KeyError:\r\n print(loads(script.string)['widgets']['@marketplace/Fink']\r\n ['/content/SkuContent/metrika']['zoneData']['price'])\r\n cur = loads(script.string)['widgets']['@marketplace/Fink'] \\\r\n ['/content/SkuContent/metrika']['zoneData']['price']\r\n self.price = 'Цена на товар {} составляет {} руб'.format(url,cur)\r\n return self.price\r\n\r\nclass LamodaSite(MasterClass):\r\n\r\n def extract_data(self, url):\r\n soup = self.parse_link(url)\r\n for div in soup.findAll('div',attrs={'class':'vue-widget'}):\r\n rating = div.find('d-add-to-cart') # В тэге хранится информация о наличии товара в магазине\r\n if rating:\r\n if rating['product-is-available']:\r\n self.info='ok'\r\n else:\r\n self.info = \"Товар {} закончился, либо остались только некоторые размеры\".format(url)\r\n return self.info\r\n\r\n def price_changes(self, url):\r\n soup = self.parse_link(url)\r\n for script in soup.findAll('x-product-prices',attrs={'itemprop':'offers'}):\r\n print(loads(script[':detailed-price']))\r\n if int(loads(script[':detailed-price'])['saved']) != 0:\r\n old = loads(script[':detailed-price'])['details'][0]['value']\r\n new = loads(script[':detailed-price'])['details'][1]['value']\r\n self.price = 'Цена на товар {} изменилась с {} на {}'.format(url, old, new)\r\n print(self.price)\r\n else:\r\n cur = loads(script[':detailed-price'])['details'][0]['value']\r\n self.price = 'Цена на товар {} составляет {} руб'.format(url, cur)\r\n print(self.price)\r\n return self.price\r\n\r\nclass WildBerriesSite(MasterClass):\r\n\r\n def extract_data(self, url):\r\n soup = self.parse_link(url)\r\n for button in soup.findAll('button',attrs={'class':'c-btn-main-lg-v1 j-add-to-wait'}):\r\n if 'hide' not in button['class']:\r\n if 'в лист ожидания' in button.text.lower():\r\n self.info = \"Товар {} закончился, либо остались только некоторые варианты\".format(url)\r\n return self.info\r\n\r\n def price_changes(self, url):\r\n soup = self.parse_link(url)\r\n for script in soup.findAll('script',attrs={'type':'text/javascript'}):\r\n try:\r\n if 'google_tag_params' in script.string:\r\n data = loads(script.string[script.string.find('google_tag_params')+20:script.string.find(';')])\r\n print(data)\r\n if 'Discount' in data:\r\n new = data['Value']\r\n self.price = 'Цена на товар {} изменилась и составляет {}'.format(url, new)\r\n print(self.price)\r\n else:\r\n print(data['Value'])\r\n cur = data['Value']\r\n self.price = 'Цена на товар {} составляет {} руб'.format(url, cur)\r\n print(self.price)\r\n except (AttributeError, decoder.JSONDecodeError) as exp:\r\n print('Error was occurred: ' + str(exp.args[0]))\r\n return self.price\r\n\r\nclass AptekaSite(MasterClass):\r\n\r\n def extract_data(self, url):\r\n soup = self.parse_link(url)\r\n for div in soup.findAll('div', attrs={'class':'stickProductCard__notAvailable'}):\r\n if 'нет в наличии' in div.text.lower():\r\n self.info = \"Товар {} закончился, либо остались только некоторые экземпляры\".format(url)\r\n return self.info\r\n\r\n def price_changes(self, url):\r\n soup = self.parse_link(url)\r\n for script in soup.findAll('script'):\r\n try:\r\n if 'window.__INITIAL_STATE__' in script.string:\r\n data = loads(script.string[script.string.find('{'):])\r\n print(list(data['product']['iteminfo'].keys())[0])\r\n elem = list(data['product']['iteminfo'].keys())[0]\r\n new = data['product']['products'][str(elem)]['price']\r\n old = data['product']['products'][str(elem)]['noDiscPrice']\r\n if old == new:\r\n print(data['product']['products'][str(elem)]['price'])\r\n print(data['product']['products'][str(elem)]['noDiscPrice'])\r\n self.price = 'Цена на товар {} составляет {} руб'.format(url, old)\r\n print(self.price)\r\n else:\r\n self.price = 'Цена на товар {} изменилась с {} на {}'.format(url, old, new)\r\n print(self.price)\r\n except (TypeError, decoder.JSONDecodeError, KeyError) as exp:\r\n print('Error was occurred: ' + str(exp.args[0]))\r\n return self.price\r\n\r\nclass DetMitSite(MasterClass):\r\n\r\n def extract_data(self, url):\r\n soup = self.parse_link(url)\r\n for span in soup.findAll('span'):\r\n if 'нет в наличии' in span.text.lower():\r\n self.info = \"Товар {} закончился, либо остались только некоторые экземпляры\".format(url)\r\n return self.info\r\n\r\n def price_changes(self, url):\r\n soup = self.parse_link(url)\r\n for script in soup.findAll('script', attrs={'type':'text/template', 'id':'app-data'}):\r\n try:\r\n data = loads(script.string.replace('"','\"'))\r\n print(data['product']['data']['item']['price'])\r\n print(data['product']['data']['item']['old_price'])\r\n new = data['product']['data']['item']['price']\r\n old = data['product']['data']['item']['old_price']\r\n if new != old and old is not None:\r\n self.price = 'Цена на товар {} изменилась с {} на {}'.format(url, old['price'], new['price'])\r\n print(self.price)\r\n else:\r\n self.price = 'Цена на товар {} составляет {} руб'.format(url, new['price'])\r\n print(self.price)\r\n\r\n except (KeyError, decoder.JSONDecodeError, TypeError) as exp:\r\n print('Error was occurred: ' + str(exp.args[0]))\r\n return self.price","sub_path":"telegramadvchkbot/Sites.py","file_name":"Sites.py","file_ext":"py","file_size_in_byte":10551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"364459548","text":"import os\nfrom flask import Flask, g, render_template, flash, redirect, url_for\nfrom flask_login import (LoginManager, login_user, logout_user,\nlogin_required, current_user)\nfrom flask_bcrypt import check_password_hash\n\nimport forms\nimport models\nimport config\n\n''' initialize program '''\napp = Flask(__name__)\napp.secret_key = config.SECRET_KEY\n\n''' login middleware '''\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n@login_manager.user_loader\ndef load_user(userid):\n\ttry:\n\t\treturn models.User.get(models.User.id == userid)\n\texcept models.DoesNotExist:\n\t\treturn None\n\n''' pool db connections '''\n@app.before_request\ndef before_request():\n\tg.db = models.DATABASE\n\tg.db.connect()\n\tg.user = current_user\n\n@app.after_request\ndef after_request(response):\n\tg.db.close()\n\treturn response\n\n##############\n''' ROUTES '''\n##############\n\n''' 404 '''\n@app.errorhandler(404)\ndef pet_404(e):\n\treturn render_template('404.html'), 404\n\n''' index/dashboard '''\n@app.route('/')\ndef dashboard():\n\t# if user is not logged in, redirect to login screen\n\tif current_user.is_anonymous:\n\t\treturn redirect(url_for('login'))\n\telse: \n\t\t# get posts, the logged in user, and any messages sent\n\t\tposts = models.Post.select()\n\t\tuser = current_user\n\t\treceived_messages = models.Message.select().where(models.Message.recipient == user.id)\n\t\tmessages = received_messages.select().where(models.Message.unread == True)\n\t\tif messages:\n\t\t\t# if the logged in user was the recipient of the messages sent\n\t\t\tif user.id == models.Message.recipient:\n\t\t\t\t# and if there are posts, render normal dashboard template\n\t\t\t\tif posts:\n\t\t\t\t\treturn render_template('dashboard.html', unread = True, posts = posts, user = user)\n\t\t\t\t# if there are no posts, render empty dashboard template\n\t\t\t\telse:\n\t\t\t\t\treturn render_template('dashboard-empty.html', unread = True, user = user)\n\t\t\telse:\n\t\t\t\tif posts:\n\t\t\t\t\treturn render_template('dashboard.html', unread = False, posts = posts, user = user)\n\t\t\t\telse:\n\t\t\t\t\treturn render_template('dashboard-empty.html', unread = False, user = user)\n\t\telse:\n\t\t\tif posts:\n\t\t\t\treturn render_template('dashboard.html', unread = False, posts = posts, user = user)\n\t\t\telse:\n\t\t\t\treturn render_template('dashboard-empty.html', unread = False, user = user)\n\n''' registration '''\n@app.route('/register', methods = ('GET', 'POST'))\ndef register_account():\n\t# for post method --> pass data from form\n\tform = forms.RegisterForm()\n\tif form.validate_on_submit():\n\t\t# register the new user\n\t\tmodels.User.create_a_user(\n\t\t\tusername = form.username.data,\n\t\t\tdisplay_name = form.display_name.data,\n\t\t\tlocation = form.location.data,\n\t\t\tpassword = form.password.data,\n\t\t\temail = form.email.data\n\t\t)\n\t\tuser = models.User.get(models.User.username == form.username.data)\n\t\t# log in newly registered user, send them to dashboard\n\t\tlogin_user(user)\n\t\treturn redirect(url_for('dashboard'))\n\t# for get method --> retrieve form\n\treturn render_template('register.html', form = form)\n\n''' logging in '''\n@app.route('/login', methods = ('GET', 'POST'))\ndef login():\n\tform = forms.LoginForm()\n\tif form.validate_on_submit():\n\t\ttry:\n\t\t\t user = models.User.get(models.User.email == form.email.data)\n\t\t# if the user's credential does not exist:\n\t\texcept models.DoesNotExist:\n\t\t\tflash('Your email or password does not match.')\n\t\t# if the user's credential exists:\n\t\telse:\n\t\t\tif check_password_hash(user.password, form.password.data):\n\t\t\t\tlogin_user(user)\n\t\t\t\treturn redirect(url_for('dashboard'))\n\t\t\telse:\n\t\t\t\tflash('Your email or password does not match.')\n\treturn render_template('login.html', form = form)\n\n''' logging out '''\n@login_required\n@app.route('/logout')\ndef logout():\n\t# destroy session, redirect to login screen\n\tlogout_user()\n\treturn redirect(url_for('login'))\n\n''' user clicked delete user button, send to confirmation page '''\n@login_required\n@app.route('/users//are_you_sure')\ndef delete_route_to_confirm(id):\n\tuser = models.User.select().where(models.User.id == id)\n\treturn render_template('confirm-delete-profile.html', user = user, id = id)\t\n\n''' after confirmation, delete a user '''\n@login_required\n@app.route('/users//delete', methods = ('GET', 'DELETE'))\ndef delete_user(id):\n\tu = models.User.select().where(models.User.id == id).get()\n\tif u == current_user:\n\t\t# delete user's posts\n\t\tposts = models.Post.delete().where(models.Post.user == id)\n\t\tposts.execute()\n\t\t# delete user's pets\n\t\tpets = models.Pet.delete().where(models.Pet.owner == id)\n\t\tpets.execute()\n\t\t# remove the user's id from the messages they have sent so our model doesn't break if a user does not exist\n\t\tsent_messages = models.Message.delete().where(models.Message.sender == id)\n\t\tsent_messages.execute()\n\t\t# \"\" from messages they have received \"\"\n\t\treceived_messages = models.Message.delete().where(models.Message.recipient == id)\n\t\treceived_messages.execute()\n\t\t# destroy user\n\t\tuser = models.User.delete().where(models.User.id == id)\n\t\tuser.execute()\n\t\t# destroy user's session\n\t\tlogout_user()\n\t\treturn redirect(url_for('login'))\n\telse:\n\t\treturn render_template('404.html')\n\n'''edit and update a user'''\n@login_required\n@app.route('/users//edit', methods = ('GET', 'POST'))\ndef update_user(id):\n\tuser = models.User.select().where(models.User.id == id).get()\n\tif user == current_user:\n\t\t# if the user is the user logged in, get the update form\n\t\tform = forms.UserUpdateForm(\n\t\t\tlocation = user.location,\n\t\t\tbio = user.bio\n\t\t)\n\t\tif form.validate_on_submit():\n\t\t\t# update the user\n\t\t\tu = models.User.update(\n\t\t\t\tlocation = form.location.data,\n\t\t\t\tbio = form.bio.data\n\t\t\t).where(models.User.id == id)\n\t\t\tu.execute()\n\t\t\treturn redirect(url_for('get_profile', id = id))\n\t\treturn render_template('edit-user.html', form=form, user=user)\n\telse:\n\t\treturn render_template('404.html')\n\n''' adding a new post '''\n@login_required\n@app.route('/new_post', methods = ('GET', 'POST'))\ndef new_post():\n\tform = forms.PostForm()\n\tuser = models.User.select().where(models.User.id == current_user.id).get()\n\tpets = models.Pet.select().where(models.Pet.owner == user)\n\t# list of dropdown choices from user's registered pets for the pet the user is posting about\n\tpetList = []\n\tfor pet in pets:\n\t\tpetList.append((pet.id, pet.name))\n\tform.pet.choices = petList\n\tif form.validate_on_submit():\n\t\t# create post\n\t\tmodels.Post.create(\n\t\t\tuser = g.user._get_current_object(),\n\t\t\tcontent = form.content.data.strip(),\n\t\t\tpet = form.pet.data,\n\t\t\trequested_time = form.requested_time.data\n\t\t)\n\t\treturn redirect(url_for('dashboard'))\n\treturn render_template('post.html', form = form)\n\n''' removing a post when a job is accepted '''\n@login_required\n@app.route('/posts//delete', methods = ('GET', 'DELETE'))\ndef delete_post(id):\n\tpost = models.Post.delete().where(models.Post.id == id)\n\t# get user id so that we can return the user to their profile instead of the dashboard after they erase a post \n\t# --> button that hits route is only accessible from user profile\n\tuserid = models.User.select().where(models.User.id == current_user.id).get()\n\tpost.execute()\n\treturn redirect(url_for('get_profile', id = userid))\n\n''' edit a post '''\n@login_required\n@app.route('/posts//edit', methods=('GET', 'POST'))\ndef update_post(id):\n\t# as above, get user id so they can be redirected to their profile\n\tuserid = models.User.select().where(models.User.id == current_user.id).get()\n\tpost = models.Post.select().where(models.Post.id == id).get()\n\tif current_user == post.user:\n\t\tform = forms.UpdatePostForm(\n\t\t\tcontent = post.content,\n\t\t)\n\t\tprint(form)\n\t\tif form.validate_on_submit():\n\t\t\tprint(post.content)\n\t\t\tquery = post.update(\n\t\t\t\tcontent = form.content.data,\n\t\t\t\trequested_time = form.requested_time.data\n\t\t\t).where(models.Post.id == id)\n\t\t\tquery.execute()\n\t\t\tprint(post.content)\n\t\t\treturn redirect(url_for('get_profile', id = userid))\n\t\treturn render_template('edit-post.html', form=form)\n\telse:\n\t\treturn render_template('404.html')\n\n''' add a new pet '''\n@login_required\n@app.route('/new_pet', methods = ('GET', 'POST'))\ndef new_pet():\n\tform = forms.PetForm()\n\tif form.validate_on_submit():\n\t\t# create new pet\n\t\tmodels.Pet.create(\n\t\t\tname = form.name.data,\n\t\t\tage = form.age.data,\n\t\t\tpet_type = form.pet_type.data,\n\t\t\tspecial_requirements = form.special_requirements.data,\n\t\t\towner = models.User.select().where(models.User.id == current_user.id).get()\n\t\t)\n\t\treturn redirect(url_for('dashboard'))\n\treturn render_template('add-pet.html', form = form)\n\n''' show a pet '''\n@login_required\n@app.route('/pets/')\ndef show_pet(id):\n\t# get pet by id\n\tpet = models.Pet.select().where(models.Pet.id == id).get()\n\treturn render_template('show-pet.html', pet = pet)\n\t\n''' edit and update a pet '''\n@login_required\n@app.route('/pets//edit', methods = ('GET', 'POST'))\ndef update_pet(id):\n\tpet = models.Pet.select().where(models.Pet.id == id).get()\n\tif pet.owner == current_user:\n\t\tform = forms.PetForm(\n\t\t\tname = pet.name,\n\t\t\tpet_type = pet.pet_type,\n\t\t\tage = pet.age,\n\t\t\tspecial_requirements = pet.special_requirements\n\t\t)\n\t\tif form.validate_on_submit():\n\t\t\tp = models.Pet.update(\n\t\t\t\tname = form.name.data,\n\t\t\t\tage = form.age.data,\n\t\t\t\tpet_type = form.pet_type.data,\n\t\t\t\tspecial_requirements = form.special_requirements.data\n\t\t\t).where(models.Pet.id == id)\n\t\t\tp.execute()\n\t\t\treturn redirect(url_for('show_pet', id = id))\n\t\treturn render_template('edit-pet.html', form=form, pet=pet)\n\telse:\n\t\treturn render_template('404.html')\n\n''' delete a pet '''\n@login_required\n@app.route('/pets//delete', methods = ('GET', 'DELETE'))\ndef delete_pet(id):\n\t# delete the posts that were about this pet\n\tposts = models.Post.delete().where(models.Post.pet == id)\n\tposts.execute()\n\t# delete the pet\n\tpet = models.Pet.delete().where(models.Pet.id == id)\n\tpet.execute()\n\treturn redirect(url_for('dashboard'))\n\n''' view user profile '''\n@login_required\n@app.route('/users/')\ndef get_profile(id):\n\t# if the user trying to access someone else's profile\n\tif id != current_user.id:\n\t\tuser = models.User.select().where(models.User.id == id).get()\n\t\tsession_user = current_user\n\t# if they want to see their own profile\n\telse:\n\t\tsession_user = current_user.id\n\t\tuser = session_user\n\t# get pets, posts\n\tpets = models.Pet.select().where(models.Pet.owner == user)\n\tposts = models.Post.select().where(models.Post.user == user)\n\treturn render_template('user_profile.html', user = user, session_user = session_user, \n\t\tpets = pets, posts = posts)\n\n''' send a message '''\n@login_required\n@app.route('/send/', methods = ('GET', 'POST'))\ndef send_message(recipient):\n\t# get the recipient of the message, get the current user, and render the send message form\n\tuser = models.User.select().where(models.User.id == recipient).get()\n\tcurrent = models.User.select().where(models.User.username == current_user.username).get()\n\tform = forms.MessageForm()\n\tif form.validate_on_submit():\n\t\tmodels.Message.create(\n\t\t\tcontent = form.content.data,\n\t\t\tsender = current,\n\t\t\trecipient = user\n\t\t)\n\t\treturn redirect(url_for('dashboard'))\n\treturn render_template('send_message.html', form = form, recipient = recipient)\n\n''' view your messages '''\n@login_required\n@app.route('/messages')\ndef read_message():\n\t# get messages the user has received\n\tmessages = models.Message.select().where(models.Message.recipient == current_user.id)\n\tif messages:\n\t\t# upon opening inbox, update unread property to false to remove the unread message notification\n\t\tmessages_to_update = models.Message.select().where(\n\t\t\tmodels.Message.recipient == current_user.id\n\t\t\tand models.Message.unread == True)\n\t\tif messages_to_update:\n\t\t\tupdate = models.Message.update(unread = False)\n\t\t\tupdate.execute()\n\t\treturn render_template('view_message.html', messages = messages)\n\telse:\n\t\treturn render_template('no_messages.html')\n\t\n\n''' delete a message '''\n@login_required\n@app.route('/messages//delete', methods = ('GET', 'DELETE'))\ndef delete_message(id):\n\tmessage = models.Message.delete().where(models.Message.id == id)\n\tmessage.execute()\n\treturn redirect(url_for('read_message'))\n\t\n''' for deployment on heroku '''\nif 'ON_HEROKU' in os.environ:\n\tprint('deployed ')\n\tmodels.init_database()\nelse:\n\tif __name__ == '__main__':\n\t\t''' initialize database '''\n\t\tmodels.init_database()\n\t\t''' only needs to be run for local testing -- gunicorn does this on heroku '''\n\t\tapp.run(debug = config.DEBUG, port = config.PORT, host='0.0.0.0')","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"446430783","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom .forms import UploadFileForm\nfrom .models import Vendas\nfrom django.db.models import Sum\n\n\n\ndef upload_file(request):\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n if form.is_valid(): \t\n \tform.save()\n \tparse_file(request.FILES['file'])\n \treturn HttpResponseRedirect('/sucess/')\n else:\n form = UploadFileForm()\n return render(request, 'upload/upload_file.html', {'form': form})\n\ndef sucess(request):\n \treturn render(request, 'upload/sucess.html', locals())\n\n\ndef parse_file(f):\n\tfilename = f.name\n\tdata=[row.split('\\t') for row in file(\"myfreecom/media/uploads/\" + filename ,'r').readlines()]\n\tresult=data[1:]\n\tfor i in result:\n\t\ta = Vendas(purchasername=i[0], itemdescription=i[1], itemprice=i[2], purchasecount=i[3], merchantaddress=i[4], merchantname=i[5])\n\t\ta.save()\n\n\ndef ver_total(request):\n\tv=Vendas.objects.extra(select = {'total': 'SUM(itemprice*purchasecount)'},)\n\t#v = Vendas.objects.raw('SELECT SUM(itemprice*purchasecount) AS TOTAL FROM upload_vendas')\n\t#v = Vendas.objects.all()\n\t#v=Vendas.objects.aggregate(Sum('itemprice' ))\n\treturn render(request, 'upload/ver_total.html', locals())\n\n\n\n\n\n\t\n\t\n\n\n\n\n","sub_path":"upload/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"126174633","text":"import scrapy\nfrom ..baseSpider import BaseSpider\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import Rule\n\n\nclass NntvSpider(BaseSpider):\n name = 'pbt'\n source_name = '老友网'\n allowed_domains = ['www.nntv.cn']\n spider_tags = ['广西', '南宁', '论坛']\n start_urls = [\n 'http://www.nntv.cn/news/m/list.shtml',\n 'http://www.nntv.cn/bl/list.shtml'\n\n ]\n rules = [Rule(LinkExtractor(allow=(r'/news/m/\\d+-\\d+-\\d+/\\d+.shtml')), callback='parse_item1', follow=False),\n Rule(LinkExtractor(allow=(r'/bl/bl_content_\\d+.shtml')), callback='parse_item2', follow=False)\n ]\n\n def parse_item1(self, response):\n\n item = self.createItem(response)\n\n item['title'] = response.css('.subject h1::text').extract_first()\n\n item['taskName'] = \"http://www.nntv.cn/img/logo2014_white.png\"\n\n item['postBy'] = response.css('.editor::text').extract_first()[5:-2]\n\n item['postOn'] = response.css('.time::text').extract_first() + ':00'\n\n item['text'] = ''.join(response.css('.contentText *::text').extract())\n\n return item\n\n def parse_item2(self, response):\n item = self.createItem(response)\n\n item['title'] = response.css('.content_left_header h3::text').extract_first()\n item['postBy'] = '老友网'\n item['postOn'] = response.css('.content_left_header p span::text').extract_first().replace('年', '-').replace('月', '-').replace('日', ' ') + '00:00:00'\n\n item['text'] = ''.join(response.css('.content_left_center *::text').extract())\n\n return item\n","sub_path":"crawl2020/spiders/nntv.py","file_name":"nntv.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"7850916","text":"# Copyright 2021 Jan-Jaap Kostelijk\r\n#\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy\r\n# of this software and associated documentation files (the \"Software\"), to deal\r\n# in the Software without restriction, including without limitation the rights\r\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n# copies of the Software, and to permit persons to whom the Software is furnished\r\n# to do so, subject to the following conditions:\r\n#\r\n# The above copyright notice and this permission notice shall be included in\r\n# all copies or substantial portions of the Software.\r\n#\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\r\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\r\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN\r\n# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r\n# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r\n\"\"\"\r\n\r\n \r\n

GoodWe inverter (via SEMS portal)

\r\n

This plugin uses the GoodWe SEMS api to retrieve the status information of your GoodWe inverter.

\r\n

Configuration

\r\n
    \r\n
  • Register your inverter at GoodWe SEMS portal (if not done already): https://www.semsportal.com
  • \r\n
  • Choose one of the following options:
  • \r\n
      \r\n
    1. You have to add one specific station to Domoticz follow the following steps:
    2. \r\n
        \r\n
      1. Login to your account on: www.semsportal.com
      2. \r\n
      3. Go to the plant status page for the station you want to add to Domoticz
      4. \r\n
      5. Get the station ID from the URL, this is the sequence of characters after: https://www.semsportal.com/PowerStation/PowerStatusSnMin/, in the pattern:\r\n (8 char)-(4 char)-(4 char)-(4 char)-(12 char), also known as a UUID
      6. \r\n
      7. Add the power station ID to the hardware configuration (mandatory)
      8. \r\n
      \r\n
    3. Not possible at this moment: If you want all of your stations added to Domoticz you only have to enter your login information below
    4. \r\n
    \r\n
\r\n
\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n
\r\n\"\"\"\r\nimport json\r\nimport Domoticz\r\nimport sys, time\r\nfrom datetime import datetime, timedelta\r\nfrom GoodWe import GoodWe\r\nfrom GoodWe import PowerStation\r\nimport exceptions\r\nimport logging\r\n\r\nclass GoodWeSEMSPlugin:\r\n httpConn = None\r\n runAgain = 6\r\n devicesUpdated = False\r\n goodWeAccount = None\r\n logger = None \r\n \r\n baseDeviceIndex = 0\r\n maxDeviceIndex = 0\r\n log_filename = \"goodwe.log\"\r\n\r\n def __init__(self):\r\n return\r\n\r\n def apiConnection(self):\r\n if Parameters[\"Port\"] == \"443\":\r\n return Domoticz.Connection(Name=\"SEMS Portal API\", Transport=\"TCP/IP\", Protocol=\"HTTPS\",\r\n Address=Parameters[\"Address\"], Port=Parameters[\"Port\"])\r\n else:\r\n return Domoticz.Connection(Name=\"SEMS Portal API\", Transport=\"TCP/IP\", Protocol=\"HTTP\",\r\n Address=Parameters[\"Address\"], Port=Parameters[\"Port\"])\r\n\r\n def startDeviceUpdateV2(self):\r\n logging.debug(\"startDeviceUpdate, token availability: '\" + str(self.goodWeAccount.tokenAvailable)+ \"'\")\r\n if not self.goodWeAccount.tokenAvailable:\r\n self.goodWeAccount.powerStationList = {}\r\n self.goodWeAccount.powerStationIndex = 0\r\n self.devicesUpdated = False\r\n try:\r\n self.goodWeAccount.tokenRequest()\r\n except (exceptions.GoodweException, exceptions.FailureWithMessage, exceptions.FailureWithoutMessage) as exp:\r\n logging.error(\"Failed to request data: \" + str(exp))\r\n Domoticz.Error(\"Failed to request data: \" + str(exp))\r\n return\r\n \r\n if self.goodWeAccount.tokenAvailable:\r\n try:\r\n DeviceData = self.goodWeAccount.stationDataRequestV2(Parameters[\"Mode1\"])\r\n except (exceptions.TooManyRetries, exceptions.FailureWithErrorCode, exceptions.FailureWithoutErrorCode) as exp:\r\n logging.error(\"Failed to request data: \" + str(exp))\r\n Domoticz.Error(\"Failed to request data: \" + str(exp))\r\n return\r\n self.goodWeAccount.createStationV2(DeviceData)\r\n self.updateDevices(DeviceData)\r\n\r\n def updateDevices(self, apiData):\r\n theStation = self.goodWeAccount.powerStationList[1]\r\n for inverter in apiData[\"inverter\"]:\r\n logging.debug(\"inverter found with SN: '\" + inverter[\"sn\"] + \"'\")\r\n if inverter[\"sn\"] in theStation.inverters:\r\n theStation.inverters[inverter[\"sn\"]].createDevices(Devices)\r\n \r\n theInverter = theStation.inverters[inverter[\"sn\"]]\r\n\r\n if len(inverter['fault_message']) > 0:\r\n Domoticz.Log(\"Fault message from GoodWe inverter (SN: \" + inverter[\"sn\"] + \"): '\" + str(inverter['fault_message']) + \"'\")\r\n logging.info(\"Fault message from GoodWe inverter (SN: \" + inverter[\"sn\"] + \"): '\" + str(inverter['fault_message']) + \"'\")\r\n Domoticz.Log(\"Status of GoodWe inverter (SN: \" + inverter[\"sn\"] + \"): '\" + str(inverter[\"status\"]) + ' ' + self.goodWeAccount.INVERTER_STATE[inverter[\"status\"]] + \"'\")\r\n logging.info(\"Status of GoodWe inverter (SN: \" + inverter[\"sn\"] + \"): '\" + str(inverter[\"status\"]) + ' ' + self.goodWeAccount.INVERTER_STATE[inverter[\"status\"]] + \"'\")\r\n Devices[theInverter.inverterStateUnit].Update(nValue=inverter[\"status\"]+1, sValue=str((inverter[\"status\"]+2)*10))\r\n if self.goodWeAccount.INVERTER_STATE[inverter[\"status\"]] == 'generating':\r\n logging.debug(\"inverter generating, log temp\")\r\n UpdateDevice(theInverter.inverterTemperatureUnit, 0, str(inverter[\"tempperature\"]))\r\n UpdateDevice(theInverter.outputFreq1Unit, 0, str(inverter[\"d\"][\"fac1\"]))\r\n\r\n UpdateDevice(theInverter.outputCurrentUnit, 0, str(inverter[\"output_current\"]), AlwaysUpdate=True)\r\n UpdateDevice(theInverter.outputVoltageUnit, 0, str(inverter[\"output_voltage\"]), AlwaysUpdate=True)\r\n UpdateDevice(theInverter.outputPowerUnit, 0, str(inverter[\"output_power\"]) + \";\" + str(inverter[\"etotal\"] * 1000), AlwaysUpdate=True)\r\n inputVoltage,inputAmps = inverter[\"pv_input_1\"].split('/')\r\n inputPower = (float(inputVoltage[:-1])) * (float(inputAmps[:-1])) #calculate the power based on P = I * V in Watt\r\n UpdateDevice(theInverter.inputVoltage1Unit, 0, inputVoltage, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputAmps1Unit, 0, inputAmps, AlwaysUpdate=True)\r\n\r\n newCounter = calculateNewEnergy(theInverter.inputPower1Unit, inputPower)\r\n UpdateDevice(theInverter.inputPower1Unit, 0, \"{:5.1f};{:10.2f}\".format(inputPower, newCounter), AlwaysUpdate=True)\r\n\r\n if \"pv_input_2\" in inverter:\r\n logging.debug(\"Second string found\")\r\n inputVoltage,inputAmps = inverter[\"pv_input_2\"].split('/')\r\n UpdateDevice(theInverter.inputVoltage2Unit, 0, inputVoltage, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputAmps2Unit, 0, inputAmps, AlwaysUpdate=True)\r\n inputPower = (float(inputVoltage[:-1])) * (float(inputAmps[:-1]))\r\n newCounter = calculateNewEnergy(theInverter.inputPower2Unit, inputPower)\r\n UpdateDevice(theInverter.inputPower2Unit, 0, \"{:5.1f};{:10.2f}\".format(inputPower, newCounter), AlwaysUpdate=True)\r\n if \"pv_input_3\" in inverter:\r\n logging.debug(\"Third string found\")\r\n inputVoltage,inputAmps = inverter[\"pv_input_3\"].split('/')\r\n UpdateDevice(theInverter.inputVoltage3Unit, 0, inputVoltage, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputAmps3Unit, 0, inputAmps, AlwaysUpdate=True)\r\n inputPower = float(inputVoltage[:-1]) * float(inputAmps[:-1])\r\n newCounter = calculateNewEnergy(theInverter.inputPower3Unit, inputPower)\r\n UpdateDevice(theInverter.inputPower3Unit, 0, \"{:5.1f};{:10.2f}\".format(inputPower, newCounter), AlwaysUpdate=True)\r\n if \"pv_input_4\" in inverter:\r\n logging.debug(\"Fourth string found\")\r\n inputVoltage,inputAmps = inverter[\"pv_input_4\"].split('/')\r\n UpdateDevice(theInverter.inputVoltage4Unit, 0, inputVoltage, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputAmps4Unit, 0, inputAmps, AlwaysUpdate=True)\r\n inputPower = float(inputVoltage[:-1]) * float(inputAmps[:-1])\r\n newCounter = calculateNewEnergy(theInverter.inputPower4Unit, inputPower)\r\n UpdateDevice(theInverter.inputPower4Unit, 0, \"{:5.1f};{:10.2f}\".format(inputPower, newCounter), AlwaysUpdate=True)\r\n #log data of battery\r\n Domoticz.Debug(\"Battery values: battery: '{0}', bms_status: '{1}', battery_power: '{2}'\".format(inverter[\"battery\"],inverter[\"bms_status\"],inverter[\"battery_power\"]))\r\n logging.debug(\"Battery values: battery: '{0}', bms_status: '{1}', battery_power: '{2}'\".format(inverter[\"battery\"],inverter[\"bms_status\"],inverter[\"battery_power\"]))\r\n\r\n def onStart(self):\r\n self.logger = logging.getLogger('root')\r\n if Parameters[\"Mode6\"] == \"Verbose\":\r\n Domoticz.Debugging(1)\r\n logging.basicConfig(format='%(asctime)s - %(levelname)-8s - %(filename)-18s - %(message)s', filename=self.log_filename,level=logging.DEBUG)\r\n Domoticz.Status(\"Starting Goodwe SEMS API plugin, logging to file {0}\".format(self.log_filename))\r\n DumpConfigToLog()\r\n elif Parameters[\"Mode6\"] == \"Debug\":\r\n Domoticz.Debugging(2)\r\n logging.basicConfig(format='%(asctime)s - %(levelname)-8s - %(filename)-18s - %(message)s', filename=self.log_filename,level=logging.DEBUG)\r\n Domoticz.Status(\"Starting Goodwe SEMS API plugin, logging to file {0}\".format(self.log_filename))\r\n DumpConfigToLog()\r\n else:\r\n logging.basicConfig(format='%(asctime)s - %(levelname)-8s - %(filename)-18s - %(message)s', filename=self.log_filename,level=logging.INFO)\r\n Domoticz.Status(\"Starting Goodwe SEMS API plugin, logging to file {0}\".format(self.log_filename))\r\n \r\n logging.info(\"starting plugin version \"+Parameters[\"Version\"])\r\n\r\n self.goodWeAccount = GoodWe(Parameters[\"Address\"], Parameters[\"Port\"], Parameters[\"Username\"], Parameters[\"Password\"])\r\n self.runAgain = int(Parameters[\"Mode2\"])\r\n\r\n if len(Parameters[\"Mode1\"]) == 0:\r\n Domoticz.Error(\"No Power Station ID provided, exiting\")\r\n logging.error(\"No Power Station ID provided, exiting\")\r\n return\r\n \r\n self.startDeviceUpdateV2()\r\n\r\n def onStop(self):\r\n Domoticz.Log(\"onStop - Plugin is stopping.\")\r\n logging.info(\"onStop - Plugin is stopping.\")\r\n if self.httpConn is not None:\r\n self.httpConn.Disconnect()\r\n\r\n def onConnect(self, Connection, Status, Description):\r\n logging.debug(\"onConnect: Status: '\" + str(Status) + \"', Description: '\" + Description + \"'\")\r\n if (Status == 0):\r\n logging.debug(\"Connected to SEMS portal API successfully.\")\r\n self.startDeviceUpdate(Connection)\r\n else:\r\n Domoticz.Log(\"Failed to connect (\" + str(Status) + \") to: \" + Parameters[\"Address\"] + \":\" + Parameters[\r\n \"Port\"] + \" with error: \" + Description)\r\n logging.info(\"Failed to connect (\" + str(Status) + \") to: \" + Parameters[\"Address\"] + \":\" + Parameters[\r\n \"Port\"] + \" with error: \" + Description)\r\n\r\n def onMessage(self, Connection, Data):\r\n logging.debug(\"onMessage: data received: Data : '\" + str(Data) + \"'\")\r\n status = int(Data[\"Status\"])\r\n\r\n if status == 200:\r\n apiUrl = \"\"\r\n try:\r\n #apiResponse sometimes contains invalid data, catch the exception\r\n if \"Data\" in Data:\r\n responseText = Data[\"Data\"].decode(\"utf-8\", \"ignore\")\r\n else:\r\n responseText = \"\"\r\n logging.debug(\"onMessage: no data found in data\")\r\n return\r\n apiResponse = json.loads(responseText)\r\n apiUrl = apiResponse[\"components\"][\"api\"]\r\n apiData = apiResponse[\"data\"]\r\n except json.JSONDecodeError as err:\r\n msg, doc, pos = err.args\r\n logging.error(msg)\r\n Domoticz.Error(msg)\r\n apiResponse = None\r\n logging.debug(\"The faulty message: '\" + doc)\r\n\r\n if \"api/v2/Common/CrossLogin\" in apiUrl:\r\n logging.debug(\"message received: CrossLogin\")\r\n if apiData == 'Null':\r\n Domoticz.Log(\"SEMS API Token not received\")\r\n logging.info(\"SEMS API Token not received\")\r\n self.goodWeAccount.tokenAvailable = False\r\n self.httpConn.Disconnect()\r\n #self.httpConn = None\r\n else:\r\n logging.debug(\"message apiData: '\" + str(apiData) + \"'\")\r\n self.goodWeAccount.token = apiData\r\n logging.debug(\"SEMS API Token: \" + json.dumps(self.goodWeAccount.token))\r\n self.goodWeAccount.tokenAvailable = True\r\n #request list of stations on this account\r\n Connection.Send(self.goodWeAccount.stationListRequest())\r\n\r\n elif \"/api/v2/HistoryData/QueryPowerStationByHistory\" in apiUrl:\r\n logging.debug(\"message received: QueryPowerStationByHistory\")\r\n if apiData is None or len(apiData)==0:\r\n Domoticz.Log(\"Power station history not received\")\r\n logging.info(\"Power station history not received\")\r\n self.httpConn.Disconnect()\r\n #self.httpConn = None\r\n else:\r\n logging.debug(\"message apiData: '\" + str(apiData) + \"'\")\r\n for stations in apiData[\"list\"]:\r\n for data in stations:\r\n logging.debug(\"station element: '\"+ str(data) + \"', value: '\" + str(stations[data]) +\"'\")\r\n for key, station in enumerate(apiData[\"list\"]):\r\n if len(Parameters[\"Mode1\"]) <= 0 or (len(Parameters[\"Mode1\"]) > 0 and station[\"id\"] == Parameters[\"Mode1\"]):\r\n #add all found stations if no ID entered, else only log the one that matches the ID\r\n self.goodWeAccount.createStation(key, station)\r\n Domoticz.Log(\"Station found: \" + station[\"id\"])\r\n logging.info(\"Station found: \" + station[\"id\"])\r\n\r\n Connection.Send(self.goodWeAccount.stationDataRequest(self.baseDeviceIndex))\r\n\r\n elif \"api/v2/PowerStation/GetMonitorDetailByPowerstationId\" in apiUrl:\r\n logging.debug(\"message received: GetMonitorDetailByPowerstationId\")\r\n if apiData is None or len(apiData) == 0:\r\n Domoticz.Error(\"No station data received from GoodWe SEMS API (Station ID: \" + str(self.goodWeAccount.powerStationList[\r\n self.goodWeAccount.powerStationIndex]) + \")\")\r\n logging.error(\"No station data received from GoodWe SEMS API (Station ID: \" + str(self.goodWeAccount.powerStationList[\r\n self.goodWeAccount.powerStationIndex]) + \")\")\r\n self.goodWeAccount.tokenAvailable = False\r\n else:\r\n #logging.debug(\"message apiData: '\" + str(apiData) + \"'\")\r\n Domoticz.Log(\"Station data received from GoodWe SEMS API ('\" + str(self.goodWeAccount.powerStationList[\r\n self.goodWeAccount.powerStationIndex]) + \"', index : '\" + str(self.goodWeAccount.powerStationIndex)+ \"')\")\r\n logging.info(\"Station data received from GoodWe SEMS API ('\" + str(self.goodWeAccount.powerStationList[\r\n self.goodWeAccount.powerStationIndex]) + \"', index : '\" + str(self.goodWeAccount.powerStationIndex)+ \"')\")\r\n theStation = self.goodWeAccount.powerStationList[self.goodWeAccount.powerStationIndex]\r\n\r\n for inverter in apiData[\"inverter\"]:\r\n logging.debug(\"inverter found with SN: '\" + inverter[\"sn\"] + \"'\")\r\n if inverter[\"sn\"] in theStation.inverters:\r\n theStation.inverters[inverter[\"sn\"]].createDevices(Devices)\r\n logging.debug(\"Details d in inverter: '\" + str(inverter['d']) + \"'\")\r\n \r\n theInverter = theStation.inverters[inverter[\"sn\"]]\r\n\r\n if len(inverter['fault_message']) > 0:\r\n Domoticz.Log(\"Fault message from GoodWe inverter (SN: \" + inverter[\"sn\"] + \"): '\" + str(inverter['fault_message']) + \"'\")\r\n logging.info(\"Fault message from GoodWe inverter (SN: \" + inverter[\"sn\"] + \"): '\" + str(inverter['fault_message']) + \"'\")\r\n Domoticz.Log(\"Status of GoodWe inverter (SN: \" + inverter[\"sn\"] + \"): '\" + str(inverter[\"status\"]) + ' ' + self.goodWeAccount.INVERTER_STATE[inverter[\"status\"]] + \"'\")\r\n logging.info(\"Status of GoodWe inverter (SN: \" + inverter[\"sn\"] + \"): '\" + str(inverter[\"status\"]) + ' ' + self.goodWeAccount.INVERTER_STATE[inverter[\"status\"]] + \"'\")\r\n Devices[theInverter.inverterStateUnit].Update(nValue=inverter[\"status\"]+1, sValue=str((inverter[\"status\"]+2)*10))\r\n if self.goodWeAccount.INVERTER_STATE[inverter[\"status\"]] == 'generating':\r\n logging.debug(\"inverter generating, log temp\")\r\n UpdateDevice(theInverter.inverterTemperatureUnit, 0, str(inverter[\"tempperature\"]))\r\n UpdateDevice(theInverter.outputFreq1Unit, 0, str(inverter[\"d\"][\"fac1\"]))\r\n\r\n UpdateDevice(theInverter.outputCurrentUnit, 0, str(inverter[\"output_current\"]), AlwaysUpdate=True)\r\n UpdateDevice(theInverter.outputVoltageUnit, 0, str(inverter[\"output_voltage\"]), AlwaysUpdate=True)\r\n UpdateDevice(theInverter.outputPowerUnit, 0, str(inverter[\"output_power\"]) + \";\" + str(inverter[\"etotal\"] * 1000), AlwaysUpdate=True)\r\n inputVoltage,inputAmps = inverter[\"pv_input_1\"].split('/')\r\n inputPower = (float(inputVoltage[:-1])) * (float(inputAmps[:-1]))\r\n UpdateDevice(theInverter.inputVoltage1Unit, 0, inputVoltage, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputAmps1Unit, 0, inputAmps, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputPower1Unit, 0, str(inputPower) + \";0\", AlwaysUpdate=True)\r\n #test to log cumulative counting\r\n previousPower,currentCount = Devices[theInverter.inputPowerTest].sValue.split(\";\") \r\n newCounter = inputPower + float(currentCount) \r\n UpdateDevice(theInverter.inputPowerTest, 0, str(inputPower) + \";\" + str(newCounter), AlwaysUpdate=True)\r\n logging.debug(\"test previousPower, currentCount, newCounter = \" + str(previousPower) + \", \" + str(currentCount) + \", \" + str(newCounter))\r\n if \"pv_input_2\" in inverter:\r\n logging.debug(\"Second string found\")\r\n inputVoltage,inputAmps = inverter[\"pv_input_2\"].split('/')\r\n UpdateDevice(theInverter.inputVoltage2Unit, 0, inputVoltage, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputAmps2Unit, 0, inputAmps, AlwaysUpdate=True)\r\n inputPower = (float(inputVoltage[:-1])) * (float(inputAmps[:-1]))\r\n UpdateDevice(theInverter.inputPower2Unit, 0, str(inputPower) + \";0\", AlwaysUpdate=True)\r\n if \"pv_input_3\" in inverter:\r\n logging.debug(\"Third string found\")\r\n inputVoltage,inputAmps = inverter[\"pv_input_3\"].split('/')\r\n UpdateDevice(theInverter.inputVoltage3Unit, 0, inputVoltage, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputAmps3Unit, 0, inputAmps, AlwaysUpdate=True)\r\n inputPower = float(inputVoltage[:-1]) * float(inputAmps[:-1])\r\n UpdateDevice(theInverter.inputPower3Unit, 0, str(inputPower) + \";0\", AlwaysUpdate=True)\r\n if \"pv_input_4\" in inverter:\r\n logging.debug(\"Fourth string found\")\r\n inputVoltage,inputAmps = inverter[\"pv_input_4\"].split('/')\r\n UpdateDevice(theInverter.inputVoltage4Unit, 0, inputVoltage, AlwaysUpdate=True)\r\n UpdateDevice(theInverter.inputAmps4Unit, 0, inputAmps, AlwaysUpdate=True)\r\n inputPower = float(inputVoltage[:-1]) * float(inputAmps[:-1])\r\n UpdateDevice(theInverter.inputPower4Unit, 0, str(inputPower) + \";0\", AlwaysUpdate=True)\r\n else:\r\n Domoticz.Log(\"Unknown inverter found with S/N: '\" + inverter[\"sn\"] +\"'.\")\r\n logging.info(\"Unknown inverter found with S/N: '\" + inverter[\"sn\"] +\"'.\")\r\n\r\n if self.goodWeAccount.powerStationIndex == (len(self.goodWeAccount.powerStationList) - 1):\r\n logging.debug(\"Last station of list found\")\r\n if self.runAgain > 2:\r\n logging.info(\"Next active heartbeat far away, disconnecting and dropping connection.\")\r\n self.httpConn.Disconnect()\r\n\r\n self.devicesUpdated = True\r\n else:\r\n logging.debug(\"Retrieving next station data (ID: \" + self.goodWeAccount.powerStationList[self.baseDeviceIndex] + \")\")\r\n self.baseDeviceIndex += 1\r\n Connection.Send(self.goodWeAccount.stationDataRequest(self.baseDeviceIndex))\r\n\r\n elif status == 302:\r\n logging.error(\"GoodWe SEMS API returned a Page Moved Error.\")\r\n Domoticz.Error(\"GoodWe SEMS API returned a Page Moved Error.\")\r\n elif status == 400:\r\n logging.error(\"GoodWe SEMS API returned a Bad Request Error.\")\r\n Domoticz.Error(\"GoodWe SEMS API returned a Bad Request Error.\")\r\n elif (status == 500):\r\n logging.error(\"GoodWe SEMS API returned a Server Error.\")\r\n Domoticz.Error(\"GoodWe SEMS API returned a Server Error.\")\r\n else:\r\n logging.error(\"GoodWe SEMS API returned a status: \" + str(status))\r\n Domoticz.Error(\"GoodWe SEMS API returned a status: \" + str(status))\r\n\r\n def onCommand(self, Unit, Command, Level, Hue):\r\n logging.debug(\"onCommand called for Unit \" + str(Unit) + \": Parameter '\" + str(Command) + \"', Level: \" + str(Level))\r\n\r\n def onDisconnect(self, Connection):\r\n logging.debug(\"onDisconnect called for connection to: \" + Connection.Address + \":\" + Connection.Port)\r\n self.httpConn = None\r\n\r\n def onHeartbeat(self):\r\n if self.httpConn is not None and (self.httpConn.Connecting() or self.httpConn.Connected()) and not self.devicesUpdated:\r\n logging.debug(\"onHeartbeat called, Connection is alive.\")\r\n elif len(Parameters[\"Mode1\"]) == 0:\r\n Domoticz.Error(\"No Power Station ID provided, exiting\")\r\n logging.error(\"No Power Station ID provided, exiting\")\r\n return\r\n else:\r\n self.runAgain = self.runAgain - 1\r\n if self.runAgain <= 0:\r\n\r\n logging.debug(\"onHeartbeat called, starting device update.\")\r\n self.startDeviceUpdateV2()\r\n\r\n self.runAgain = int(Parameters[\"Mode2\"])\r\n else:\r\n logging.debug(\"onHeartbeat called, run again in \" + str(self.runAgain) + \" heartbeats.\")\r\n\r\nglobal _plugin\r\n_plugin = GoodWeSEMSPlugin()\r\n\r\ndef calculateNewEnergy(Unit, inputPower):\r\n try:\r\n #read power currently on display (comes from previous update) in Watt and energy counter uptill now in Wh\r\n previousPower,currentCount = Devices[Unit].sValue.split(\";\") \r\n except:\r\n #in case no values there, just assume zero\r\n previousPower = 0 #Watt\r\n currentCount = 0 #Wh\r\n dt_format = \"%Y-%m-%d %H:%M:%S\"\r\n dt_string = Devices[Unit].LastUpdate\r\n lastUpdateDT = datetime.fromtimestamp(time.mktime(time.strptime(dt_string, dt_format)))\r\n elapsedTime = datetime.now() - lastUpdateDT\r\n logging.debug(\"Test power, previousPower: {}, last update: {:%Y-%m-%d %H:%M}, elapsedTime: {}, elapsedSeconds: {:6.2f}\".format(previousPower, lastUpdateDT, elapsedTime, elapsedTime.total_seconds()))\r\n \r\n #average current and previous power (Watt) and multiply by elapsed time (hour) to get Watt hour\r\n previousPower = str(previousPower).replace(\"w\",\"\").replace(\"W\",\"\")\r\n newCount = round(((float(previousPower) + inputPower ) / 2) * elapsedTime.total_seconds()/3600,2)\r\n newCounter = newCount + float(currentCount) #add the amount of energy since last update to the already logged energy\r\n logging.debug(\"Test power, previousPower: {}, currentCount: {:6.2f}, newCounter: {:6.2f}, added: {:6.2f}\".format(previousPower, float(currentCount), newCounter, newCount))\r\n return newCounter\r\n\r\ndef UpdateDevice(Unit, nValue, sValue, BatteryLevel=255, AlwaysUpdate=False):\r\n if Unit not in Devices: return\r\n if Devices[Unit].nValue != nValue\\\r\n or Devices[Unit].sValue != sValue\\\r\n or Devices[Unit].BatteryLevel != BatteryLevel\\\r\n or AlwaysUpdate == True:\r\n\r\n Devices[Unit].Update(nValue, str(sValue), BatteryLevel=BatteryLevel)\r\n\r\n logging.debug(\"Update %s: nValue %s - sValue %s - BatteryLevel %s\" % (\r\n Devices[Unit].Name,\r\n nValue,\r\n sValue,\r\n BatteryLevel))\r\n\r\ndef onStart():\r\n global _plugin\r\n _plugin.onStart()\r\n\r\ndef onStop():\r\n global _plugin\r\n _plugin.onStop()\r\n\r\ndef onConnect(Connection, Status, Description):\r\n global _plugin\r\n _plugin.onConnect(Connection, Status, Description)\r\n\r\ndef onMessage(Connection, Data):\r\n global _plugin\r\n _plugin.onMessage(Connection, Data)\r\n\r\ndef onCommand(Unit, Command, Level, Hue):\r\n global _plugin\r\n _plugin.onCommand(Unit, Command, Level, Hue)\r\n\r\ndef onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):\r\n global _plugin\r\n _plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)\r\n\r\ndef onDisconnect(Connection):\r\n global _plugin\r\n _plugin.onDisconnect(Connection)\r\n\r\ndef onHeartbeat():\r\n global _plugin\r\n _plugin.onHeartbeat()\r\n\r\n# Generic helper functions\r\ndef LogMessage(Message):\r\n if Parameters[\"Mode6\"] == \"File\":\r\n f = open(Parameters[\"HomeFolder\"] + \"http.html\", \"w\")\r\n f.write(Message)\r\n f.close()\r\n Domoticz.Log(\"File written\")\r\n logging.info(\"File written\")\r\n\r\ndef DumpConfigToLog():\r\n Domoticz.Debug(\"Parameters count: \" + str(len(Parameters)))\r\n for x in Parameters:\r\n if Parameters[x] != \"\":\r\n Domoticz.Debug(\"Parameter: '\" + x + \"':'\" + str(Parameters[x]) + \"'\")\r\n Domoticz.Debug(\"Device count: \" + str(len(Devices)))\r\n for x in Devices:\r\n Domoticz.Debug(\"Device: \" + str(x) + \" - \" + str(Devices[x]))\r\n return\r\n\r\ndef DumpHTTPResponseToLog(httpDict):\r\n if isinstance(httpDict, dict):\r\n logging.debug(\"HTTP Details (\" + str(len(httpDict)) + \"):\")\r\n for x in httpDict:\r\n if isinstance(httpDict[x], dict):\r\n logging.debug(\"--->'\" + x + \" (\" + str(len(httpDict[x])) + \"):\")\r\n for y in httpDict[x]:\r\n logging.debug(\"------->'\" + y + \"':'\" + str(httpDict[x][y]) + \"'\")\r\n else:\r\n logging.debug(\"--->'\" + x + \"':'\" + str(httpDict[x]) + \"'\")\r\n","sub_path":"plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":31022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"359247115","text":"import random\n\nclass BaseFactory(object):\n \"\"\"Base Class for creating django objects \"\"\"\n\n # parameters to instantiate an object.\n # may be overridden by childcls's getparams() method\n default_params = dict(save_to_db=True, )\n last_obj_created = 'None'\n\n def getparams(cls):\n \"\"\"Template method: must be overridden by child class.\n Return dict of params that get sent to self.create()\n\n Example logic:\n\n pk = self.getUnusedPk() # optional\n username = 'markov_%s' % pk\n password = username\n\n return locals()\n \"\"\"\n raise NotImplementedError(\n 'You cannot directly instantiate BaseFactory '\n 'or call this method directly')\n\n def __init__(self, *args, **kwargs):\n \"\"\"Create new instance of a model by calling getparams in child class.\n Don't call directly. Don't instantiate BaseFactory directly.\n\n Any given params are passed to cls.getparams(*args, **kwargs)\"\"\"\n\n #add kwargs as class vars. This means getparams() can use\n # any kwargs passed in at time of instantiation. kwargs won't\n # get explicitly passed to django unless set in getparams()\n # (or by overriding __init__ in the child)\n self.__dict__ = kwargs\n\n # Get dict of params necessary to create object\n dict_ = self.default_params\n dict_.update(self.getparams())\n\n #override getparams args with those supplied at runtime\n dict_.update(**kwargs)\n\n # Check and prep dict_ as necessary\n try: del dict_['self'] # we don't want to pass this around\n except: pass\n\n # Create model object\n self.last_obj_created = self.create(**dict_)\n\n def __repr__(self):\n return \"%s: last_obj_created <%s>\" % (\n self.__class__.__name__, str(self.last_obj_created))\n\n def create(self, save_to_db=True, **kwargs):\n \"\"\"A wrapper that uses self.model to create an instance of\n self.model. Assumes this works: inst=model(**kwargs) and inst.save()\n\n In Django, this would wrap Django's\n model.objects.create(**kwargs) method.\"\"\"\n\n inst = self.model(**kwargs)\n if save_to_db:\n inst.save()\n return inst\n\nclass DjangoMixin(object):\n \"\"\"Useful/Necessary methods for Fixture Factories\"\"\"\n def _getmodel(self, model=None):\n if model == None:\n return self.model\n return model\n\n def getSome(self, percent, model=None):\n \"\"\"Return list of model objects with len equal to\n some percent the len of self.model.objects.all()\"\"\"\n model = self._getmodel(model)\n if isinstance(percent, int):\n percent = percent * .1\n percent = 1 - percent\n rv = [x for x in self.model.objects.all() if random.random() > percent]\n return rv\n\n def getPks(self, model=None):\n \"\"\"Get flattened list of primary keys\"\"\"\n model = self._getmodel(model)\n pks = model.objects.values_list('pk', flat=True)\n return pks\n\n def getUnusedPk(self, model=None):\n \"\"\"Get minimum possible unused primary key\"\"\"\n a = set(self.getPks(model)) or [1]\n b = set(range(min(a), max(a)+2))\n return min(b.difference(a))\n\n def getRandInst(self, model=None):\n \"\"\"Return randomly selected instance of possible models\"\"\"\n model = self._getmodel(model)\n pks = self.getPks(model)\n if not pks:\n raise IndexError('No primary keys for model: %s' % model)\n return model.objects.get(pk=random.choice(pks))\n\n #def newInstance(self, model=None):\n #\"\"\"\"return self.model.objects.get(pk=sorted(pks)[-1])\n\n\n","sub_path":"fixturefactory.py","file_name":"fixturefactory.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"356419246","text":"# Faça um Programa que verifique se uma letra digitada é vogal ou consoante.\n\nletra = input(\"Digite aqui uma letra: \")\nvogais = [\"A\",\"B\",\"E\",\"I\",\"O\",\"U\"]\nL = letra.upper()\n\nif L in vogais:\n print(\"A letra é uma vogal\")\nelif L not in vogais:\n print(\"É uma consoante\")\nelse:\n print(\"Comando invalido\")\n\n","sub_path":"Py_teste/022_exercicio.py","file_name":"022_exercicio.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"235239600","text":"from __future__ import print_function\n\nimport os\nimport re\nfrom datetime import datetime\nfrom functools import wraps\nimport difflib\nimport textwrap\n\nimport six\n\nimport numpy as np\nimport pandas as pd\nimport click\n\nfrom .containers import FASTA_FMT\n\nend = '...'\n\ndef print_msg(*msg):\n def deco(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n if six.PY3:\n print(datetime.now(), ':', *msg, end=end, flush=True)\n elif six.PY2:\n print(datetime.now(), ':', *msg, end=end)\n result = func(*args, **kwargs)\n print('done.')\n return result\n return wrapper\n return deco\n\n# heavily inspired and borrowed\n# by https://github.com/jorvis/biocode/blob/master/lib/biocode/utils.py#L149\n# Joshua Orvis\n\n\ndef _fasta_dict_from_file(file_object, header_search='specific'):\n \"\"\"\n Reads a file of FASTA entries and returns a dict for each entry.\n It parsers the headers such that `>gi|12345|ref|NP_XXXXX| Description`\n returns as `{gi: 12345, ref: 'NP_XXXXX', description : 'Description'}`\n The sequence has all whitespace removed.\n\n :header_search: One of `specific` or `generic`\n if `specific` tries to parse the header\n if `general` just returns each whitespace separated header\n \"\"\"\n\n current_id = dict()\n current_seq = ''\n current_header = None\n pat = re.compile('>(\\S+)\\s*(.*)')\n header_pat = re.compile(r'(\\w+)\\|(\\w+\\.?\\w*)?')\n\n def parse_header(header, pairs=True):\n keys = header_pat.findall(header)\n header_data = dict()\n for key in keys:\n header_data[key[0]] = key[1]\n # gi -> ProteinGI #, ref -> NP_XXXX\n return header_data\n\n for line in file_object:\n line = line.rstrip()\n m = pat.search(line)\n if m:\n ## new residue line matched, purge the existing one, if not the first\n if current_id:\n ## remove all whitespace and save\n current_seq = ''.join(current_seq.split())\n current_id['sequence'] = current_seq\n yield current_id\n # current_id.clear() # this is actually bad for list comprehensions\n # as it returns empty dictionaries\n\n current_seq = ''\n header = m.group(1)\n if header_search == 'specific':\n current_id = parse_header(header)\n elif header_search == 'generic':\n current_id = dict(header = header)\n current_id['description'] = m.group(2)\n\n else:\n ## python 2.6+ makes string concatenation amortized O(n)\n ## http://stackoverflow.com/a/4435752/1368079\n current_seq += str(line)\n\n ## don't forget the last one\n current_seq = ''.join(current_seq.split())\n current_id['sequence'] = current_seq\n yield current_id\n\ndef fasta_dict_from_file(fasta_file, header_search='specific'):\n with open(fasta_file, 'r') as f:\n # yield from _fasta_dict_from_file(f, header_search=header_search)\n for v in _fasta_dict_from_file(f, header_search=header_search):\n yield v\nfasta_dict_from_file.__doc__ = _fasta_dict_from_file.__doc__\n\ndef convert_tab_to_fasta(tabfile, geneid=None, ref=None, gi=None, homologene=None, taxon=None,\n description=None, sequence=None, symbol=None):\n HEADERS = {'geneid': geneid, 'ref': ref, 'gi': gi, 'homologene': homologene, 'taxon': taxon,\n 'description': description, 'sequence': sequence, 'symbol': symbol}\n CUTOFF = .35\n df = pd.read_table(tabfile, dtype=str)\n choices = click.Choice([x for y in [df.columns, ['SKIP']] for x in y])\n col_names = dict()\n for h,v in HEADERS.items():\n if v is not None or v=='SKIP':\n col_names[h] = v\n continue\n\n closest_match = difflib.get_close_matches(h, df.columns, n=1, cutoff=CUTOFF)\n if closest_match and h != 'homologene':\n col_names[h] = closest_match[0]\n else:\n print(\"Can not find header match for :\", h)\n print(\"Choose from :\", ' '.join(choices.choices))\n choice = click.prompt(\"Selected the correct name or SKIP\",\n type=choices, show_default=True, err=True,\n default='SKIP')\n col_names[h] = choice\n print()\n for _, series in df.iterrows():\n row = series.to_dict()\n gid = row.get( col_names['geneid'], '')\n ref = row.get( col_names['ref'], '')\n hid = row.get( col_names['homologene'], '')\n gi = row.get( col_names['gi'], '')\n taxon = row.get( col_names['taxon'], '')\n desc = row.get( col_names['description'], ' ')\n seq = '\\n'.join(textwrap.wrap(row.get( col_names['sequence'], '' ), width=70))\n symbol = row.get( col_names['symbol'], '' )\n\n hid = int(hid) if hid and not np.isnan(hid) else ''\n try:\n gid = int(gid)\n except ValueError:\n pass\n\n r = dict(gid=gid, ref=ref, taxons=taxon, gis=gi, homologene=hid, description=desc, seq=seq, symbols=symbol)\n yield(FASTA_FMT.format(**r))\n\n\ndef sniff_fasta(fasta):\n nrecs = 1\n fasta = fasta_dict_from_file(fasta)\n counter = 0\n REQUIRED = ('ref', 'sequence')\n while counter < nrecs:\n for rec in fasta:\n if any(x not in rec for x in REQUIRED):\n raise ValueError('Invalid input FASTA')\n counter += 1\n return 0 # all good\n","sub_path":"RefProtDB/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"633586912","text":"from numpy import get_include as np_get_include\nfrom distutils.core import setup,Extension\nfrom Cython.Build import cythonize\n\nextGameClass = Extension(name=\"gameClassOffline\", sources=[\"gameClassOffline.py\"],\n include_dirs=[np_get_include()]\n )\n\nextClient = Extension(name=\"client\", sources=[\"client.py\"],\n include_dirs=[np_get_include()]\n )\n\nextServer = Extension(name=\"server\", sources=[\"server.py\"],\n include_dirs=[np_get_include()]\n )\n\nsetup(ext_modules=cythonize(extGameClass))\nsetup(ext_modules=cythonize(extClient))\nsetup(ext_modules=cythonize(extServer))","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"376614729","text":"\"\"\"Lexer definition for input databases\n\nJanuary 2017, C.J. Voesenek\n\"\"\"\n\nimport ply.lex as lex\n\n__author__ = \"C.J. Voesenek\"\n__maintainer__ = \"C.J. Voesenek\"\n__email__ = \"cees.voesenek@wur.nl\"\n\ntokens = (\"BOOLEAN\",\n \"VARIABLE\",\n \"STRING\",\n \"COMMENT\",\n \"EQUALS\",\n \"MINUS\",\n \"PLUS\",\n \"TIMES\",\n \"DIVIDE\",\n \"POWER\",\n \"COMMA\",\n \"COLON\",\n \"OPEN_PARENTHESIS\",\n \"CLOSE_PARENTHESIS\",\n \"OPEN_BRACKET\",\n \"CLOSE_BRACKET\",\n \"OPEN_CURLY_BRACKET\",\n \"CLOSE_CURLY_BRACKET\",\n \"INTEGER\",\n \"FLOAT\")\n\nt_ignore = \" \\t\\r\\n\"\nt_COMMENT = r\"//.*\"\nt_EQUALS = r\"=\"\nt_MINUS = r\"-\"\nt_PLUS = r\"\\+\"\nt_TIMES = r\"\\*\"\nt_DIVIDE = r\"/\"\nt_POWER = r\"\\^\"\nt_COMMA = r\",\"\nt_COLON = r\":\"\nt_OPEN_PARENTHESIS = r\"\\(\"\nt_CLOSE_PARENTHESIS = r\"\\)\"\nt_OPEN_BRACKET = r\"\\[\"\nt_CLOSE_BRACKET = r\"\\]\"\nt_OPEN_CURLY_BRACKET = r\"\\{\"\nt_CLOSE_CURLY_BRACKET = r\"\\}\"\n\n# We add BOOLEAN, VARIABLE, and STRING as functions to ensure their order is\n# correct - we need BOOLEAN to be first, since it will be parsed as a\n# VARIABLE otherwise.\ndef t_BOOLEAN(t):\n r\"(?(\\d+)?)\\.(?(leading)\\d*|\\d+)(e(-)?\\d+)?\" \\\n r\"|\" \\\n r\"[-+]?\\d+e(-)?\\d+\" \\\n r\")\"\n t.value = float(t.value)\n return t\n\n\ndef t_error(t):\n raise TypeError(\"Invalid string: {}\".format(t.value))\n\n\nlexer = lex.lex()\n","sub_path":"Vpp3_FlowVisualization/Package/parser/newlexer.py","file_name":"newlexer.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"429123396","text":"\"\"\"\nScript to serialise images into example protos in TF Record files.\n\nINSTRUCTIONS:\nModify the following variables to adjust the script to the data\n\nDATA_DIRECTORY: Indicates where the iamges are stored.\n\nLABELS: Indicates the names of the variables. The names should match the\nnames of the directories where the images are divided. Example:\n DATA_DIRECTORY\n |-LABEL 1\n |-LABEL 2\n |-...\n |-LABEL n\n\nTRAINING_PROPORTION indicates the percentage of images to use for training,\nthe rest will be used for validation.\n\nTRAINING_TFRECORD_NAME and VALIDATION_TFRECORD_NAME indicate the name of the\ngenerated TFRecord files.\n\nLast tested with Tensorflow 2.0 Beta.\n\"\"\"\n\n# Imports\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\nimport numpy as np\nimport random\n\nimport ilqi_tfrecords\n\n# Configuration constants\nDATA_DIRECTORY = './images_v2'\nLABELS = ['gaps', 'offset', 'overlaps', 'qok']\nTRAINING_PROPORTION = 0.8\nTRAINING_TFRECORD_NAME = './data/training_dataset.tfrecord'\nVALIDATION_TFRECORD_NAME = './data/validation_dataset.tfrecord'\n\n# Utility functions\ndef find_file_names(search_directory):\n \"\"\"Build a list of all images files and labels in the data set.\n Args:\n search_directory[string]: Path to the root directory of images.\n Returns:\n filenames[string list]: Each string is a path to an image file.\n \"\"\"\n # Placeholders for the list and the label directories\n label_directories = []\n absolute_filenames = []\n labels = []\n label_index = 0\n\n # Save label directories in an array\n for label in LABELS:\n path_string = '%s/%s/*' % (DATA_DIRECTORY, label)\n label_directories.append(path_string)\n \n # Make a list of the filenames available accross all labels\n for label_directory in label_directories:\n # This throws an error if the directories are not found,\n # so check that the labels are correctly written \n matching_files = tf.io.gfile.glob(label_directory)\n absolute_filenames += matching_files\n labels.extend([label_index] * len(matching_files))\n label_index += 1\n \n # Return list\n return absolute_filenames, labels\n\ndef shuffle_and_split(filenames, labels):\n \"\"\"\n Takes a list of filenames and a list of correspoding labels and shuffles them.\n The function then shuffles the lists, without losing the image-label relation,\n and splits the data, leaving TRAINING_PROPORTION % as training data and the rest\n as validation data.\n Args:\n filenames: List of filenames\n labels: List of corresponding labels\n Returns:\n training_filenames: List of shuffled samples for training\n training_labels: List of shuffled labels for training\n validation_filenames: List of shuffled samples for validation\n validation_labels: List of shuffled labels for validation\n \"\"\"\n # Create a list of indices to be able to shuffle both\n # labels and file names\n indices = list(range(len(filenames)))\n\n # Shuffle indices. This function shuffles lists in place,\n # so there's no need to reassign.\n random.shuffle(indices)\n\n # Calculate split indices\n section = int(TRAINING_PROPORTION*len(filenames))\n training_indices = indices[:section]\n validation_indices = indices[section:]\n\n # Split datasets\n training_filenames = [filenames[i] for i in training_indices]\n training_labels = [labels[i] for i in training_indices]\n validation_filenames = [filenames[i] for i in validation_indices]\n validation_labels = [labels[i] for i in validation_indices]\n\n # Return datasets and labels\n return training_filenames, training_labels, validation_filenames, validation_labels\n\ndef write_tfrecord(tfrecord_file, filenames, labels):\n \"\"\"\n Takes a list of filenames and a list of corresponding labels. It reads\n the files and stores them, together with their labels, into a TF Record\n file.\n Args:\n tfrecord_file: Name of the TFRecord file\n filenames: List of filenames with the images\n labels: List of corresponding labels \n \"\"\"\n with tf.io.TFRecordWriter(tfrecord_file) as writer:\n # Iterate through all datasets' filenames\n for i in range (len(filenames)):\n # Read images and standardise format to jpeg\n encoded_image = tf.io.read_file(filenames[i])\n decoded_image = tf.io.decode_image(encoded_image)\n\n # Convert to example\n example = ilqi_tfrecords.image_to_example(decoded_image, labels[i])\n\n # Write TFRecords\n writer.write(example.SerializeToString())\n\n # Return success\n return 0\n\n# Main function\ndef run():\n \"\"\"\n Executes the file finding, shuffle, splitting and TF Record writing.\n \"\"\"\n # Find pictures files\n picture_files, picture_labels = find_file_names(DATA_DIRECTORY)\n\n # Shuffle file names and split into training and validation\n training_filenames, training_labels, validation_filenames, validation_labels = shuffle_and_split(picture_files, picture_labels)\n\n # Write files, 1 for training and one for validation\n write_tfrecord(TRAINING_TFRECORD_NAME, training_filenames, training_labels)\n write_tfrecord(VALIDATION_TFRECORD_NAME, validation_filenames, validation_labels)\n\n # Return success\n return 0\n\n\n# Main name\nif __name__ == \"__main__\":\n tf.enable_eager_execution()\n run()\n\n","sub_path":"quality_inspector2/python/build_tfrecords.py","file_name":"build_tfrecords.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"430675481","text":"from docxtpl import DocxTemplate, InlineImage, RichText\nfrom docx.shared import Mm, Inches, Pt\nimport jinja2\nfrom webapp.models import *\nfrom baoming.settings import MEDIA_URL, MEDIA_ROOT, BASE_DIR\nimport datetime\nimport os\nimport time\nfrom webapp.controller.common import *\nimport platform\n\n\ndef apply_chemical(student):\n \"\"\"\n 非化工类的申请表下载专用\n :param student:\n :return:\n \"\"\"\n try:\n user_info = student.user_info\n document_root = os.path.join(BASE_DIR, 'document')\n tpl = DocxTemplate(document_root + '/fujian03.docx')\n # system_type = platform.system()\n # if 'indows' in system_type:\n # tpl = DocxTemplate('D:/PycharmProjects/lelingzdy/baoming/webapp/utils/fujian03.docx')\n # else:\n # tpl = DocxTemplate('/opt/python3_space/lelingzdy/baoming/webapp/utils/fujian03.docx')\n print(user_info.hukou_province.region_name)\n file_root = MEDIA_ROOT + '/' + str(user_info.two_inch_photo.picture_path)\n file_root = file_root.replace(\"\\\\\", \"/\")\n id_number = str(user_info.id_number)\n rt_aa = RichText('')\n rt_aa.add(id_number[0], size=14) # 字体大小\n rt_bb = RichText('')\n rt_bb.add(id_number[1], size=14) # 字体大小\n rt_cc = RichText('')\n rt_cc.add(id_number[2], size=14) # 字体大小\n rt_dd = RichText('')\n rt_dd.add(id_number[3], size=14) # 字体大小\n rt_ee = RichText('')\n rt_ee.add(id_number[4], size=14) # 字体大小\n rt_ff = RichText('')\n rt_ff.add(id_number[5], size=14) # 字体大小\n rt_gg = RichText('')\n rt_gg.add(id_number[6], size=14) # 字体大小\n rt_hh = RichText('')\n rt_hh.add(id_number[7], size=14) # 字体大小\n rt_ii = RichText('')\n rt_ii.add(id_number[8], size=14) # 字体大小\n rt_jj = RichText('')\n rt_jj.add(id_number[9], size=14) # 字体大小\n rt_kk = RichText('')\n rt_kk.add(id_number[10], size=14) # 字体大小\n rt_ll = RichText('')\n rt_ll.add(id_number[11], size=14) # 字体大小\n rt_mm = RichText('')\n rt_mm.add(id_number[12], size=14) # 字体大小\n rt_nn = RichText('')\n rt_nn.add(id_number[13], size=14) # 字体大小\n rt_oo = RichText('')\n rt_oo.add(id_number[14], size=14) # 字体大小\n rt_pp = RichText('')\n rt_pp.add(id_number[15], size=14) # 字体大小\n rt_qq = RichText('')\n rt_qq.add(id_number[16], size=14) # 字体大小\n rt_rr = RichText('')\n rt_rr.add(id_number[17], size=14) # 字体大小\n\n # 户口所在地\n rt_hukou = RichText('')\n hukou = user_info.hukou_province.region_name + user_info.hukou_city.region_name + user_info.hukou_county.region_name\n if str(hukou).__len__() > 8:\n rt_hukou.add(hukou, size=10) # 字体大小\n elif str(hukou).__len__() > 13:\n rt_hukou.add(hukou, size=8) # 字体大小\n else:\n rt_hukou.add(hukou, size=14) # 字体大小\n\n # 身份证住址\n rt_id_addr = RichText('')\n id_card_address = user_info.id_card_address\n if str(id_card_address).__len__() > 8:\n rt_id_addr.add(id_card_address, size=10) # 字体大小\n elif str(id_card_address).__len__() > 13:\n rt_id_addr.add(id_card_address, size=8) # 字体大小\n elif str(id_card_address).__len__() > 16:\n rt_id_addr.add(id_card_address, size=6) # 字体大小\n else:\n rt_id_addr.add(id_card_address, size=14) # 字体大小\n\n # 政治面貌\n rt_p_status = RichText('')\n political_status_value = political_status[str(user_info.political_status)]\n # rt_p_status.add(political_status_value, size=12) # 字体大小\n if str(political_status_value).__len__() >= 4:\n rt_p_status.add(political_status_value, size=14) # 字体大小\n else:\n rt_p_status.add(political_status_value) # 字体大小\n\n # 原职业工种\n rt_former_occupation = RichText('')\n former_occupation = student.former_occupation\n if str(former_occupation).__len__() >= 4:\n rt_former_occupation.add(former_occupation, size=14) # 字体大小\n else:\n rt_former_occupation.add(former_occupation) # 字体大小\n # 申报职业\n rt_declaration_of_occupation = RichText('')\n declaration_of_occupation = student.declaration_of_occupation\n if str(declaration_of_occupation).__len__() >= 4:\n rt_declaration_of_occupation.add(declaration_of_occupation, size=14) # 字体大小\n else:\n rt_declaration_of_occupation.add(declaration_of_occupation) # 字体大小\n\n # 原级别\n primary_level = str(student.primary_level)\n if len(student.primary_level) > 0:\n primary_level = worker_level[str(student.primary_level)]\n else:\n primary_level = ''\n\n # 申报级别\n identification_level = str(student.identification_level)\n if len(identification_level) > 0:\n identification_level = worker_level[str(student.identification_level)]\n else:\n identification_level = ''\n # 原证书编号\n original_certificate_number = student.original_certificate_number\n if original_certificate_number:\n pass\n else:\n original_certificate_number = \"\"\n\n if student.issuance_time:\n issuance_time = student.issuance_time\n else:\n issuance_time = ''\n\n career_life = student.career_life\n original_certificate_worker_year = student.original_certificate_worker_year\n apprentice_year = student.apprentice_year\n apprentice_month = student.apprentice_month\n\n flag_working_time = False\n if student.identification_level == \"3\":\n working_year = ''\n elif student.identification_level == \"4\":\n if original_certificate_worker_year:\n if original_certificate_worker_year > 0:\n working_year = ''\n else:\n flag_working_time = True\n else:\n flag_working_time = True\n else:\n flag_working_time = True\n\n if flag_working_time:\n if not career_life:\n if apprentice_year:\n if apprentice_year > 0:\n working_year = str(apprentice_year)\n else:\n if apprentice_month:\n if apprentice_month > 0:\n working_year = str(apprentice_month) + \"月\"\n else:\n working_year = ''\n else:\n working_year = ''\n else:\n working_year = career_life\n else:\n pass\n\n # if not career_life:\n # if original_certificate_worker_year:\n # working_year = original_certificate_worker_year\n # else:\n # if apprentice_year > 0:\n # working_year = str(apprentice_year)\n # else:\n # if apprentice_month > 0:\n # working_year = str(apprentice_month) + \"月\"\n # else:\n # working_year = ''\n # else:\n # working_year = career_life\n #\n # if student.identification_level == \"3\":\n # working_year = ''\n #\n # if student.identification_level == \"4\":\n # if original_certificate_worker_year > 0:\n # working_year = ''\n #\n # if working_year is None:\n # working_year = ''\n\n # 文化程度\n education_degree = student.user_info.education_degree\n if education_degree:\n education_name = student.user_info.education_degree.education_name\n else:\n education_name = ''\n context = {\n 'r_e': user_info.real_name,\n 'sa': get_sex(user_info.sex),\n 'bir': user_info.birthday,\n 'edu': education_name,\n 'id_number': user_info.id_number,\n 'work_unit': user_info.work_unit,\n 'u_n': user_info.unit_nature.unit_nature,\n 's_w_d': user_info.start_working_date,\n 'cl': working_year,\n 'hukou': rt_hukou,\n 'email': user_info.email,\n 'f_p': user_info.fixed_telephone,\n 'unit_address': user_info.unit_address,\n 'address': user_info.address,\n 'id_addr': rt_id_addr,\n 'postal_c': user_info.postal_code,\n # 'p': rt_p_status,\n 'nati': user_info.nation_info.nation_name,\n 'f_occ': rt_former_occupation,\n 'p_level': primary_level,\n 'issuance_time': issuance_time,\n 'issue_unit': student.issue_unit,\n 'o_cer_num': original_certificate_number,\n 'dec_of_occ': rt_declaration_of_occupation,\n 'id_level': identification_level,\n 'work_training': student.work_training,\n 'inch_img': InlineImage(tpl, file_root, width=Mm(35), height=Mm(48)),\n 'major': student.major,\n 'a': rt_aa,\n 'b': rt_bb,\n 'c': rt_cc,\n 'd': rt_dd,\n 'e': rt_ee,\n 'f': rt_ff,\n 'g': rt_gg,\n 'h': rt_hh,\n 'i': rt_ii,\n 'j': rt_jj,\n 'k': rt_kk,\n 'l': rt_ll,\n 'm': rt_mm,\n 'n': rt_nn,\n 'o': rt_oo,\n 'p': rt_pp,\n 'q': rt_qq,\n 'r': rt_rr\n }\n day_string = str(time.strftime('%Y/%m/%d', time.localtime(time.time())))\n file_root = MEDIA_ROOT + \"/files/\"\n day_files_path = file_root + 'report_files/apply_chemical/' + student.declaration_of_occupation + \"/\" + str(\n student.identification_level) + \"/\" + day_string\n if os.path.exists(day_files_path):\n pass\n else:\n os.makedirs(day_files_path)\n uuid_string = str(uuid.uuid4())\n file_day_files_path = day_files_path + \"/\" + uuid_string + \".docx\"\n jinja_env = jinja2.Environment(autoescape=True)\n tpl.render(context, jinja_env)\n tpl.save(file_day_files_path)\n if os.path.exists(file_day_files_path):\n file_manage = FileManage()\n file_manage.file_name = \"化工报表-\" + declaration_of_occupation\n file_manage.file_uuid = uuid_string\n file_manage.file_path = file_day_files_path\n file_manage.save()\n # 附件1 申请表获取成功,\n\n return str(file_manage.file_uuid)\n else:\n return None\n except Exception as e:\n print(e)\n raise e\n # return None\n\n\ndef get_sex(value):\n \"\"\"\n 性别过滤器\n :param value:\n :return:\n \"\"\"\n return_value = ''\n if value == 'MALE':\n return_value = '男'\n if value == 'FEMALE':\n return_value = '女'\n if value == 'OTHER':\n return_value = '未填写'\n return return_value\n","sub_path":"baoming/webapp/utils/apply_chemical.py","file_name":"apply_chemical.py","file_ext":"py","file_size_in_byte":11328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"512085914","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 15 11:26:00 2017\n\n@author: 凯风\n\"\"\"\n\n'''\n 插值排序:\n 说明:\n 假定第一个元素被排序了~反正只有一个\n 加入第二个元素与第一个元素比较,插入到相应的位置\n 加入第三个元素,与前两个比较,插入相应的位置\n ……\n 复杂度:O(n^2)\n'''\n\ndef insertionSort(alist):\n for index in range(1,len(alist)):\n \n currentvalue = alist[index]\n position = index\n while position > 0 and alist[position-1] > currentvalue:\n alist[position] = alist[position-1]\n position = position - 1\n \n alist[position] = currentvalue\n\nalist = [54,26,93,17,77,31,44,55,20]\ninsertionSort(alist)\nprint(alist) ","sub_path":"DataStructures_Algorithms_Python/Sort/insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"231915138","text":"# -*- coding: utf-8 -*-\n\n# Задание 1: простейший parser/dumper\nfrom collections import Counter, defaultdict\n\n\ndef get_dicts_from_json(path_to_json_file):\n with open(path_to_json_file, 'r') as json_file:\n json_string = json_file.read()[3:-3]\n objects = json_string.split('}, {\"')\n objects = [obj.split(', \"') for obj in objects]\n\n def pairs(d):\n key = d.split('\": ')[0]\n value = d.split('\": ')[1].strip('\"').replace(\", '\", \",'\")\n return (key, value)\n objects = [dict(pairs(pair) for pair in obj) for obj in objects]\n return objects\n\n\ndef dump_to_json(list_of_dicts, dump_file_name):\n with open(dump_file_name, 'w') as json_file:\n replaces = [(\"{'\", '{\"'), (\"'}\", '\"}'), (\"': '\", '\": \"')]\n replaces += [(\"', '\", '\", \"'), ('\\', \"', '\", \"'), ('\", \\'', '\", \"')]\n replaces += [(\", '\", ', \"'), (\"': \", '\": '), (\"['\", '[\"')]\n replaces += [(\"']\", '\"]'), (\"\\\\'\", \"'\"), (\",'\", \", '\")]\n replaces += [('\\\\\\\\', '\\\\'), (\"'null'\", \"null\")]\n str_to_write = str(list_of_dicts)\n for r in replaces:\n str_to_write = str_to_write.replace(*r)\n json_file.write(f'{str_to_write}')\n\n\n# Задание 2: объединение файлов, удаление дубликатов, сортировка\n\n\ndef get_unique_dicts(list_of_dicts):\n list_of_dict_items = [tuple(d.items()) for d in list_of_dicts]\n list_of_unique_dicts = [dict(s) for s in set(list_of_dict_items)]\n return list_of_unique_dicts\n\n\ndef sort_list_of_dicts(list_of_dicts):\n\n def key_to_sort(dict_elem):\n if dict_elem['price'] == 'null':\n return (1, dict_elem['variety'].lower())\n else:\n return (-int(dict_elem['price']), dict_elem['variety'].lower())\n sorted_list = sorted(list_of_dicts, key=key_to_sort)\n return sorted_list\n\n\n# Задание 3: сбор ст��тистики\n\n\ndef varieties_statistic(winedata):\n varieties = ['Gew\\\\u00fcrztraminer', 'Riesling']\n varieties += ['Merlot', 'Madera', 'Tempranillo', 'Red Blend']\n stats = ['average_price', 'min_price', 'max_price']\n stats += ['region', 'country', 'average_score']\n var_stat = {v: {s: 0 for s in stats} for v in varieties}\n for var in var_stat:\n var_stat[var]['min_price'] = float('inf')\n var_stat[var]['region'] = Counter()\n var_stat[var]['country'] = Counter()\n var_stat[var]['sum_price'] = 0\n var_stat[var]['sum_price_cnt'] = 0\n var_stat[var]['sum_score'] = 0\n var_stat[var]['sum_score_cnt'] = 0\n\n for variety in varieties:\n price = []\n for wine in winedata:\n if wine['price'] != 'null' and wine['variety'] == variety:\n price.append(int(wine['price']))\n if len(price):\n min_price, max_price = min(price), max(price)\n avg_price = round(sum(price) / len(price), 2)\n else:\n min_price, max_price, avg_price = 0, 0, 0\n var_stat[variety]['min_price'] = min_price\n var_stat[variety]['max_price'] = max_price\n var_stat[variety]['average_price'] = avg_price\n score = []\n for wine in winedata:\n if wine['points'] != 'null' and wine['variety'] == variety:\n score.append(int(wine['points']))\n if len(score):\n avg_score = round(sum(score) / len(score), 2)\n else:\n avg_score = 0\n var_stat[variety]['average_score'] = avg_score\n\n for wine in winedata:\n variety = wine['variety']\n if variety in varieties:\n if wine['region_1'] != 'null':\n var_stat[variety]['region'] += Counter([wine['region_1']])\n if wine['country'] != 'null':\n var_stat[variety]['country'] += Counter([wine['country']])\n for var in var_stat:\n if var_stat[var]['region']:\n var_stat[var]['region'] = var_stat[var]['region'].most_common(1)\n var_stat[var]['region'] = var_stat[var]['region'][0][0]\n else:\n var_stat[var]['region'] = 'null'\n if var_stat[var]['country']:\n var_stat[var]['country'] = var_stat[var]['country'].most_common(1)\n var_stat[var]['country'] = var_stat[var]['country'][0][0]\n else:\n var_stat[var]['country'] = 'null'\n var_stat_dict_keys = var_stat[var].keys()\n for wine_param in set(var_stat_dict_keys) - set(stats):\n del var_stat[var][wine_param]\n return var_stat\n\n\ndef common_statistic(winedata):\n price_list = set(int(w['price']) for w in winedata if w['price'] != 'null')\n max_price, min_price = max(price_list), min(price_list)\n most_expensive_wine = []\n for wine in winedata:\n if wine['price'] != 'null' and int(wine['price']) == max_price:\n most_expensive_wine.append(wine['title'])\n cheapest_wine = []\n for wine in winedata:\n if wine['price'] != 'null' and int(wine['price']) == min_price:\n cheapest_wine.append(wine['title'])\n score = set(int(w['points']) for w in winedata if w['points'] != 'null')\n max_score, min_score = max(score), min(score)\n counter, price = defaultdict(int), defaultdict(int)\n for wine in winedata:\n if wine['price'] != 'null' and wine['country'] != 'null':\n counter[wine['country']] += 1\n price[wine['country']] += int(wine['price'])\n avg_price_list = [(price[p] / counter[p], p) for p in price]\n max_avg_price = max(avg_price_list, key=lambda x: x[0])[1]\n min_avg_price = min(avg_price_list, key=lambda x: x[0])[1]\n counter, score = defaultdict(int), defaultdict(int)\n for wine in winedata:\n if wine['points'] != 'null' and wine['country'] != 'null':\n counter[wine['country']] += 1\n score[wine['country']] += int(wine['points'])\n avg_score_list = [(score[s] / counter[s], s) for s in score]\n max_avg_score = max(avg_score_list, key=lambda x: x[0])[1]\n min_avg_score = min(avg_score_list, key=lambda x: x[0])[1]\n tasters = Counter()\n for wine in winedata:\n if wine['taster_name'] != 'null':\n tasters += Counter([wine['taster_name']])\n most_active_commentator = tasters.most_common(1)[0][0]\n common_stat = {'most_expensive_wine': most_expensive_wine}\n common_stat['cheapest_wine'] = cheapest_wine\n common_stat['highest_score'] = max_score\n common_stat['lowest_score'] = min_score\n common_stat['most_expensive_coutry'] = max_avg_price\n common_stat['cheapest_coutry'] = min_avg_price\n common_stat['most_rated_country'] = max_avg_score\n common_stat['underrated_country'] = min_avg_score\n common_stat['most_active_commentator'] = most_active_commentator\n return common_stat\n\n\n# Задание 4: markdown\n\ndef dump_stat_to_markdown(stat, markdown_file_name):\n with open(markdown_file_name, 'w', encoding='utf-8') as md_file:\n md_file.write('# Statistic\\n\\n')\n md_file.write('## Certain wines\\n')\n wine_stat = stat['statistic']['wine']\n wine_params = list(wine_stat['Merlot'].keys())\n table_head = f\"| |{'|'.join(wine_params)}|\"\n table_head = table_head.replace('_', ' ').title()\n delimiter = '-|'*(len(wine_params) + 1)\n md_file.write(f'{table_head}\\n')\n md_file.write(f'{delimiter}\\n')\n for wine in wine_stat:\n row = f'|**{wine}**|'.encode().decode('unicode-escape')\n for params in wine_params:\n if wine_stat[wine][params] == 'null':\n parameter_value = ' '\n else:\n parameter_value = wine_stat[wine][params]\n row += f'{parameter_value}|'.encode().decode('unicode-escape')\n md_file.write(f'{row}\\n')\n md_file.write('\\n## Whole wines\\n')\n md_file.write('* Most expensive wine:\\n')\n for wine in stat['statistic']['most_expensive_wine']:\n unicode_escape_wine = wine.encode().decode('unicode-escape')\n md_file.write(f'\\t* _{unicode_escape_wine}_\\n')\n md_file.write('* Cheapest wine:\\n')\n for wine in stat['statistic']['cheapest_wine']:\n unicode_escape_wine = wine.encode().decode('unicode-escape')\n md_file.write(f'\\t* _{unicode_escape_wine}_\\n')\n for s in stat['statistic']:\n if s not in ('wine', 'most_expensive_wine', 'cheapest_wine'):\n line = f\"* {s.replace('_', ' ').capitalize()}: \"\n unicode_escape_stat = stat['statistic'][s]\n line += f\"_{unicode_escape_stat}_\\n\"\n md_file.write(line)\n\n\nif __name__ == '__main__':\n winedata_1 = get_dicts_from_json('winedata_1.json')\n winedata_2 = get_dicts_from_json('winedata_2.json')\n winedata_full = get_unique_dicts(winedata_1 + winedata_2)\n winedata_full = sort_list_of_dicts(winedata_full)\n dump_to_json(winedata_full, 'winedata_full.json')\n variety_statistic = varieties_statistic(winedata_full)\n common_statistic = common_statistic(winedata_full)\n whole_stat = {\"statistic\": {\"wine\": variety_statistic, **common_statistic}}\n dump_to_json(whole_stat, 'stats.json')\n dump_stat_to_markdown(whole_stat, 'stats.md')\n","sub_path":"01-Data-Structures/hw/sticks/json_hw.py","file_name":"json_hw.py","file_ext":"py","file_size_in_byte":9214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"351709542","text":"from Kalman_class import Kalman\nfrom Kalman_Check import Check_Circle\nimport numpy as np\nimport math as ma\nimport matplotlib.pyplot as plt\n\nSensors_Data, X_Ground_Truth, Y_Ground_Truth, Time, u = Check_Circle()\n\nK = Kalman()\nK.State_Correction = np.zeros([5, 1])\nK.State_Correction[0] = 100\nK.State_Correction[4] = ma.pi / 2\nK.Covariance_Update = 0.01 * np.eye(len(K.State_Correction))\nK.Measure_Noise = np.diag([0.1 ** 2, 0.1 ** 2, 0.1 ** 2, 0.1 ** 2, 0.1 ** 2])\nK.Motion_Noise = np.diag([0.1 ** 2, 0.01 ** 2])\nX = np.empty([5, len(Sensors_Data)])\nK.State_Prediction_function(u[:, 0])\nfor i in range(len(Sensors_Data)):\n K.State_Update_function(Sensors_Data[i, :])\n X[:, i : i + 1] = K.State_Correction\n K.State_Prediction_function(u[:, i])\n\nplt.figure(1)\nplt.plot(Sensors_Data[:, 0], Sensors_Data[:, 1], \"ro\", label=\"Sensors Data\")\nplt.plot(X[0, :], X[1, :], label=\"State\")\nplt.plot(X_Ground_Truth[0, :], Y_Ground_Truth[0, :], label=\"Ground Truth\")\nplt.legend([\"Ground Truth\", \"State\", \"Sensors Data\"])\nplt.grid()\nplt.axis(\"equal\")\nplt.grid()\nplt.figure(2)\nplt.plot(Sensors_Data[:, 0], Sensors_Data[:, 1], \"ro\", label=\"Sensors Data\")\nplt.plot(X[0, :], X[1, :], label=\"State\")\nplt.legend([\"Sensors Data\", \"State\"])\nplt.grid()\nplt.axis(\"equal\")\nplt.show()\n","sub_path":"Code_RealTime/KalmanFilter/Kalman_class_check.py","file_name":"Kalman_class_check.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"548889991","text":"import json\n\nimport requests\nfrom flask import Flask, request\n\nCloudConnector = Flask(__name__)\n\n\ndef process(message):\n requests.post(\"http://dbconnector:7000/Processed\", json=message)\n\ndef sendToCloud(message):\n message.pop(\"ReceiverEmail\", None)\n message.pop(\"Sensor\", None)\n message.pop(\"Gravity\", None)\n message.pop(\"Value\", None)\n message.pop(\"SensorType\", None)\n latPos = str(message[\"Position\"][\"Lat\"])\n latPosFirstPart = latPos[:2]\n latPosSecondPart = latPos[2:]\n latPos = latPosFirstPart + \".\" + latPosSecondPart\n latPos = float(latPos)\n message[\"Position\"][\"Lat\"] = latPos\n\n longPos = str(message[\"Position\"][\"Long\"])\n longPosFirstPart = longPos[:2]\n longPosSecondPart = longPos[3:]\n longPos = longPosFirstPart + \".\" + longPosSecondPart\n longPos = float(longPos)\n message[\"Position\"][\"Long\"] = longPos\n data = [message]\n res = requests.post(\"http://cloud-service.us-east-1.elasticbeanstalk.com/data\", json=data)\n\n@CloudConnector.route(\"/sendProcessed\", methods=[\"POST\"])\ndef sendProcessed():\n data = request.json\n process(data)\n\n@CloudConnector.route(\"/sendData\", methods=[\"POST\"])\ndef sendMessage():\n data = request.json\n sendToCloud(data)\n return data\n\n\nif __name__ == \"__main__\":\n CloudConnector.run(host='0.0.0.0', port=6000)\n","sub_path":"FogLayer/CloudConnector/CloudConnector.py","file_name":"CloudConnector.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"40349142","text":"import sqlite3\n\n# Connect to database\nconn = sqlite3.connect(\"customers.db\")\n\n# Create a curso\nc = conn.cursor()\n\n# Insert one record to table\nc.execute(\"INSERT INTO customers VALUES ('customerName', 'customerLastName', 'customer@email.com')\")\n\n# Commit changes to db\nconn.commit()\n\n# Close connection to db\nconn.close()\n","sub_path":"addOneRecord.py","file_name":"addOneRecord.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"456478603","text":"# -*- coding:utf-8 -*-\n# @author :adolf\nimport requests\nimport json\nimport base64\nimport cv2\n\n# file_path = '/home/shizai/adolf/data/jindie/ehtd.png'\nfile_path = 'test_imgs/2CwH.png'\n# img = cv2.imread(file_path)\n# print(img.shape)\n\nurl = \"https://rpa-vc-verify.ai-indeed.com/verification_service/\"\n# url = \"http://127.0.0.1:2002/verification_service/\"\n\n\ndef get_result(encodestr):\n payload = {\"image\": encodestr, \"scenes\": 'shenzhen'}\n r = requests.post(url, json=payload)\n # print(r.text)\n res = json.loads(r.text)\n return res\n\n\nwith open(file_path, 'rb') as f:\n image = f.read()\n encodestr = str(base64.b64encode(image), 'utf-8')\n\nres_ = get_result(encodestr)\nprint(res_)\n","sub_path":"rpa_ocr/verification_service/test_captcha.py","file_name":"test_captcha.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"312623748","text":"import unittest\n\nimport scCloud as sc\nimport anndata\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\n\nclass TestPreprocessing(unittest.TestCase):\n\n\tdef test_log_norm(self):\n\t\tX = csr_matrix([[1, 11], [2, 20], [5, 6]])\n\t\tadata = anndata.AnnData(X)\n\t\tadata.var['robust'] = True\n\t\tsc.tools.log_norm(adata, 10)\n\t\tnp.testing.assert_allclose(np.expm1(adata.X.toarray()).sum(axis=1), 10, rtol=1e-7, atol=0)\n\n\tdef test_filter_cells_cite_seq(self):\n\t\tX = csr_matrix([[1, 11], [2, 20], [5, 6]])\n\t\tadata = anndata.AnnData(X)\n\t\tsc.tools.filter_cells_cite_seq(adata, 2)\n\t\tself.assertEqual(adata.shape[0], 2)\n","sub_path":"tests/test_preprocessing.py","file_name":"test_preprocessing.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"470944748","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2020 ETSI OSM\n#\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#\n\nimport logging\nimport yaml\nimport random\n\nfrom osm_ro_plugin.sdnconn import SdnConnectorBase, SdnConnectorError\n# from osm_rosdn_juniper_contrail.rest_lib import ContrailHttp\n# from osm_rosdn_juniper_contrail.rest_lib import NotFound\nfrom osm_rosdn_juniper_contrail.rest_lib import DuplicateFound\nfrom osm_rosdn_juniper_contrail.rest_lib import HttpException\nfrom osm_rosdn_juniper_contrail.sdn_api import UnderlayApi\n\n\nclass JuniperContrail(SdnConnectorBase):\n \"\"\"\n Juniper Contrail SDN plugin. The plugin interacts with Juniper Contrail Controller,\n whose API details can be found in these links:\n\n - https://github.com/tonyliu0592/contrail/wiki/API-Configuration-REST\n - https://www.juniper.net/documentation/en_US/contrail19/information-products/pathway-pages/api-guide-1910/\n tutorial_with_rest.html\n - https://github.com/tonyliu0592/contrail-toolbox/blob/master/sriov/sriov\n \"\"\"\n _WIM_LOGGER = \"openmano.sdnconn.junipercontrail\"\n\n def __init__(self, wim, wim_account, config=None, logger=None):\n \"\"\"\n\n :param wim: (dict). Contains among others 'wim_url'\n :param wim_account: (dict). Contains among others 'uuid' (internal id), 'name',\n 'sdn' (True if is intended for SDN-assist or False if intended for WIM), 'user', 'password'.\n :param config: (dict or None): Particular information of plugin. These keys if present have a common meaning:\n 'mapping_not_needed': (bool) False by default or if missing, indicates that mapping is not needed.\n 'service_endpoint_mapping': (list) provides the internal endpoint mapping. The meaning is:\n KEY meaning for WIM meaning for SDN assist\n -------- -------- --------\n device_id pop_switch_dpid compute_id\n device_interface_id pop_switch_port compute_pci_address\n service_endpoint_id wan_service_endpoint_id SDN_service_endpoint_id\n service_mapping_info wan_service_mapping_info SDN_service_mapping_info\n contains extra information if needed. Text in Yaml format\n switch_dpid wan_switch_dpid SDN_switch_dpid\n switch_port wan_switch_port SDN_switch_port\n datacenter_id vim_account vim_account\n id: (internal, do not use)\n wim_id: (internal, do not use)\n :param logger (logging.Logger): optional logger object. If none is passed 'openmano.sdn.sdnconn' is used.\n \"\"\"\n self.logger = logger or logging.getLogger(self._WIM_LOGGER)\n self.logger.debug('wim: {}, wim_account: {}, config: {}'.format(wim, wim_account, config))\n super().__init__(wim, wim_account, config, logger)\n\n self.user = wim_account.get(\"user\")\n self.password = wim_account.get(\"password\")\n\n url = wim.get(\"wim_url\") # underlay url\n auth_url = None\n self.project = None\n self.domain = None\n self.asn = None\n self.fabric = None\n overlay_url = None\n self.vni_range = None\n if config:\n auth_url = config.get(\"auth_url\")\n self.project = config.get(\"project\")\n self.domain = config.get(\"domain\")\n self.asn = config.get(\"asn\")\n self.fabric = config.get(\"fabric\")\n self.overlay_url = config.get(\"overlay_url\")\n self.vni_range = config.get(\"vni_range\")\n\n if not url:\n raise SdnConnectorError(\"'url' must be provided\")\n if not url.startswith(\"http\"):\n url = \"http://\" + url\n if not url.endswith(\"/\"):\n url = url + \"/\"\n self.url = url\n\n if not self.vni_range:\n self.vni_range = ['1000001-2000000']\n self.logger.info(\"No vni_range was provided. Using ['1000001-2000000']\")\n self.used_vni = set()\n\n if auth_url:\n if not auth_url.startswith(\"http\"):\n auth_url = \"http://\" + auth_url\n if not auth_url.endswith(\"/\"):\n auth_url = auth_url + \"/\"\n self.auth_url = auth_url\n\n if overlay_url:\n if not overlay_url.startswith(\"http\"):\n overlay_url = \"http://\" + overlay_url\n if not overlay_url.endswith(\"/\"):\n overlay_url = overlay_url + \"/\"\n self.overlay_url = overlay_url\n\n if not self.project:\n raise SdnConnectorError(\"'project' must be provided\")\n if not self.asn:\n # TODO: Get ASN from controller config; otherwise raise ERROR for the moment\n raise SdnConnectorError(\"'asn' was not provided and it was not possible to obtain it\")\n if not self.fabric:\n # TODO: Get FABRIC from controller config; otherwise raise ERROR for the moment\n raise SdnConnectorError(\"'fabric' was not provided and was not possible to obtain it\")\n if not self.domain:\n self.domain = 'default-domain'\n self.logger.info(\"No domain was provided. Using 'default-domain'\")\n\n underlay_api_config = {\n \"auth_url\": self.auth_url,\n \"project\": self.project,\n \"domain\": self.domain,\n \"asn\": self.asn,\n \"fabric\": self.fabric\n }\n self.underlay_api = UnderlayApi(url, underlay_api_config, user=self.user, password=self.password, logger=logger)\n\n self._max_duplicate_retry = 2\n self.logger.info(\"Juniper Contrail Connector Initialized.\")\n\n def _generate_vni(self):\n \"\"\"\n Method to get unused VxLAN Network Identifier (VNI)\n Args:\n None\n Returns:\n VNI\n \"\"\"\n # find unused VLAN ID\n for vlanID_range in self.vni_range:\n try:\n start_vni, end_vni = map(int, vlanID_range.replace(\" \", \"\").split(\"-\"))\n for i in range(start_vni, end_vni + 1):\n vni = random.randrange(start_vni, end_vni, 1)\n if vni not in self.used_vni:\n return vni\n except Exception as exp:\n raise SdnConnectorError(\"Exception {} occurred while searching a free VNI.\".format(exp))\n else:\n raise SdnConnectorError(\"Unable to create the virtual network.\"\n \" All VNI in VNI range {} are in use.\".format(self.vni_range))\n\n # Aux functions for testing\n def get_url(self):\n return self.url\n\n def get_overlay_url(self):\n return self.overlay_url\n\n def _create_port(self, switch_id, switch_port, network, vlan):\n \"\"\"\n 1 - Look for virtual port groups for provided switch_id, switch_port using name\n 2 - It the virtual port group does not exist, create it\n 3 - Create virtual machine interface for the indicated network and vlan\n \"\"\"\n self.logger.debug(\"create_port: switch_id: {}, switch_port: {}, network: {}, vlan: {}\".format(\n switch_id, switch_port, network, vlan))\n\n # 1 - Check if the vpg exists\n vpg_name = self.underlay_api.get_vpg_name(switch_id, switch_port)\n vpg = self.underlay_api.get_vpg_by_name(vpg_name)\n if not vpg:\n # 2 - If it does not exist create it\n vpg_id, _ = self.underlay_api.create_vpg(switch_id, switch_port)\n else:\n # Assign vpg_id from vpg\n vpg_id = vpg.get(\"uuid\")\n\n # 3 - Check if the vmi alreaady exists\n vmi_id, _ = self.underlay_api.create_vmi(switch_id, switch_port, network, vlan)\n self.logger.debug(\"port created\")\n\n return vpg_id, vmi_id\n\n def _delete_port(self, switch_id, switch_port, vlan):\n self.logger.debug(\"delete port, switch_id: {}, switch_port: {}, vlan: {}\".format(switch_id, switch_port, vlan))\n\n vpg_name = self.underlay_api.get_vpg_name(switch_id, switch_port)\n vmi_name = self.underlay_api.get_vmi_name(switch_id, switch_port, vlan)\n\n # 1 - Obtain vpg by id (if not vpg_id must have been error creating ig, nothing to be done)\n vpg_fqdn = [\"default-global-system-config\", self.fabric, vpg_name]\n vpg = self.underlay_api.get_by_fq_name(\"virtual-port-group\", vpg_fqdn)\n if not vpg:\n self.logger.warning(\"vpg: {} to be deleted not found\".format(vpg_name))\n else:\n # 2 - Get vmi interfaces from vpg\n vmi_list = vpg.get(\"virtual_machine_interface_refs\")\n if not vmi_list:\n # must have been an error during port creation when vmi is created\n # may happen if there has been an error during creation\n self.logger.warning(\"vpg: {} has not vmi, will delete nothing\".format(vpg))\n else:\n num_vmis = len(vmi_list)\n for vmi in vmi_list:\n fqdn = vmi.get(\"to\")\n # check by name\n if fqdn[2] == vmi_name:\n self.underlay_api.unref_vmi_vpg(vpg.get(\"uuid\"), vmi.get(\"uuid\"), fqdn)\n self.underlay_api.delete_vmi(vmi.get(\"uuid\"))\n num_vmis = num_vmis - 1\n\n # 3 - If there are no more vmi delete the vpg\n if not vmi_list or num_vmis == 0:\n self.underlay_api.delete_vpg(vpg.get(\"uuid\"))\n\n def check_credentials(self):\n \"\"\"Check if the connector itself can access the SDN/WIM with the provided url (wim.wim_url),\n user (wim_account.user), and password (wim_account.password)\n\n Raises:\n SdnConnectorError: Issues regarding authorization, access to\n external URLs, etc are detected.\n \"\"\"\n self.logger.debug(\"\")\n try:\n resp = self.underlay_api.check_auth()\n if not resp:\n raise SdnConnectorError('Empty response')\n except Exception as e:\n self.logger.error('Error checking credentials')\n raise SdnConnectorError('Error checking credentials: {}'.format(str(e)))\n\n def get_connectivity_service_status(self, service_uuid, conn_info=None):\n \"\"\"Monitor the status of the connectivity service established\n\n Arguments:\n service_uuid (str): UUID of the connectivity service\n conn_info (dict or None): Information returned by the connector\n during the service creation/edition and subsequently stored in\n the database.\n\n Returns:\n dict: JSON/YAML-serializable dict that contains a mandatory key\n ``sdn_status`` associated with one of the following values::\n\n {'sdn_status': 'ACTIVE'}\n # The service is up and running.\n\n {'sdn_status': 'INACTIVE'}\n # The service was created, but the connector\n # cannot determine yet if connectivity exists\n # (ideally, the caller needs to wait and check again).\n\n {'sdn_status': 'DOWN'}\n # Connection was previously established,\n # but an error/failure was detected.\n\n {'sdn_status': 'ERROR'}\n # An error occurred when trying to create the service/\n # establish the connectivity.\n\n {'sdn_status': 'BUILD'}\n # Still trying to create the service, the caller\n # needs to wait and check again.\n\n Additionally ``error_msg``(**str**) and ``sdn_info``(**dict**)\n keys can be used to provide additional status explanation or\n new information available for the connectivity service.\n \"\"\"\n self.logger.debug(\"\")\n try:\n resp = self.underlay_api.get_virtual_network(service_uuid)\n if not resp:\n raise SdnConnectorError('Empty response')\n if resp:\n vnet_info = resp\n\n # Check if conn_info reports error\n if conn_info.get(\"sdn_status\") == \"ERROR\":\n return {'sdn_status': 'ERROR', 'sdn_info': conn_info}\n else:\n return {'sdn_status': 'ACTIVE', 'sdn_info': vnet_info}\n else:\n return {'sdn_status': 'ERROR', 'sdn_info': 'not found'}\n except SdnConnectorError:\n raise\n except HttpException as e:\n self.logger.error(\"Error getting connectivity service: {}\".format(e))\n raise SdnConnectorError(\"Exception deleting connectivity service: {}\".format(str(e)))\n except Exception as e:\n self.logger.error('Exception getting connectivity service info: %s', e, exc_info=True)\n return {'sdn_status': 'ERROR', 'error_msg': str(e)}\n\n def create_connectivity_service(self, service_type, connection_points, **kwargs):\n \"\"\"\n Establish SDN/WAN connectivity between the endpoints\n :param service_type: (str): ``ELINE`` (L2), ``ELAN`` (L2), ``ETREE`` (L2), ``L3``.\n :param connection_points: (list): each point corresponds to\n an entry point to be connected. For WIM: from the DC to the transport network.\n For SDN: Compute/PCI to the transport network. One\n connection point serves to identify the specific access and\n some other service parameters, such as encapsulation type.\n Each item of the list is a dict with:\n \"service_endpoint_id\": (str)(uuid) Same meaning that for 'service_endpoint_mapping' (see __init__)\n In case the config attribute mapping_not_needed is True, this value is not relevant. In this case\n it will contain the string \"device_id:device_interface_id\"\n \"service_endpoint_encapsulation_type\": None, \"dot1q\", ...\n \"service_endpoint_encapsulation_info\": (dict) with:\n \"vlan\": ..., (int, present if encapsulation is dot1q)\n \"vni\": ... (int, present if encapsulation is vxlan),\n \"peers\": [(ipv4_1), (ipv4_2)] (present if encapsulation is vxlan)\n \"mac\": ...\n \"device_id\": ..., same meaning that for 'service_endpoint_mapping' (see __init__)\n \"device_interface_id\": same meaning that for 'service_endpoint_mapping' (see __init__)\n \"switch_dpid\": ..., present if mapping has been found for this device_id,device_interface_id\n \"switch_port\": ... present if mapping has been found for this device_id,device_interface_id\n \"service_mapping_info\": present if mapping has been found for this device_id,device_interface_id\n :param kwargs: For future versions:\n bandwidth (int): value in kilobytes\n latency (int): value in milliseconds\n Other QoS might be passed as keyword arguments.\n :return: tuple: ``(service_id, conn_info)`` containing:\n - *service_uuid* (str): UUID of the established connectivity service\n - *conn_info* (dict or None): Information to be stored at the database (or ``None``).\n This information will be provided to the :meth:`~.edit_connectivity_service` and :obj:`~.delete`.\n **MUST** be JSON/YAML-serializable (plain data structures).\n :raises: SdnConnectorException: In case of error. Nothing should be created in this case.\n Provide the parameter http_code\n \"\"\"\n # Step 1. Check in the overlay controller the virtual network created by the VIM\n # Best option: get network id of the VIM as param (if the VIM already created the network),\n # and do a request to the controller of the virtual networks whose VIM network id is the provided\n # Next best option: obtain the network by doing a request to the controller\n # of the virtual networks using the VLAN ID of any service endpoint.\n # 1.1 Read VLAN ID from a service endpoint\n # 1.2 Look for virtual networks with \"Provider Network\" including a VLAN ID.\n # 1.3 If more than one, ERROR\n # Step 2. Modify the existing virtual network in the overlay controller\n # 2.1 Add VNI (VxLAN Network Identifier - one free from the provided range)\n # 2.2 Add RouteTarget (RT) ('ASN:VNI', ASN = Autonomous System Number, provided as param or read from\n # controller config)\n # Step 3. Create a virtual network in the underlay controller\n # 3.1 Create virtual network (name, VNI, RT)\n # If the network already existed in the overlay controller, we should use the same name\n # name = 'osm-plugin-' + overlay_name\n # Else:\n # name = 'osm-plugin-' + VNI\n self.logger.info(\"create_connectivity_service, service_type: {}, connection_points: {}\".\n format(service_type, connection_points))\n if service_type.lower() != 'elan':\n raise SdnConnectorError('Only ELAN network type is supported by Juniper Contrail.')\n\n try:\n # Initialize data\n conn_info = None\n\n # 1 - Filter connection_points (transform cp to a dictionary with no duplicates)\n # This data will be returned even if no cp can be created if something is created\n work_cps = {}\n for cp in connection_points:\n switch_id = cp.get(\"service_endpoint_encapsulation_info\").get(\"switch_dpid\")\n switch_port = cp.get(\"service_endpoint_encapsulation_info\").get(\"switch_port\")\n service_endpoint_id = cp.get(\"service_endpoint_id\")\n cp_name = self.underlay_api.get_vpg_name(switch_id, switch_port)\n add_cp = work_cps.get(cp_name)\n if not add_cp:\n # check cp has vlan\n vlan = cp.get(\"service_endpoint_encapsulation_info\").get(\"vlan\")\n if vlan:\n # add cp to dict\n service_endpoint_ids = []\n service_endpoint_ids.append(service_endpoint_id)\n add_cp = {\"service_endpoint_ids\": service_endpoint_ids,\n \"switch_dpid\": switch_id,\n \"switch_port\": switch_port,\n \"vlan\": vlan}\n work_cps[cp_name] = add_cp\n else:\n self.logger.warning(\"cp service_endpoint_id : {} has no vlan, ignore\".format(\n service_endpoint_id))\n else:\n # add service_endpoint_id to list\n service_endpoint_ids = add_cp[\"service_endpoint_ids\"]\n service_endpoint_ids.append(service_endpoint_id)\n\n # 2 - Obtain free VNI\n vni = self._generate_vni()\n self.logger.debug(\"VNI: {}\".format(vni))\n\n # 3 - Create virtual network (name, VNI, RT), by the moment the name will use VNI\n retry = 0\n while retry < self._max_duplicate_retry:\n try:\n vnet_name = 'osm-plugin-' + str(vni)\n vnet_id, _ = self.underlay_api.create_virtual_network(vnet_name, vni)\n self.used_vni.add(vni)\n break\n except DuplicateFound as e:\n self.logger.debug(\"Duplicate error for vnet_name: {}\".format(vnet_name))\n self.used_vni.add(vni)\n retry += 1\n if retry >= self._max_duplicate_retry:\n raise e\n else:\n # Try to obtain a new vni\n vni = self._generate_vni()\n continue\n conn_info = {\n \"vnet\": {\n \"uuid\": vnet_id,\n \"name\": vnet_name\n },\n \"connection_points\": work_cps # dict with port_name as key\n }\n\n # 4 - Create a port for each endpoint\n for cp in work_cps.values():\n switch_id = cp.get(\"switch_dpid\")\n switch_port = cp.get(\"switch_port\")\n vlan = cp.get(\"vlan\")\n vpg_id, vmi_id = self._create_port(switch_id, switch_port, vnet_name, vlan)\n cp[\"vpg_id\"] = vpg_id\n cp[\"vmi_id\"] = vmi_id\n\n self.logger.info(\"created connectivity service, uuid: {}, name: {}\".format(vnet_id, vnet_name))\n return vnet_id, conn_info\n\n except Exception as e:\n # Log error\n if isinstance(e, SdnConnectorError) or isinstance(e, HttpException):\n self.logger.error(\"Error creating connectivity service: {}\".format(e))\n else:\n self.logger.error(\"Error creating connectivity service: {}\".format(e), exc_info=True)\n\n # If nothing is created raise error else return what has been created and mask as error\n if not conn_info:\n raise SdnConnectorError(\"Exception create connectivity service: {}\".format(str(e)))\n else:\n conn_info[\"sdn_status\"] = \"ERROR\"\n conn_info[\"sdn_info\"] = repr(e)\n # iterate over not added connection_points and add but marking them as error\n for cp in work_cps.values():\n if not cp.get(\"vmi_id\") or not cp.get(\"vpg_id\"):\n cp[\"sdn_status\"] = \"ERROR\"\n return vnet_id, conn_info\n\n def delete_connectivity_service(self, service_uuid, conn_info=None):\n \"\"\"\n Disconnect multi-site endpoints previously connected\n\n :param service_uuid: The one returned by create_connectivity_service\n :param conn_info: The one returned by last call to 'create_connectivity_service' or 'edit_connectivity_service'\n if they do not return None\n :return: None\n :raises: SdnConnectorException: In case of error. The parameter http_code must be filled\n \"\"\"\n self.logger.info(\"delete_connectivity_service vnet_name: {}, connection_points: {}\".\n format(service_uuid, conn_info))\n\n try:\n vnet_uuid = service_uuid\n # vnet_name = conn_info[\"vnet\"][\"name\"] # always should exist as the network is the first thing created\n work_cps = conn_info[\"connection_points\"]\n\n # 1: For each connection point delete vlan from vpg and it is is the\n # last one, delete vpg\n for cp in work_cps.values():\n self._delete_port(cp.get(\"switch_dpid\"), cp.get(\"switch_port\"), cp.get(\"vlan\"))\n\n # 2: Delete vnet\n self.underlay_api.delete_virtual_network(vnet_uuid)\n self.logger.info(\"deleted connectivity_service vnet_uuid: {}, connection_points: {}\".\n format(service_uuid, conn_info))\n except SdnConnectorError:\n raise\n except HttpException as e:\n self.logger.error(\"Error deleting connectivity service: {}\".format(e))\n raise SdnConnectorError(\"Exception deleting connectivity service: {}\".format(str(e)))\n except Exception as e:\n self.logger.error(\"Error deleting connectivity service: {}\".format(e), exc_info=True)\n raise SdnConnectorError(\"Exception deleting connectivity service: {}\".format(str(e)))\n\n def edit_connectivity_service(self, service_uuid, conn_info=None, connection_points=None, **kwargs):\n \"\"\" Change an existing connectivity service.\n\n This method's arguments and return value follow the same convention as\n :meth:`~.create_connectivity_service`.\n\n :param service_uuid: UUID of the connectivity service.\n :param conn_info: (dict or None): Information previously returned by last call to create_connectivity_service\n or edit_connectivity_service\n :param connection_points: (list): If provided, the old list of connection points will be replaced.\n :param kwargs: Same meaning that create_connectivity_service\n :return: dict or None: Information to be updated and stored at the database.\n When ``None`` is returned, no information should be changed.\n When an empty dict is returned, the database record will be deleted.\n **MUST** be JSON/YAML-serializable (plain data structures).\n Raises:\n SdnConnectorException: In case of error.\n \"\"\"\n # 0 - Check if there are connection_points marked as error and delete them\n # 1 - Compare conn_info (old connection points) and connection_points (new ones to be applied):\n # Obtain list of connection points to be added and to be deleted\n # Obtain vlan and check it has not changed\n # 2 - Obtain network: Check vnet exists and obtain name\n # 3 - Delete unnecesary ports\n # 4 - Add new ports\n self.logger.info(\"edit connectivity service, service_uuid: {}, conn_info: {}, \"\n \"connection points: {} \".format(service_uuid, conn_info, connection_points))\n\n # conn_info should always exist and have connection_points and vnet elements\n old_cp = conn_info.get(\"connection_points\", {})\n\n # Check if an element of old_cp is marked as error, in case it is delete it\n # Not return a new conn_info in this case because it is only partial information\n # Current conn_info already marks ports as error\n try:\n deleted_ports = []\n for cp in old_cp.values():\n if cp.get(\"sdn_status\") == \"ERROR\":\n switch_id = cp.get(\"switch_dpid\")\n switch_port = cp.get(\"switch_port\")\n old_vlan = cp.get(\"vlan\")\n self._delete_port(switch_id, switch_port, old_vlan)\n deleted_ports.append(self.underlay_api.get_vpg_name(switch_id, switch_port))\n\n for port in deleted_ports:\n del old_cp[port]\n\n # Delete sdn_status and sdn_info if exists (possibly marked as error)\n if conn_info.get(\"vnet\", {}).get(\"sdn_status\"):\n del conn_info[\"vnet\"][\"sdn_status\"]\n except HttpException as e:\n self.logger.error(\"Error trying to delete old ports marked as error: {}\".format(e))\n raise SdnConnectorError(e)\n except SdnConnectorError as e:\n self.logger.error(\"Error trying to delete old ports marked as error: {}\".format(e))\n raise\n except Exception as e:\n self.logger.error(\"Error trying to delete old ports marked as error: {}\".format(e), exc_info=True)\n raise SdnConnectorError(\"Error trying to delete old ports marked as error: {}\".format(e))\n\n if connection_points:\n\n # Check and obtain what should be added and deleted, if there is an error here raise an exception\n try:\n work_cps = {}\n for cp in connection_points:\n switch_id = cp.get(\"service_endpoint_encapsulation_info\").get(\"switch_dpid\")\n switch_port = cp.get(\"service_endpoint_encapsulation_info\").get(\"switch_port\")\n service_endpoint_id = cp.get(\"service_endpoint_id\")\n cp_name = self.underlay_api.get_vpg_name(switch_id, switch_port)\n add_cp = work_cps.get(cp_name)\n if not add_cp:\n # add cp to dict\n # check cp has vlan\n vlan = cp.get(\"service_endpoint_encapsulation_info\").get(\"vlan\")\n if vlan:\n service_endpoint_ids = []\n service_endpoint_ids.append(service_endpoint_id)\n add_cp = {\"service_endpoint_ids\": service_endpoint_ids,\n \"switch_dpid\": switch_id,\n \"switch_port\": switch_port,\n \"vlan\": vlan}\n work_cps[cp_name] = add_cp\n else:\n self.logger.warning(\"cp service_endpoint_id : {} has no vlan, ignore\".\n format(service_endpoint_id))\n else:\n # add service_endpoint_id to list\n service_endpoint_ids = add_cp[\"service_endpoint_ids\"]\n service_endpoint_ids.append(service_endpoint_id)\n\n old_port_list = list(old_cp.keys())\n port_list = list(work_cps.keys())\n to_delete_ports = list(set(old_port_list) - set(port_list))\n to_add_ports = list(set(port_list) - set(old_port_list))\n self.logger.debug(\"ports to delete: {}\".format(to_delete_ports))\n self.logger.debug(\"ports to add: {}\".format(to_add_ports))\n\n # Obtain network (check it is correctly created)\n vnet = self.underlay_api.get_virtual_network(service_uuid)\n if vnet:\n vnet_name = vnet[\"name\"]\n else:\n raise SdnConnectorError(\"vnet uuid: {} not found\".format(service_uuid))\n\n except SdnConnectorError:\n raise\n except Exception as e:\n self.logger.error(\"Error edit connectivity service: {}\".format(e), exc_info=True)\n raise SdnConnectorError(\"Exception edit connectivity service: {}\".format(str(e)))\n\n # Delete unneeded ports and add new ones: if there is an error return conn_info\n try:\n # Connection points returned in con_info should reflect what has (and should as ERROR) be done\n # Start with old cp dictionary and modify it as we work\n conn_info_cp = old_cp\n\n # Delete unneeded ports\n deleted_ports = []\n for port_name in conn_info_cp.keys():\n if port_name in to_delete_ports:\n cp = conn_info_cp[port_name]\n switch_id = cp.get(\"switch_dpid\")\n switch_port = cp.get(\"switch_port\")\n self.logger.debug(\"delete port switch_id={}, switch_port={}\".format(switch_id, switch_port))\n self._delete_port(switch_id, switch_port, vlan)\n deleted_ports.append(port_name)\n\n # Delete ports\n for port_name in deleted_ports:\n del conn_info_cp[port_name]\n\n # Add needed ports\n for port_name, cp in work_cps.items():\n if port_name in to_add_ports:\n switch_id = cp.get(\"switch_dpid\")\n switch_port = cp.get(\"switch_port\")\n vlan = cp.get(\"vlan\")\n self.logger.debug(\"add port switch_id={}, switch_port={}\".format(switch_id, switch_port))\n vpg_id, vmi_id = self._create_port(switch_id, switch_port, vnet_name, vlan)\n cp_added = cp.copy()\n cp_added[\"vpg_id\"] = vpg_id\n cp_added[\"vmi_id\"] = vmi_id\n conn_info_cp[port_name] = cp_added\n # replace endpoints in case they have changed\n conn_info_cp[port_name][\"service_endpoint_ids\"] = cp[\"service_endpoint_ids\"]\n\n conn_info[\"connection_points\"] = conn_info_cp\n return conn_info\n\n except Exception as e:\n # Log error\n if isinstance(e, SdnConnectorError) or isinstance(e, HttpException):\n self.logger.error(\"Error edit connectivity service: {}\".format(e), exc_info=True)\n else:\n self.logger.error(\"Error edit connectivity service: {}\".format(e))\n\n # There has been an error mount conn_info_cp marking as error cp that should\n # have been deleted but have not or should have been added\n for port_name, cp in conn_info_cp.items():\n if port_name in to_delete_ports:\n cp[\"sdn_status\"] = \"ERROR\"\n\n for port_name, cp in work_cps.items():\n curr_cp = conn_info_cp.get(port_name)\n if not curr_cp:\n cp_error = work_cps.get(port_name).copy()\n cp_error[\"sdn_status\"] = \"ERROR\"\n conn_info_cp[port_name] = cp_error\n conn_info_cp[port_name][\"service_endpoint_ids\"] = cp[\"service_endpoint_ids\"]\n\n conn_info[\"sdn_status\"] = \"ERROR\"\n conn_info[\"sdn_info\"] = repr(e)\n conn_info[\"connection_points\"] = conn_info_cp\n return conn_info\n\n else:\n # Connection points have not changed, so do nothing\n self.logger.info(\"no new connection_points provided, nothing to be done\")\n return\n\n\nif __name__ == '__main__':\n # Init logger\n log_format = \"%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(funcName)s(): %(message)s\"\n log_formatter = logging.Formatter(log_format, datefmt='%Y-%m-%dT%H:%M:%S')\n handler = logging.StreamHandler()\n handler.setFormatter(log_formatter)\n logger = logging.getLogger('openmano.sdnconn.junipercontrail')\n # logger.setLevel(level=logging.ERROR)\n # logger.setLevel(level=logging.INFO)\n logger.setLevel(level=logging.DEBUG)\n logger.addHandler(handler)\n\n # Read config\n with open('test.yaml') as f:\n config = yaml.safe_load(f.read())\n wim = {'wim_url': config.pop('wim_url')}\n wim_account = {'user': config.pop('user'), 'password': config.pop('password')}\n logger.info('wim: {}, wim_account: {}, config: {}'.format(wim, wim_account, config))\n\n # Init controller\n juniper_contrail = JuniperContrail(wim=wim, wim_account=wim_account, config=config, logger=logger)\n\n # Tests\n # Generate VNI\n for i in range(5):\n vni = juniper_contrail._generate_vni()\n juniper_contrail.used_vni.add(vni)\n print(juniper_contrail.used_vni)\n # juniper_contrail.used_vni.remove(1000003)\n print(juniper_contrail.used_vni)\n for i in range(2):\n vni = juniper_contrail._generate_vni()\n juniper_contrail.used_vni.add(vni)\n print(juniper_contrail.used_vni)\n\n # 0. Check credentials\n print('0. Check credentials')\n # juniper_contrail.check_credentials()\n\n # 1 - Create and delete connectivity service\n conn_point_0 = {\n \"service_endpoint_id\": \"0000:83:11.4\",\n \"service_endpoint_encapsulation_type\": \"dot1q\",\n \"service_endpoint_encapsulation_info\": {\n \"switch_dpid\": \"LEAF-1\",\n \"switch_port\": \"xe-0/0/17\",\n \"vlan\": \"501\"\n }\n }\n conn_point_1 = {\n \"service_endpoint_id\": \"0000:81:10.3\",\n \"service_endpoint_encapsulation_type\": \"dot1q\",\n \"service_endpoint_encapsulation_info\": {\n \"switch_dpid\": \"LEAF-2\",\n \"switch_port\": \"xe-0/0/16\",\n \"vlan\": \"501\"\n }\n }\n conn_point_2 = {\n \"service_endpoint_id\": \"0000:08:11.7\",\n \"service_endpoint_encapsulation_type\": \"dot1q\",\n \"service_endpoint_encapsulation_info\": {\n \"switch_dpid\": \"LEAF-2\",\n \"switch_port\": \"xe-0/0/16\",\n \"vlan\": \"502\"\n }\n }\n conn_point_3 = {\n \"service_endpoint_id\": \"0000:83:10.4\",\n \"service_endpoint_encapsulation_type\": \"dot1q\",\n \"service_endpoint_encapsulation_info\": {\n \"switch_dpid\": \"LEAF-1\",\n \"switch_port\": \"xe-0/0/17\",\n \"vlan\": \"502\"\n }\n }\n\n # 1 - Define connection points\n logger.debug(\"create first connection service\")\n print(\"Create connectivity service\")\n connection_points = [conn_point_0, conn_point_1]\n service_id, conn_info = juniper_contrail.create_connectivity_service(\"ELAN\", connection_points)\n logger.info(\"Created connectivity service 1\")\n logger.info(service_id)\n logger.info(yaml.safe_dump(conn_info, indent=4, default_flow_style=False))\n\n logger.debug(\"create second connection service\")\n print(\"Create connectivity service\")\n connection_points = [conn_point_2, conn_point_3]\n service_id2, conn_info2 = juniper_contrail.create_connectivity_service(\"ELAN\", connection_points)\n logger.info(\"Created connectivity service 2\")\n logger.info(service_id2)\n logger.info(yaml.safe_dump(conn_info2, indent=4, default_flow_style=False))\n\n logger.debug(\"Delete connectivity service 1\")\n juniper_contrail.delete_connectivity_service(service_id, conn_info)\n logger.debug(\"Delete Ok\")\n\n logger.debug(\"Delete connectivity service 2\")\n juniper_contrail.delete_connectivity_service(service_id2, conn_info2)\n logger.debug(\"Delete Ok\")\n","sub_path":"RO-SDN-juniper_contrail/osm_rosdn_juniper_contrail/sdn_assist_juniper_contrail.py","file_name":"sdn_assist_juniper_contrail.py","file_ext":"py","file_size_in_byte":38090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382634455","text":"\"\"\"\n.. module:: landscape\n :platform: Darwin, Linux, Unix, Windows\n :synopsis: Module containing the :class:`TestLandscape` class and associated diagnostic.\n\n.. moduleauthor:: Myron Walker \n\n\"\"\"\n\n__author__ = \"Myron Walker\"\n__copyright__ = \"Copyright 2020, Myron W Walker\"\n__credits__ = []\n__version__ = \"1.0.0\"\n__maintainer__ = \"Myron Walker\"\n__email__ = \"myron.walker@gmail.com\"\n__status__ = \"Development\" # Prototype, Development or Production\n__license__ = \"MIT\"\n\nfrom os.path import basename\nfrom typing import List, Optional, Union\n\nimport copy\nimport inspect\nimport json\nimport os\nimport threading\nimport traceback\nimport yaml\n\nimport pprint\n\nfrom akit.compat import import_by_name\n\nfrom akit.environment.variables import VARIABLES\nfrom akit.environment.context import Context\n\nfrom akit.exceptions import AKitConfigurationError, AKitSemanticError\nfrom akit.integration.credentials.basiccredential import BasicCredential\n\nfrom akit.paths import get_expanded_path, get_path_for_output\n\n\nfrom akit.xformatting import split_and_indent_lines\nfrom akit.xlogging.foundations import getAutomatonKitLogger\n\nfrom akit.integration.coordinators.powercoordinator import PowerCoordinator\nfrom akit.integration.credentials.musecredential import MuseCredential\nfrom akit.integration.credentials.sshcredential import SshCredential\nfrom akit.integration.landscaping.landscapedescription import LandscapeDescription\nfrom akit.integration.landscaping.landscapedevice import LandscapeDevice\nfrom akit.integration.landscaping.landscapedeviceextension import LandscapeDeviceExtension\n\nPASSWORD_MASK = \"(hidden)\"\n\ndef mask_passwords (context):\n \"\"\"\n Takes a dictionary context object and will recursively mask any password members found\n in the dictionary.\n \"\"\"\n for key, val in context.items():\n if (key == \"password\" or key == \"secret\"):\n context[key] = PASSWORD_MASK\n\n if isinstance(val, dict):\n mask_passwords(val)\n elif isinstance(val, list):\n for item in val:\n if isinstance(item, dict):\n mask_passwords(item)\n\n return\n\ndef filter_credentials(device_info, credential_lookup, category):\n \"\"\"\n Looks up the credentials associated with a device and returns the credentials found\n that match a given category.\n\n :param device_info: Device information dictionary with credential names to reference.\n :param credential_lookup: A credential lookup dictionary that is used to convert credential\n names into credential objects loaded from the landscape.\n :param category: The category of credentials to return when filtering credentials.\n \"\"\"\n cred_found_list = []\n\n cred_name_list = device_info[\"credentials\"]\n for cred_name in cred_name_list:\n if cred_name in credential_lookup:\n credential = credential_lookup[cred_name]\n if credential.category == category:\n cred_found_list.append(credential)\n else:\n error_lines = [\n \"The credential '{}' was not found in the credentials list.\",\n \"DEVICE:\"\n ]\n\n dev_repr_lines = pprint.pformat(device_info, indent=4).splitlines(False)\n for dline in dev_repr_lines:\n error_lines.append(\" \" + dline)\n\n error_lines.append(\"CREDENTIALS:\")\n cred_available_list = [cname for cname in credential_lookup.keys()]\n cred_available_list.sort()\n for cred_avail in cred_available_list:\n error_lines.append(\" \" + cred_avail)\n\n errmsg = os.linesep.join(error_lines)\n raise AKitConfigurationError(errmsg)\n\n return cred_found_list\n\n\nclass _LandscapeQueryLayer:\n \"\"\"\n The :class:`LanscapeQueryLayer` serves as the base layer for the :class:`Landscape` object. The\n :class:`LandscapeQueryLayer` contains the data and method that are initilized as part of the\n initialization of the Landscape object. It allows access to the processed data pulled from the\n \"landscape.yaml\" file which details the static declarations for the devices and resources that\n are the landscape file declares.\n \"\"\"\n context = Context()\n\n logger = getAutomatonKitLogger()\n landscape_lock = threading.RLock()\n\n landscape_description = LandscapeDescription\n landscape_device = LandscapeDevice\n landscape_device_extension = LandscapeDeviceExtension\n\n _query_gate = None\n\n def __init__(self):\n \"\"\"\n The :class:`LandscapeQueryLayer` object should not be instantiated directly.\n \"\"\"\n self._landscape_info = None\n self._landscape_file = None\n\n self._environment_info = None\n self._environment_label = None\n self._environment_muse = None\n \n self._has_muse_devices = False\n self._has_upnp_devices = False\n self._has_ssh_devices = False\n\n self._all_devices = {}\n\n self._credentials = {}\n\n self._serial_config_lookup_table = {}\n\n self._initialize()\n return\n\n @property\n def databases(self) -> dict:\n \"\"\"\n Returns the database configuration information from the landscape file.\n \"\"\"\n db_info = self.landscape_info[\"databases\"]\n return db_info\n\n @property\n def credentials(self) -> dict:\n return self._credentials\n\n @property\n def environment(self) -> dict:\n \"\"\"\n Returns the environment section of the landscape configuration.\n \"\"\"\n return self._environment_info\n\n @property\n def environment_label(self) -> str:\n \"\"\"\n Returns the environment.label section of the landscape configuration.\n \"\"\"\n return self._environment_label\n\n @property\n def environment_muse(self) -> dict:\n \"\"\"\n Returns the environment.muse section of the landscape configuration or None.\n \"\"\"\n return self._environment_muse\n\n @property\n def landscape_info(self):\n \"\"\"\n Returns the root landscape configuration dictionary.\n \"\"\"\n return self._landscape_info\n\n @property\n def has_muse_devices(self) -> bool:\n \"\"\"\n Returns a boolean indicating if the landscape contains muse devices.\n \"\"\"\n return self._has_muse_devices\n\n @property\n def has_ssh_devices(self) -> bool:\n \"\"\"\n Returns a boolean indicating if the landscape contains ssh devices.\n \"\"\"\n return self._has_ssh_devices\n\n @property\n def has_upnp_devices(self) -> bool:\n \"\"\"\n Returns a boolean indicating if the landscape contains upnp devices.\n \"\"\"\n return self._has_upnp_devices\n\n @property\n def name(self) -> str:\n \"\"\"\n Returns the name associated with the landscape.\n \"\"\"\n lname = None\n if \"name\" in self.landscape_info:\n lname = self.landscape_info[\"name\"]\n return lname\n\n def get_devices(self) -> List[LandscapeDevice]:\n \"\"\"\n Returns the list of devices from the landscape. This will\n skip any device that has a \"skip\": true member.\n \"\"\"\n device_list = None\n\n self.landscape_lock.acquire()\n try:\n device_list = [dev for dev in self._all_devices.values()]\n finally:\n self.landscape_lock.release()\n\n return device_list\n\n def get_device_configs(self) -> List[dict]:\n \"\"\"\n Returns the list of device configurations from the landscape. This will\n skip any device that has a \"skip\": true member.\n \"\"\"\n device_config_list = self._internal_get_device_configs()\n\n return device_config_list\n\n def get_muse_device_configs(self, exclude_upnp=False) -> List[dict]:\n \"\"\"\n Returns a list of devices that support Sonos muse protocol.\n \"\"\"\n muse_device_config_list = []\n\n for devinfo in self._internal_get_device_configs():\n dev_type = devinfo[\"deviceType\"]\n\n if exclude_upnp and dev_type == \"network/upnp\":\n continue\n\n if \"muse\" in devinfo:\n muse_device_config_list.append(devinfo)\n\n return muse_device_config_list\n\n def get_ssh_device_configs(self, exclude_upnp=False) -> List[dict]:\n \"\"\"\n Returns a list of devices that support ssh.\n \"\"\"\n ssh_device_config_list = []\n\n for devinfo in self._internal_get_device_configs():\n dev_type = devinfo[\"deviceType\"]\n\n if exclude_upnp and dev_type == \"network/upnp\":\n continue\n\n if \"ssh\" in devinfo:\n ssh_device_config_list.append(devinfo)\n\n return ssh_device_config_list\n\n def get_ssh_device_list(self) -> List[dict]:\n \"\"\"\n Returns a list of SSH devices.\n \"\"\"\n\n ssh_device_list = []\n\n for device in self._all_devices.values():\n device_type = device.device_type\n if device_type == \"network/ssh\":\n ssh_device_list.append(device)\n elif device_type == \"network/upnp\":\n if device.has_ssh_credential:\n ssh_device_list.append(device)\n\n return ssh_device_list\n\n def get_upnp_device_configs(self, ssh_only=False) -> List[dict]:\n \"\"\"\n Returns a list of UPNP device information dictionaries.\n \"\"\"\n upnp_device_config_list = self._internal_get_upnp_device_configs(ssh_only=ssh_only)\n\n return upnp_device_config_list\n\n def get_upnp_device_config_lookup_table(self) -> dict:\n \"\"\"\n Returns a USN lookup table for upnp devices.\n \"\"\"\n upnp_device_table = self._internal_get_upnp_device_config_lookup_table()\n\n return upnp_device_table\n\n def get_serial_config(self, serial_service_name: str):\n \"\"\"\n Looks up the configuration dictionary for the serial service specified.\n \"\"\"\n serial_config = None\n\n pod_config = self._landscape_info[\"pod\"]\n\n if \"serial\" in pod_config:\n if self._serial_config_lookup_table is not None:\n serial_config_lookup_table = self._serial_config_lookup_table\n else:\n serial_config_lookup_table = {}\n\n serial_config_list = pod_config[\"serial\"]\n for serial_config in serial_config_list:\n cfgname = serial_config[\"name\"]\n serial_config_lookup_table[cfgname] = serial_config\n\n if serial_service_name in self._serial_config_lookup_table:\n serial_config = self._serial_config_lookup_table[serial_service_name]\n\n return serial_config\n\n def _initialize(self):\n \"\"\"\n Called by '__init__' once at the beginning of the lifetime of a Landscape derived\n type. This allows the derived types to participate in a customized intialization\n process.\n \"\"\"\n\n context = Context()\n log_landscape_declaration = context.lookup(\"/environment/behaviors/log-landscape-declaration\")\n\n self._landscape_file = get_expanded_path(context.lookup(\"/environment/configuration/paths/landscape\"))\n landscape_file_basename = os.path.basename(self._landscape_file)\n landscape_file_basename, landscape_file_ext = os.path.splitext(landscape_file_basename)\n\n try:\n lscape_desc = self.landscape_description()\n self._landscape_info = lscape_desc.load(self._landscape_file)\n\n if log_landscape_declaration:\n results_dir = get_path_for_output()\n\n landscape_info_copy = copy.deepcopy(self._landscape_info)\n mask_passwords(landscape_info_copy)\n\n landscape_file_copy = os.path.join(results_dir, \"{}-declared{}\".format(landscape_file_basename, landscape_file_ext))\n with open(landscape_file_copy, 'w') as lsf:\n yaml.dump(landscape_info_copy, lsf, indent=4)\n\n landscape_file_copy = os.path.join(results_dir, \"{}-declared{}\".format(landscape_file_basename, \".json\"))\n with open(landscape_file_copy, 'w') as lsf:\n json.dump(landscape_info_copy, lsf, indent=4)\n\n except Exception as xcpt:\n err_msg = \"Error loading the landscape file from (%s)%s%s\" % (\n self._landscape_file, os.linesep, traceback.format_exc())\n raise AKitConfigurationError(err_msg) from xcpt\n\n if \"environment\" not in self._landscape_info:\n err_msg = \"The landscape file must have an 'environment' decription. (%s)\" % self._landscape_file\n raise AKitConfigurationError(err_msg)\n\n self._environment_info = self._landscape_info[\"environment\"]\n if \"label\" not in self._environment_info:\n err_msg = \"The landscape 'environment' decription must have a 'label' member (development, production, test). (%s)\" % self._landscape_file\n raise AKitConfigurationError(err_msg)\n if \"credentials\" not in self._environment_info:\n err_msg = \"There must be a 'environment/credentials' section.\"\n\n self._environment_label = self._environment_info[\"label\"]\n\n if \"muse\" in self._environment_info:\n self._environment_muse = self._environment_info[\"muse\"]\n if (\"authhost\" not in self._environment_muse) or (\"ctlhost\" not in self._environment_muse) or (\"version\" not in self._environment_muse):\n err_msg = \"The landscape 'environment/muse' decription must have both a 'envhost' and 'version' members. (%s)\" % self._landscape_file\n raise AKitConfigurationError(err_msg)\n\n self._initialize_credentials()\n\n # Initialize the devices so we know what they are, this will create a LandscapeDevice object for each device\n # and register it in the all_devices table where it can be found by the device coordinators for further activation\n self._initialize_devices()\n\n # Set the landscape_initialized even to allow other threads to use the APIs of the Landscape object\n self._query_gate.set()\n\n return\n\n def _initialize_credentials(self):\n \"\"\"\n \"\"\"\n\n credentials_list = self._environment_info[\"credentials\"]\n for credential in credentials_list:\n if \"identifier\" not in credential:\n raise AKitConfigurationError(\"Credential items in 'environment/credentials' must have an 'identifier' member.\")\n ident = credential[\"identifier\"]\n\n if \"category\" not in credential:\n raise AKitConfigurationError(\"Credential items in 'environment/credentials' must have an 'category' member.\")\n category = credential[\"category\"]\n\n if category == \"basic\":\n BasicCredential.validate(credential)\n credobj = BasicCredential(**credential)\n self._credentials[ident] = credobj\n elif category == \"muse\":\n MuseCredential.validate(credential)\n credobj = MuseCredential(**credential)\n self._credentials[ident] = credobj\n elif category == \"ssh\":\n SshCredential.validate(credential)\n credobj = SshCredential(**credential)\n self._credentials[ident] = credobj\n else:\n errmsg = \"Unknown category '{}' found in credential '{}'\".format(category, ident)\n raise AKitConfigurationError(errmsg)\n\n return\n\n def _initialize_devices(self):\n\n for dev_config_info in self._internal_get_device_configs():\n dev_type = dev_config_info[\"deviceType\"]\n keyid = None\n device = NotImplemented\n if dev_type == \"network/upnp\":\n upnp_info = dev_config_info[\"upnp\"]\n keyid = upnp_info[\"USN\"]\n device = LandscapeDevice(self, keyid, dev_type, dev_config_info)\n elif dev_type == \"network/ssh\":\n keyid = dev_config_info[\"host\"]\n device = LandscapeDevice(self, keyid, dev_type, dev_config_info)\n else:\n errmsg_lines = [\n \"Unknown device type %r in configuration file.\" % dev_type,\n \"DEVICE INFO:\"\n ]\n errmsg_lines.extend(split_and_indent_lines(pprint.pformat(dev_config_info, indent=4), 1))\n\n errmsg = os.linesep.join(errmsg_lines)\n raise AKitConfigurationError(errmsg)\n \n if keyid not in self._all_devices:\n self._all_devices[keyid] = device\n else:\n errmsg_lines = [\n \"Devices found with duplicate identifiers.\",\n \"FIRST DEVICE:\"\n ]\n errmsg_lines.extend(split_and_indent_lines(pprint.pformat(self._all_devices[keyid], indent=4), 1))\n errmsg_lines.append(\"DUPLICATE DEVICE:\")\n errmsg_lines.extend(split_and_indent_lines(pprint.pformat(dev_config_info, indent=4), 1))\n\n errmsg = os.linesep.join(errmsg_lines)\n raise AKitConfigurationError(errmsg)\n\n return\n\n def _internal_get_device_configs(self) -> List[dict]:\n \"\"\"\n Returns the list of devices from the landscape. This will\n skip any device that has a \"skip\": true member.\n\n .. note:: The _internal_ methods do not guard against calls prior to\n landscape initialization so they should only be called with care. This\n should not be called until after the _landscape_info variable has been\n loaded and contains the configuration data from the landscape.yaml file.\n \"\"\"\n\n device_config_list = []\n\n self.landscape_lock.acquire()\n try:\n pod_info = self._landscape_info[\"pod\"]\n for dev_config_info in pod_info[\"devices\"]:\n if \"skip\" in dev_config_info and dev_config_info[\"skip\"]:\n continue\n device_config_list.append(dev_config_info)\n finally:\n self.landscape_lock.release()\n\n return device_config_list\n\n def _internal_get_ssh_device_configs(self) -> List[dict]:\n \"\"\"\n Returns a list of SSH device information dictionaries.\n \"\"\"\n\n ssh_device_config_list = []\n\n for device_config in self._internal_get_device_configs():\n dev_type = device_config[\"deviceType\"]\n\n if dev_type == \"network/ssh\":\n ssh_device_config_list.append(device_config)\n\n return ssh_device_config_list\n\n def _internal_get_upnp_device_configs(self, ssh_only=False) -> List[dict]:\n \"\"\"\n Returns a list of UPNP device information dictionaries.\n \"\"\"\n\n upnp_device_config_list = []\n\n for device_config in self._internal_get_device_configs():\n dev_type = device_config[\"deviceType\"]\n\n if dev_type != \"network/upnp\":\n continue\n\n if ssh_only and \"ssh\" in device_config:\n upnp_device_config_list.append(device_config)\n else:\n upnp_device_config_list.append(device_config)\n\n return upnp_device_config_list\n\n def _internal_get_upnp_device_list(self) -> List[dict]:\n \"\"\"\n Returns a list of UPNP devices.\n \"\"\"\n\n upnp_device_list = []\n\n for device in self._all_devices.values():\n if device.device_type == \"network/upnp\":\n upnp_device_list.append(device)\n\n return upnp_device_list\n\n \n def _internal_get_upnp_device_config_lookup_table(self) -> dict:\n \"\"\"\n Returns a USN lookup table for upnp devices.\n\n .. note:: The _internal_ methods do not guard against calls prior to\n landscape initialization so they should only be called with care. This\n should not be called until after the _landscape_info variable has been\n loaded and contains the configuration data from the landscape.yaml file.\n \"\"\"\n\n upnp_device_config_list = self._internal_get_upnp_device_configs()\n\n upnp_device_config_table = {}\n for device_config in upnp_device_config_list:\n usn = device_config[\"upnp\"][\"USN\"]\n upnp_device_config_table[usn] = device_config\n\n return upnp_device_config_table\n\n def _internal_lookup_device_by_keyid(self, keyid) -> Optional[LandscapeDevice]:\n \"\"\"\n Looks up a device by keyid.\n \"\"\"\n\n self.landscape_lock.acquire()\n try:\n device = None\n if keyid in self._all_devices:\n device = self._all_devices[keyid]\n finally:\n self.landscape_lock.release()\n\n return device\n\nclass _LandscapeRegistrationLayer(_LandscapeQueryLayer):\n \"\"\"\n\n \"\"\"\n\n _registration_gate = None\n\n def __init__(self):\n _LandscapeQueryLayer.__init__(self)\n\n self._ordered_roles = []\n\n self._integration_points_registered = {}\n\n self._integration_point_registration_counter = 0\n\n # We need to wait till we have initialized the landscape query\n # layer before we start registering integration points\n self.landscape_description.register_integration_points(self)\n\n return\n \n\n def register_integration_point(self, role: str, mixin: type):\n \"\"\"\n This method should be called from the attach_to_environment methods from individual mixins\n in order to register the base level integrations. Integrations can be hierarchical so it\n is only necessary to register the root level integration mixins, the descendant mixins can\n be called from the root level mixins.\n\n :param role: The name of a role to assign for a mixin.\n :param mixin: The mixin to register for the associated role.\n \"\"\"\n thisType = type(self)\n\n self.landscape_lock.acquire()\n try:\n if role not in self._integration_points_registered:\n self._ordered_roles.append(role)\n self._integration_points_registered[role] = mixin\n\n self._integration_point_registration_counter += 1\n else:\n raise AKitSemanticError(\"A mixin with the role %r was already registered.\" % role)\n finally:\n self.landscape_lock.release()\n\n return\n\n def registration_finalize(self):\n \"\"\"\n Called in order to marke the registration process as complete in order\n for the activation stage to begin and to make the activation level methods\n callable.\n \"\"\"\n self._registration_complete = True\n return\n\n \n\nclass _LandscapeActivationLayer(_LandscapeRegistrationLayer):\n \"\"\"\n\n \"\"\"\n\n _activation_gate = None\n\n def __init__(self):\n _LandscapeRegistrationLayer.__init__(self)\n\n self._power_coord = None\n self._serial_coord = None\n\n self._muse_coord = None\n self._upnp_coord = None\n self._ssh_coord = None\n\n self._active_devices = {}\n\n self._device_pool = {}\n\n self._log_landscape_scan = self.context.lookup(\"/environment/behaviors/log-landscape-scan\")\n\n self._activation_errors = []\n\n self._first_contact_results = None\n\n self._integration_points_activated = {}\n self._integration_point_activation_counter = 0\n\n return\n\n @property\n def muse_coord(self):\n \"\"\"\n Returns a the :class:`MuseCoordinator` that is used to manage muse devices.\n \"\"\"\n self._ensure_activation()\n return self._muse_coord\n\n @property\n def ssh_coord(self):\n \"\"\"\n Returns a the :class:`SshPoolCoordinator` that is used to manage ssh devices.\n \"\"\"\n self._ensure_activation()\n return self._ssh_coord\n\n @property\n def upnp_coord(self):\n \"\"\"\n Returns a the :class:`UpnpCoordinator` that is used to manage upnp devices.\n \"\"\"\n self._ensure_activation()\n return self._upnp_coord\n\n def activate_integration_point(self, role: str, coordinator_constructor: callable):\n \"\"\"\n This method should be called from the attach_to_environment methods from individual mixins\n in order to register the base level integrations. Integrations can be hierarchical so it\n is only necessary to register the root level integration mixins, the descendant mixins can\n be called from the root level mixins.\n\n :param role: The name of a role to assign for a mixin.\n :param mixin: The mixin to register for the associated role.\n \"\"\"\n\n if role.startswith(\"coordinator/\"):\n \n if \"coordinator/serial\" not in self._integration_points_activated:\n self._integration_points_activated[\"coordinator/serial\"] = True\n\n if \"coordinator/power\" not in self._integration_points_activated:\n self._integration_points_activated[\"coordinator/power\"] = True\n\n _, coord_type = role.split(\"/\")\n if coord_type == \"upnp\" or coord_type == \"ssh\":\n if role not in self._integration_points_activated:\n self._integration_points_activated[role] = coordinator_constructor\n else:\n raise AKitSemanticError(\"Attempted to activate the UPNP coordinator twice.\")\n else:\n raise AKitSemanticError(\"Unknown coordinator type '%s'.\" % role)\n else:\n raise AKitSemanticError(\"Don't know how to activate integration point of type '%s'.\" % role)\n\n return\n\n def activation_finalize(self):\n\n thisType = type(self)\n\n self.landscape_lock.acquire()\n try:\n\n if thisType._activation_gate is None:\n thisType._activation_gate = threading.Event()\n thisType._activation_gate.clear()\n\n # Don't hold the landscape like while we wait for the\n # landscape to be activated\n self.landscape_lock.release()\n try:\n if \"coordinator/serial\" in self._integration_points_activated:\n self._activate_serial_coordinator()\n \n if \"coordinator/power\" in self._integration_points_activated:\n self._activate_power_coordinator()\n \n if \"coordinator/upnp\" in self._integration_points_activated:\n coordinator_constructor = self._integration_points_activated[\"coordinator/upnp\"]\n self._activate_upnp_coordinator(coordinator_constructor)\n \n if \"coordinator/ssh\" in self._integration_points_activated:\n coordinator_constructor = self._integration_points_activated[\"coordinator/ssh\"]\n self._activate_ssh_coordinator(coordinator_constructor)\n\n self._establish_connectivity()\n\n self._activation_gate.set()\n\n finally:\n self.landscape_lock.acquire()\n\n else:\n\n # Don't hold the landscape like while we wait for the\n # landscape to be activated\n self.landscape_lock.release()\n try:\n # Because the landscape is a global singleton and because\n # we were not the first thread to call the activate method,\n # wait for the first calling thread to finish activating the\n # Landscape before we return allowing other use of the Landscape\n # singleton\n self._activation_gate.wait()\n finally:\n self.landscape_lock.acquire()\n\n finally:\n self.landscape_lock.release()\n\n return\n\n def list_available_devices(self) -> List[LandscapeDevice]:\n \"\"\"\n Returns the list of devices from the landscape device pool. This will\n skip any device that has a \"skip\": true member.\n \"\"\"\n self._ensure_activation()\n\n device_list = None\n\n self.landscape_lock.acquire()\n try:\n device_list = [dev for dev in self._device_pool.values()]\n finally:\n self.landscape_lock.release()\n\n return device_list\n\n def _activate_power_coordinator(self):\n \"\"\"\n Initializes the power coordinator according the the information specified in the\n 'power' portion of the configuration file.\n \"\"\"\n pod_info = self._landscape_info[\"pod\"]\n\n # We need to initialize the power before attempting to initialize any devices, so the\n # devices will be able to lookup serial connections as they are initialized\n if \"power\" in pod_info:\n power_config = pod_info[\"power\"]\n self._power_coord = PowerCoordinator(self, power_config)\n\n return\n\n def _activate_serial_coordinator(self):\n \"\"\"\n Initializes the serial coordinator according the the information specified in the\n 'serial' portion of the configuration file.\n \"\"\"\n pod_info = self._landscape_info[\"pod\"]\n\n # We need to initialize the serial before attempting to initialize any devices, so the\n # devices will be able to lookup serial connections as they are initialized\n if \"serial\" in pod_info:\n serial_config = pod_info[\"serial\"]\n # TODO: Add creation of SerialCoordinator\n self._serial_coord = None\n\n return\n\n def _activate_ssh_coordinator(self, coordinator_constructor):\n \"\"\"\n Initializes the ssh coordinator according the the information specified in the\n 'devices' portion of the configuration file.\n \"\"\"\n self._has_ssh_devices = True\n self._ssh_coord = coordinator_constructor(self)\n\n return\n\n def _activate_upnp_coordinator(self, coordinator_constructor):\n \"\"\"\n Initializes the upnp coordinator according the the information specified in the\n 'devices' portion of the configuration file.\n \"\"\"\n\n self._has_upnp_devices = True \n self._upnp_coord = coordinator_constructor(self)\n\n return\n\n def _ensure_activation(self):\n \"\"\"\n Called by methods that require Landscape activation in order to make sure the 'activate' method\n has been called before the attempted use of the specified method.\n\n :param method: The name of the method guarding against the use of a Landscape that has not been\n activated.\n \"\"\"\n if self._activation_gate is not None:\n self._activation_gate.wait()\n else:\n curframe = inspect.currentframe()\n calframe = inspect.getouterframes(curframe, 2)\n guarded_method = calframe[1][3]\n\n errmsg = \"The Landscape must be activated before calling the '%s' method.\" % guarded_method\n raise AKitSemanticError(errmsg)\n\n return\n \n def _establish_connectivity(self) -> List[str]:\n \"\"\"\n The `_establish_connectivity` method provides a mechanism for the verification of connectivity with\n enterprise resources.\n\n :returns list: list of failing entities\n \"\"\"\n\n error_list = []\n connectivity_results = {}\n\n if self._has_upnp_devices:\n integration_cls = self._integration_points_registered[\"coordinator/upnp\"]\n upnp_error_list, upnp_connectivity_results = integration_cls.establish_connectivity()\n error_list.extend(upnp_error_list)\n connectivity_results.update(upnp_connectivity_results)\n\n if self._has_ssh_devices:\n integration_cls = self._integration_points_registered[\"coordinator/ssh\"]\n ssh_error_list, ssh_connectivity_results = integration_cls.establish_connectivity()\n error_list.extend(ssh_error_list)\n connectivity_results.update(ssh_connectivity_results)\n\n self._first_contact_results = connectivity_results\n\n return error_list\n\n def _internal_activate_device(self, keyid):\n \"\"\"\n Activates a device by copying a reference to the device from the all_devices\n pool to the active_devices and device_pool tables to make the device available\n for active use.\n \"\"\"\n errmsg = None\n\n self.landscape_lock.acquire()\n try:\n # Add the device to all devices, all devices does not change\n # based on check-out or check-in activity\n if keyid in self._all_devices:\n device = self._all_devices[keyid]\n\n if device is not None:\n # Add the device to the device pool, the device pool is used\n # for tracking device availability for check-out\n self._active_devices[keyid] = device\n self._device_pool[keyid] = device\n else:\n errmsg = \"Attempt made to activate an unknown device. keyid=%s\" % keyid\n\n finally:\n self.landscape_lock.release()\n\n return errmsg\n\n def _internal_get_upnp_coord(self):\n \"\"\"\n Internal method to get a reference to the upnp coordinator. This provides access\n to the upnp coordinator reference in the middle of activation and bypasses normal\n activation thread synchronization mechanisms. It should only be used after the upnp\n coordinator has been activated.\n \"\"\"\n return self._upnp_coord\n\n def _intenal_scan_activated_devices_for_power(self) -> bool:\n \"\"\"\n Go through all of the activated device types such as SSH and\n UPNP look for power automation requirements.\n \"\"\"\n return\n\n def _intenal_scan_activated_devices_for_serial(self) -> bool:\n \"\"\"\n Go through all of the activated device types such as SSH and\n UPNP look for power automation requirements.\n \"\"\"\n return\n\n def _locked_checkout_device(self, device) -> Optional[LandscapeDevice]:\n\n rtn_device = None\n\n keyid = device.keyid\n if keyid not in self._device_pool:\n raise AKitSemanticError(\"A device is being checked out, that is not in the device pool.\")\n\n rtn_device = self._device_pool[keyid]\n del self._device_pool[keyid]\n\n return rtn_device\n\n def _log_device_activation_results(self):\n\n landscape_first_contact_result_file = os.path.join(get_path_for_output(), \"landscape-first-contact-results.json\")\n with open(landscape_first_contact_result_file, 'w') as fcrf:\n json.dump(self._first_contact_results, fcrf, indent=4)\n\n if len(self._activation_errors) > 0:\n errmsg_lines = [\n \"Encountered device activation errors.\",\n \"ACTIVATION ERROR LIST:\"\n ]\n for aerror in self._activation_errors:\n errmsg_lines.append(\" %s\" % aerror)\n\n errmsg = os.linesep.join(errmsg_lines)\n raise AKitConfigurationError(errmsg)\n\n return\n\n\nclass Landscape(_LandscapeActivationLayer):\n \"\"\"\n The base class for all derived :class:`Landscape` objects. The :class:`Landscape`\n object is a singleton object that provides access to the resources and test\n environment level methods.\n \"\"\"\n\n _landscape_type = None\n _instance = None\n\n def __new__(cls):\n \"\"\"\n Constructs new instances of the Landscape object from the :class:`Landscape`\n type or from a derived type that is found in the module specified in the\n :module:`akit.environment.variables` module or by setting the\n 'AKIT_LANDSCAPE_MODULE' environment variable.\n \"\"\"\n if cls._instance is None:\n if cls._landscape_type is None:\n cls._instance = super(Landscape, cls).__new__(cls)\n else:\n cls._instance = super(Landscape, cls._landscape_type).__new__(cls._landscape_type)\n # Put any initialization here.\n return cls._instance\n\n def __init__(self):\n \"\"\"\n Creates an instance or reference to the :class:`Landscape` singleton object. On the first call to this\n constructor the :class:`Landscape` object is initialized and the landscape configuration is loaded.\n \"\"\"\n\n thisType = type(self)\n\n self.landscape_lock.acquire()\n try:\n\n if thisType._query_gate is None:\n thisType._query_gate = threading.Event()\n thisType._query_gate.clear()\n\n # We don't need to hold the landscape lock while initializing\n # the Landscape because no threads calling the constructor can\n # exit without the landscape initialization being finished.\n self.landscape_lock.release()\n\n try:\n _LandscapeActivationLayer.__init__(self)\n finally:\n self.landscape_lock.acquire()\n\n else:\n\n # Don't hold the landscape like while we wait for the\n # landscape to be initialized\n self.landscape_lock.release()\n try:\n # Because the landscape is a global singleton and because\n # we were not the first thread to call the contructor, wait\n # for the first calling thread to finish initializing the\n # Landscape before we return and try to use the returned\n # Landscape reference\n self._query_gate.wait()\n finally:\n self.landscape_lock.acquire()\n finally:\n self.landscape_lock.release()\n\n return\n\n def checkin_device(self, device: LandscapeDevice):\n \"\"\"\n Returns a landscape device to the the available device pool.\n \"\"\"\n self._ensure_activation()\n\n keyid = device.keyid\n\n self.landscape_lock.acquire()\n try:\n self._device_pool[keyid] = device\n finally:\n self.landscape_lock.release()\n\n return\n\n def checkout_a_device_by_modelName(self, modelName: str) -> Optional[LandscapeDevice]:\n \"\"\"\n Checks out a single device from the available pool using the modelName match\n criteria provided.\n \"\"\"\n self._ensure_activation()\n\n device = None\n\n device_list = self.checkout_devices_by_match(\"modelName\", modelName, count=1)\n if len(device_list) > 0:\n device = device_list[0]\n\n return device\n\n def checkout_a_device_by_modelNumber(self, modelNumber: str) -> Optional[LandscapeDevice]:\n \"\"\"\n Checks out a single device from the available pool using the modelNumber match\n criteria provided.\n \"\"\"\n self._ensure_activation()\n\n device = None\n\n device_list = self.checkout_devices_by_match(\"modelNumber\", modelNumber, count=1)\n if len(device_list) > 0:\n device = device_list[0]\n\n return device\n\n def checkout_devices_by_match(self, match_type: str, *match_params, count=None) -> List[LandscapeDevice]:\n \"\"\"\n Checks out the devices that are found to correspond with the match criteria provided. If the\n 'count' parameter is passed, then the number of devices that are checked out is limited to\n count matching devices.\n \"\"\"\n self._ensure_activation()\n\n device_list = None\n\n self.landscape_lock.acquire()\n try:\n device_list = self.list_available_devices_by_match(match_type, *match_params, count=count)\n\n for device in device_list:\n self._locked_checkout_device(device)\n finally:\n self.landscape_lock.release()\n\n return device_list\n\n def checkout_devices_by_modelName(self, modelName:str , count=None) -> List[LandscapeDevice]:\n \"\"\"\n Checks out the devices that are found to correspond with the modelName match criteria provided.\n If the 'count' parameter is passed, the the number of devices that are checked out is limited to\n count matching devices.\n \"\"\"\n self._ensure_activation()\n\n device_list = self.checkout_devices_by_match(\"modelName\", modelName, count=count)\n\n return device_list\n\n\n def checkout_devices_by_modelNumber(self, modelNumber: str, count=None) -> List[LandscapeDevice]:\n \"\"\"\n Checks out the devices that are found to correspond with the modelNumber match criteria provided.\n If the 'count' parameter is passed, the the number of devices that are checked out is limited to\n count matching devices.\n \"\"\"\n self._ensure_activation()\n\n device_list = self.checkout_devices_by_match(\"modelNumber\", modelNumber, count=count)\n\n return device_list\n\n def diagnostic(self, diaglabel: str, diags: dict): # pytest: disable=unused-argument\n \"\"\"\n Can be called in order to perform a diagnostic capture across the test landscape.\n\n :param diaglabel: The label to use for the diagnostic.\n :param diags: A dictionary of diagnostics to run.\n \"\"\"\n self._ensure_activation()\n\n return\n\n\n def first_contact(self) -> List[str]:\n \"\"\"\n The `first_contact` method provides a mechanism for the verification of connectivity with\n enterprise resources that is seperate from the initial call to `establish_connectivity`.\n\n :returns list: list of failing entities\n \"\"\"\n error_list = []\n return error_list\n\n def list_available_devices_by_match(self, match_type, *match_params, count=None) -> List[LandscapeDevice]:\n \"\"\"\n Creates and returns a list of devices from the available devices pool that are found\n to correspond to the match criteria provided. If a 'count' parameter is passed\n then the number of devices returned is limited to count devices.\n\n .. note:: This API does not perform a checkout of the devices returns so the\n caller should not consider themselves to the the owner of the devices.\n \"\"\"\n matching_devices = []\n device_list = self.list_available_devices()\n\n for dev in device_list:\n if dev.match_using_params(match_type, *match_params):\n matching_devices.append(dev)\n if count is not None and len(matching_devices) >= count:\n break\n\n return matching_devices\n\n def list_devices_by_match(self, match_type, *match_params, count=None) -> List[LandscapeDevice]:\n \"\"\"\n Creates and returns a list of devices that are found to correspond to the match\n criteria provided. If a 'count' parameter is passed then the number of devices\n returned is limited to count devices.\n \"\"\"\n matching_devices = []\n device_list = self.get_devices()\n\n for dev in device_list:\n if dev.match_using_params(match_type, *match_params):\n matching_devices.append(dev)\n if count is not None and len(matching_devices) >= count:\n break\n\n return matching_devices\n\n def list_devices_by_modelName(self, modelName, count=None) -> List[LandscapeDevice]:\n \"\"\"\n Creates and returns a list of devices that are found to correspond to the modelName\n match criteria provided. If a 'count' parameter is passed then the number of devices\n returned is limited to count devices.\n \"\"\"\n\n matching_devices = self.list_devices_by_match(\"modelName\", modelName, count=count)\n\n return matching_devices\n\n def list_devices_by_modelNumber(self, modelNumber, count=None) -> List[LandscapeDevice]:\n \"\"\"\n Creates and returns a list of devices that are found to correspond to the modelNumber\n match criteria provided. If a 'count' parameter is passed then the number of devices\n returned is limited to count devices.\n \"\"\"\n\n matching_devices = self.list_devices_by_match(\"modelNumber\", modelNumber, count=count)\n\n return matching_devices\n\n def lookup_credential(self, credential_name) -> Union[str, None]:\n \"\"\"\n Looks up a credential.\n \"\"\"\n cred_info = None\n \n if credential_name in self._credentials:\n cred_info = self._credentials[credential_name]\n\n return cred_info\n\n def lookup_device_by_modelName(self, modelName) -> Optional[LandscapeDevice]:\n \"\"\"\n Looks up a single device that is found to correspond to the modelName match criteria\n provided.\n \"\"\"\n device = None\n\n matching_devices = self.list_devices_by_match(\"modelName\", modelName, count=1)\n if len(matching_devices) > 0:\n device = matching_devices[0]\n\n return device\n\n def lookup_device_by_modelNumber(self, modelNumber) -> Optional[LandscapeDevice]:\n \"\"\"\n Looks up a single device that is found to correspond to the modelNumber match criteria\n provided.\n \"\"\"\n device = None\n\n matching_devices = self.list_devices_by_match(\"modelNumber\", modelNumber, count=1)\n if len(matching_devices) > 0:\n device = matching_devices[0]\n\n return device\n\n def lookup_power_agent(self, power_mapping: str) -> Union[dict, None]:\n \"\"\"\n Looks up a power agent by name.\n \"\"\"\n power_agent = self._power_coord.lookup_agent(power_mapping)\n return power_agent\n\n def lookup_serial_agent(self, serial_mapping: str) -> Union[dict, None]:\n \"\"\"\n Looks up a serial agent name.\n \"\"\"\n serial_agent = self._serial_coordinator.lookup_agent(serial_mapping)\n return serial_agent\n\n\ndef is_subclass_of_landscape(cand_type):\n \"\"\"\n Returns a boolean value indicating if the candidate type is a subclass\n of :class:`Landscape`.\n \"\"\"\n is_scol = False\n if inspect.isclass(cand_type) and issubclass(cand_type, Landscape):\n is_scol = True\n return is_scol\n\ndef load_and_set_landscape_type(lscape_module):\n \"\"\"\n Scans the module provided for :class:`Landscape` derived classes and will\n take the first one and assign it as the current runtime landscape type.\n \"\"\"\n class_items = inspect.getmembers(lscape_module, is_subclass_of_landscape)\n for _, cls_type in class_items:\n type_module_name = cls_type.__module__\n if type_module_name == lscape_module.__name__:\n Landscape._landscape_type = cls_type # pylint: disable=protected-access\n break\n return\n\nif VARIABLES.AKIT_LANDSCAPE_MODULE is not None:\n lscape_module_override = import_by_name(VARIABLES.AKIT_LANDSCAPE_MODULE)\n load_and_set_landscape_type(lscape_module_override )\n check_landscape = Landscape()\n","sub_path":"packages/akit/integration/landscaping/landscape.py","file_name":"landscape.py","file_ext":"py","file_size_in_byte":47683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"632151522","text":"import numpy as np\n\n\nclass DBSCAN:\n \"\"\" 基于密度的概念对数据样本进行聚类 \"\"\"\n def __init__(self, eps = 0.5, min_sample = 5):\n self.eps = eps\n self.min_sample = min_sample\n # end\n\n def get_neighbors(self, X, i):\n m = len(X)\n distances = [np.linalg.norm(X[i] - X[j], 2) for j in range(m)]\n neighbors_i = [j for j in range(m) if distances[j] < self.eps]\n return neighbors_i\n # end\n \n def grow_cluster(self, X, i, neighbors_i, id):\n self.assignments[i] = id\n Q = neighbors_i\n t = 0\n while t < len(Q):\n j = Q[t]\n t += 1\n if self.assignments[j] == 0:\n self.assignments[j] = id\n neighbors_j = self.get_neighbors(X, j)\n if len(neighbors_j) > self.min_sample:\n Q += neighbors_j\n # end\n \n def fit_transform(self, X):\n self.assignments = np.zeros(len(X))\n id = 1\n for i in range(len(X)):\n if self.assignments[i] != 0:\n continue\n neighbors_i = self.get_neighbors(X, i)\n if len(neighbors_i) > self.min_sample:\n self.grow_cluster(X, i, neighbors_i, id)\n id += 1\n return self.assignments\n # end\n# end\n","sub_path":"Modules/DBSCAN.py","file_name":"DBSCAN.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"245435515","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# ライブラリのインポート\nimport boto3\n\n\n# テキストファイルから文章を読み出す\nwith open(\"./translate5.txt\") as f:\n input_text = f.read()\n\n# 翻訳前の文を表示\nprint(\"------------------------------------\")\nprint(\"○ 翻訳前:\\n{}\".format(input_text))\nprint(\"------------------------------------\")\n\n# AWSを使った翻訳の準備\ntranslate = boto3.client(service_name=\"translate\")\n\n############################################\n\n\ndef honyaku(text, source, target):\n \"\"\"\n AWSを使って簡単に翻訳できるようにした関数\n \"\"\"\n\n result = translate.translate_text(\n Text=text,\n SourceLanguageCode=source,\n TargetLanguageCode=target\n )[\"TranslatedText\"].encode(\"UTF-8\")\n return result\n\n#############################################\n\n\n# 日本語から英語へ翻訳\ntranslate_en = honyaku(input_text, \"ja\", \"en\")\n# 英語への翻訳結果から日本語に翻訳\ntranslate_ja = honyaku(translate_en, \"en\", \"ja\")\nprint(\"○ 英語から日本語:\\n{}\".format(translate_ja))\nprint(\"------------------------------------\")\n\n#############################################\n\n# 英語からスペイン語に翻訳\ntranslate_es = honyaku(translate_en, \"en\", \"es\")\n# スペイン語への翻訳結果から日本語に翻訳\ntranslate_ja = honyaku(translate_es, \"es\", \"ja\")\nprint(\"○ スペイン語から日本語:\\n{}\".format(translate_ja))\nprint(\"------------------------------------\")\n\n#############################################\n\n# スペイン語からフィンランド語に翻訳\ntranslate_fi = honyaku(translate_es, \"es\", \"fi\")\n# フィンランド語への翻訳結果から日本語に翻訳\ntranslate_ja = honyaku(translate_fi, \"fi\", \"ja\")\nprint(\"○ フィンランド語から日本語:\\n{}\".format(translate_ja))\nprint(\"------------------------------------\")\n\n#############################################\n\n# フィンランド語からイタリア語に翻訳\ntranslate_it = honyaku(translate_fi, \"fi\", \"it\")\n# イタリア語への翻訳結果から日本語に翻訳\ntranslate_ja = honyaku(translate_it, \"it\", \"ja\")\nprint(\"○ イタリア語から日本語:\\n{}\".format(translate_ja))\nprint(\"------------------------------------\")\n\n#############################################\n\n# イタリア語からドイツ語に翻訳\ntranslate_de = honyaku(translate_it, \"it\", \"de\")\n# ドイツ語への翻訳結果から日本語に翻訳\ntranslate_ja = honyaku(translate_de, \"de\", \"ja\")\nprint(\"○ ドイツ語から日本語:\\n{}\".format(translate_ja))\nprint(\"------------------------------------\")\n\n#############################################\n\n# ドイツ語からチェコ語に翻訳\ntranslate_cs = honyaku(translate_de, \"de\", \"cs\")\n# チェコ語への翻訳結果から日本語に翻訳\ntranslate_ja = honyaku(translate_cs, \"cs\", \"ja\")\nprint(\"○ チェコ語から日本語:\\n{}\".format(translate_ja))\nprint(\"------------------------------------\")\n\n#############################################\n\n# チェコ語からロシア語に翻訳\ntranslate_ru = honyaku(translate_cs, \"cs\", \"ru\")\n# ロシア語への翻訳結果から日本語に翻訳\ntranslate_ja = honyaku(translate_ru, \"ru\", \"ja\")\nprint(\"○ ロシア語から日本語:\\n{}\".format(translate_ja))\n","sub_path":"aws/translate5.py","file_name":"translate5.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"412428430","text":"from django.shortcuts import render,redirect\nfrom .models import Zakgeld\nfrom django.views.decorators.csrf import csrf_exempt\n\n# Create your views here.\n\n\ndef index(request):\n return render(request,\"index.html\")\n\n\ndef minizakgeld_add (request):\n if request.method == \"POST\":\n person = request.POST['person']\n task = request.POST['task']\n amount = request.POST['amount']\n\n minizakgeld=Zakgeld(person=person, task=task, amount=amount)\n minizakgeld.save()\n\n return redirect('/')\n \n return render(request, \"minizakgeld_add.html\")\n\n\n\ndef minizakgeld_details (request):\n Zakgelds=Zakgeld.objects.all()\n \n context = {\n \"Zakgelds\": Zakgelds\n }\n return render(request,\"minizakgeld_details.html\", context)\n\n\ndef person_1 (request):\n \n return render(request, \"person_1.html\")","sub_path":"houseworks/minizakgeld/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"372684428","text":"import moderngl\nimport numpy as np\n\n\nclass SkinnedProjectedMeshRenderer(object):\n\n def __init__(self, ctx, vertices, indices, boneids, weights, skeleton):\n self.ctx = ctx\n self.skeleton = skeleton\n\n self.program = self.ctx.program(\n vertex_shader='''\n #version 430\n uniform mat4 Mvp;\n uniform mat4 Bones[32];\n\n in vec3 in_vert;\n\n in vec4 in_skinIndices;\n in vec4 in_skinWeights;\n\n void main() {\n\n vec4 vert = vec4(in_vert , 1.0);\n vec4 accumulated = vec4(0,0,0,1);\n\n accumulated += Bones[int(in_skinIndices.x)] * vert * in_skinWeights.x;\n accumulated += Bones[int(in_skinIndices.y)] * vert * in_skinWeights.y;\n accumulated += Bones[int(in_skinIndices.z)] * vert * in_skinWeights.z;\n accumulated += Bones[int(in_skinIndices.w)] * vert * in_skinWeights.w;\n\n accumulated.y = 0;\n \n gl_Position = Mvp * vec4(accumulated.xyz , 1.0);\n }\n ''',\n fragment_shader='''\n #version 430\n\n out vec4 f_color;\n void main() {\n\n f_color = vec4(.2, .2, .23, 1.0);\n gl_FragDepth = 0.999;\n }\n ''',\n )\n\n positions_only = vertices[:, :3]\n\n vbo = self.ctx.buffer(positions_only.flatten().astype('f4'))\n ibo = self.ctx.buffer(indices)\n sibo = self.ctx.buffer(boneids.flatten().astype('i4'))\n swbo = self.ctx.buffer(weights.flatten().astype('f4'))\n\n self.vao = ctx.vertex_array(\n self.program,\n [\n (vbo, '3f4', 'in_vert'),\n (sibo, '4i4', 'in_skinIndices'),\n (swbo, '4f4', 'in_skinWeights')\n ],\n ibo\n )\n\n def render(self, mvp, globalBoneMatrices):\n skinpose = np.zeros([32, 4, 4])\n for i in range(len(self.skeleton.bindpose)):\n skinpose[i, :, :] = np.dot(self.skeleton.bindpose[i], globalBoneMatrices[i])\n\n self.program['Mvp'].write(mvp)\n self.program['Bones'].write((skinpose.flatten()).astype('f4'))\n\n self.vao.render(moderngl.TRIANGLES)\n","sub_path":"animation/npk/animation_framework/viewer/projectedgroundshadowrender.py","file_name":"projectedgroundshadowrender.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"577251492","text":"import pandas as pd\nimport pickle\nfrom scipy.sparse import load_npz\n\ncategorical = ['category_name', 'city', 'image_top_1', 'param_1', 'param_2', 'param_3',\n 'parent_category_name', 'region', 'user_type', 'image_is_null', 'user_id']\n\nnumerical = ['item_seq_number', 'price', 'title_length_chars', 'description_length_chars',\n 'categorical_one_hot', 'ridge_predictions', 'mean_encoded_categorical']\n\ntext = ['title_tfidf', 'description_tfidf', 'title_pymorphy_tfidf',\n 'description_pymorphy_tfidf', 'title_bof', 'description_bof',\n 'title_tfidf_no_2grams', 'description_tfidf_no_2grams',\n 'title_tfidf_7000', 'description_tfidf_50000',\n 'title_tfidf_7000_pymorphy', 'description_tfidf_50000_pymorphy']\n\nimage = ['vgg16_512']\n\nall_features = categorical + numerical + text\n\ndef load_feature(category, feature_name, dataset='train'):\n path = '../feature_exploration/{}/{}/{}.npz'.format(category, dataset, feature_name)\n with open(path, 'rb') as f:\n feature = load_npz(f)\n return feature_name, feature\n\n\ndef extract_baseline_features(dfs):\n df = dfs[0] #main df\n feature_names = ['region', 'city', 'parent_category_name', 'category_name',\n 'param_1', 'param_2', 'param_3',\n 'price', 'item_seq_number', 'user_type', 'image_top_1']\n iscategorical = [True, True, True, True,\n True, True, True,\n False, False, True, True]\n \n features = []\n for feature_name, iscat in zip(feature_names, iscategorical):\n if feature_name.startswith('param_'):\n feature = df[feature_name].fillna(\"NA\")\n elif feature_name == 'image_top_1':\n feature = df[feature_name].fillna(-1)\n else:\n feature = df[feature_name]\n features.append((feature_name, feature, iscat))\n return features\n\n\ndef extract_date_features(dfs):\n df = dfs[0] #main df\n dates = pd.to_datetime(df['activation_date'])\n return [('activation_dayofweek', dates.dt.dayofweek, True)]\n\ndef extract_isnull_features(dfs):\n df = dfs[0] #main df\n \n return [\n ('image_isnotnull', ~pd.isnull(df['image']), True),\n ('price_isnotnull', ~pd.isnull(df['price']), True),\n ]\n\ndef get_train_vgg16():\n with open('../feature_exploration/train_img_features_vgg16/all.pkl', 'rb') as f:\n return pickle.load(f)\n\ndef get_test_vgg16():\n with open('../feature_exploration/test_img_features_vgg16/all.pkl', 'rb') as f:\n return pickle.load(f)\n \n\ndef get_train_vgg16pca100():\n with open('../feature_exploration/train_img_features_vgg16/pca100.pkl', 'rb') as f:\n return pickle.load(f)\n\ndef get_test_vgg16pca100():\n with open('../feature_exploration/test_img_features_vgg16/pca100.pkl', 'rb') as f:\n return pickle.load(f)\n\n\ndef extract_train_vgg16(dfs):\n df = dfs[0]\n vggtrain = get_train_vgg16()\n vggtrain = pd.merge(df, vggtrain, 'left', on='image', copy=False, sort=False)\n vggtrain = vggtrain[list(range(512))]\n vggtrain.fillna(0, inplace=True)\n return [('train_vgg16', vggtrain.as_matrix(), False)]\n\ndef extract_test_vgg16(dfs):\n df = dfs[0]\n vggtest = get_test_vgg16()\n vggtest = pd.merge(df, vggtrain, 'left', on='image', copy=False, sort=False)\n vggtest = vggtest[list(range(512))]\n vggtest.fillna(0, inplace=True)\n return [('test_vgg16', vggtest.as_matrix(), False)]\n\ndef extract_train_vgg16pca100(dfs):\n df = dfs[0]\n vggtrain = get_train_vgg16pca100()\n vggtrain = pd.merge(df, vggtrain, 'left', on='image', copy=False, sort=False)\n vggtrain = vggtrain[list(range(100))]\n vggtrain.fillna(0, inplace=True)\n return [('train_vgg16pca100', vggtest.as_matrix(), False)]\n\ndef extract_test_vgg16pca100(dfs):\n df = dfs[0]\n vggtest = get_test_vgg16pca100()\n vggtest = pd.merge(df, vggtest, 'left', on='image', copy=False, sort=False)\n vggtest = vggtest[list(range(100))]\n vggtest.fillna(0, inplace=True)\n return [('train_vgg16pca100', vggtest.as_matrix(), False)]\n\nextractors = {\n 'baseline': extract_baseline_features,\n 'date_features': extract_date_features, \n 'isnull_features': extract_isnull_features,\n 'train_vgg16': extract_train_vgg16,\n 'test_vgg16': extract_test_vgg16,\n 'train_vgg16pca100': extract_train_vgg16pca100,\n 'test_vgg16pca100': extract_test_vgg16pca100,\n}\n\ndef extract_features(dfs, names=['all']):\n features = [] # list of tuples (Series or np.array, boolean)\n if 'all' in names:\n for _, extractor in extractors.items():\n features += extractor(dfs)\n else:\n for name in names:\n features += extractors[name](dfs)\n return list(zip(*features))\n\n\ndef load_features(dataset='train', names=['all']):\n if 'all' in names:\n names = all_features\n \n features = []\n categorical_indices = []\n \n current_index = 0\n \n for feature_name in names:\n if feature_name in categorical:\n _, feature = load_feature('cat_features', feature_name, dataset=dataset)\n categorical_indices += list(range(current_index, current_index + feature.shape[1]))\n elif feature_name in numerical:\n _, feature = load_feature('num_features', feature_name, dataset=dataset)\n elif feature_name in text:\n _, feature = load_feature('text_features', feature_name, dataset=dataset)\n elif feature_name in image:\n _, feature = load_feature('img_features', feature_name, dataset=dataset)\n else:\n raise Exception('Wrong feature name: ' + feature_name)\n current_index += feature.shape[1]\n features.append(feature)\n return names, features, categorical_indices","sub_path":"models/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"618275679","text":"# Standard Form --> Y-intercept Form\nimport string, time\n \ndef init(): \n print(\"Standard Form to Y-intercept Form Calculator\")\n print(\"A Sub-Program to the Linear Equation Solver\\n\")\n time.sleep(1)\n \n print(string.capwords(\"\\n----- some important information -----\\n\")) \n print(\"1) The equation must already be in Standard Form:\")\n print(\" Ax + By = C\")\n print(\"2) You will enter the values individualy when asked\")\n print(\"3) The program currently supports only two variables\") \n print((\"-\" * len(\"----- some important information -----\")))\n time.sleep(1)\n\n AskEquation()\n\ndef AskEquation():\n # Formula = Ax + By = C\n A = input(\"\\nEnter coefficient of x: \")\n B = input(\"Enter coefficient of y: \")\n C = input(\"Enter value of c: \")\n\n Astr = str(A)\n Bstr = str(B)\n Cstr = str(C)\n\n print(\"\\nIs this the equation: \\n\")\n print(Astr + \"x + \" + Bstr + \"y = \" + Cstr + \"?\")\n answer = input(\"\")\n if answer == \"yes\":\n time.sleep(1)\n TransformEquation(A,B,C)\n elif answer == \"no\":\n time.sleep(1)\n AskEquation()\n\ndef TransformEquation(A, B, C):\n A = float(A)\n B = float(B)\n C = float(C)\n # Moves the x to the other side: By = C - Ax\n # Communative property of addition: By = -Ax + c\n A *= -1\n\n # Divide all sides by y coefficient: y = -Ax/B + C/B\n A /= B\n C /= B\n B /= B\n\n DisplaySolution(A,B,C) \n\ndef DisplaySolution(A,B,C):\n Asub = str(A)\n Bsub = str(B)\n Csub = str(C)\n if C < 0:\n print(\"Your equation in Y-intercept form is: \")\n print(\"\\ny = \" + Asub + \"x - \" + str(abs(C)))\n if C > 0:\n print(\"Your equation in Y-intercept form is: \")\n print(\"\\ny = \" + Asub + \"x + \" + Csub)\n if C == 0:\n print(\"\\nYour equation in Y-intercept form is: \")\n print(\"\\ny = \" + Asub + \"x\")\n\nif __name__ == \"__main__\":\n print(\"\\n\")\n init()\n\n\"\"\"\nADD FLOAT POINT VALUES\n\"\"\"\n","sub_path":"SFtoYIF.py","file_name":"SFtoYIF.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"185990987","text":"import numpy as np\nimport re\nfrom matplotlib import pyplot as plt\nimport sys\nfrom struct import unpack\nfrom PIL import Image\n\ndoffs=293.97\nbaseline=17.4724\nwidth=2912\nheight=2020\nndisp=260\nisint=0\nvmin=0\nvmax=238\nfocal_length = 6872.874\n\ndef read_pfm(file):\n # Adopted from https://stackoverflow.com/questions/48809433/read-pfm-format-in-python\n with open(file, \"rb\") as f:\n # Line 1: PF=>RGB (3 channels), Pf=>Greyscale (1 channel)\n type = f.readline().decode('latin-1')\n if \"PF\" in type:\n channels = 3\n elif \"Pf\" in type:\n channels = 1\n else:\n sys.exit(1)\n # Line 2: width height\n line = f.readline().decode('latin-1')\n width, height = re.findall('\\d+', line)\n width = int(width)\n height = int(height)\n\n # Line 3: +ve number means big endian, negative means little endian\n line = float(f.readline().decode('latin-1'))\n BigEndian = True\n if \"-\" in line:\n BigEndian = False\n # Slurp all binary data\n samples = width * height * channels;\n buffer = f.read(samples * 4)\n # Unpack floats with appropriate endianness\n if BigEndian:\n fmt = \">\"\n else:\n fmt = \"<\"\n fmt = fmt + str(samples) + \"f\"\n img = unpack(fmt, buffer)\n return img, height, width\n\n\ndepth_img, height, width = read_pfm('/home/ido/Deep/Pytorch/EDSR-PyTorch/src/disp0.pfm')\n\ndepth_img = np.array(depth_img)\n# Convert from the floating-point disparity value d [pixels] in the .pfm file to depth Z [mm]\ndepths = baseline * focal_length / (depth_img + doffs)\ndepths = np.reshape(depth_img, (height, width))\ndepths = np.fliplr([depths])[0]\n\nD = Image.open('/home/ido/Deep/Pytorch/EDSR-PyTorch/src/disp1.png')\nD = np.asarray(D)\nprint(np.min(depths))\nprint(np.max(depths))\nplt.imshow(depths)\nplt.show()","sub_path":"src/data/convert_middlebury.py","file_name":"convert_middlebury.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"382935739","text":"\"\"\"\ncollection of useful code sniplets\n\"\"\"\nimport torch\nimport torch.nn as nn\nfrom torchvision import transforms\nimport importlib\nimport os\nimport cv2\nimport numpy as np\n\ndef batch_accuracy(logits, labels):\n \"\"\"\n follow Bilinear Attention Networks https://github.com/jnhwkim/ban-vqa.git\n \"\"\"\n logits = torch.max(logits, 1)[1].data # argmax\n one_hots = torch.zeros(*labels.size()).cuda()\n one_hots.scatter_(1, logits.view(-1, 1), 1)\n scores = (one_hots * labels)\n\n return scores.sum(1)\n\n\ndef print_dict(d):\n for k in d:\n print(\"{}:{}\".format(k,d[k]))\n\n\ndef print_lr(optimizer, prefix, epoch):\n all_rl = []\n for p in optimizer.param_groups:\n all_rl.append(p['lr'])\n print('{} E{:03d}:'.format(prefix, epoch), ' Learning Rate: ', set(all_rl))\n\ndef set_lr(optimizer, value):\n for p in optimizer.param_groups:\n p['lr'] = value\n\ndef decay_lr(optimizer, rate):\n for p in optimizer.param_groups:\n p['lr'] *= rate\n\n\nclass Tracker:\n \"\"\" Keep track of results over time, while having access to monitors to display information about them. \"\"\"\n def __init__(self):\n self.data = {}\n\n def track(self, name, *monitors):\n \"\"\" Track a set of results with given monitors under some name (e.g. 'val_acc').\n When appending to the returned list storage, use the monitors to retrieve useful information.\n \"\"\"\n l = Tracker.ListStorage(monitors)\n self.data.setdefault(name, []).append(l)\n return l\n\n def to_dict(self):\n # turn list storages into regular lists\n return {k: list(map(list, v)) for k, v in self.data.items()}\n\n\n class ListStorage:\n \"\"\" Storage of data points that updates the given monitors \"\"\"\n def __init__(self, monitors=[]):\n self.data = []\n self.monitors = monitors\n for monitor in self.monitors:\n setattr(self, monitor.name, monitor)\n\n def append(self, item):\n for monitor in self.monitors:\n monitor.update(item)\n self.data.append(item)\n\n def __iter__(self):\n return iter(self.data)\n\n class MeanMonitor:\n \"\"\" Take the mean over the given values \"\"\"\n name = 'mean'\n\n def __init__(self):\n self.n = 0\n self.total = 0\n\n def update(self, value):\n self.total += value\n self.n += 1\n\n @property\n def value(self):\n return self.total / self.n\n\n class MovingMeanMonitor:\n \"\"\" Take an exponentially moving mean over the given values \"\"\"\n name = 'mean'\n\n def __init__(self, momentum=0.9):\n self.momentum = momentum\n self.first = True\n self.value = None\n\n def update(self, value):\n if self.first:\n self.value = value\n self.first = False\n else:\n m = self.momentum\n self.value = m * self.value + (1 - m) * value\n\n\ndef getNet(config):\n net_module = importlib.import_module(config.model_name)\n net = net_module.Net(config)\n model = nn.DataParallel(net).cuda()\n model_path = os.path.join(config.exp_dir, 'ckpt_best_accuracy_top1_model.pth')\n model_dict = torch.load(model_path)\n model.load_state_dict(model_dict)\n return model\n\n\ndef predict(model, image, isFile=True):\n if isFile:\n image = cv2.imread(image)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n image = cv2.resize(image, (28, 28))\n image = image[:,:,np.newaxis] # H,W,C ->ToTensor->C,H,W\n item_tf = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])\n image = item_tf(image)\n image = image.unsqueeze(0) # C,H,W -> batch,C,H,W\n model.eval()\n image.cuda()\n print(type(model))\n print(type(model.module))\n with torch.no_grad():\n result=model(image)\n logp=result['prob_dist'].squeeze(0)\n prob=np.exp(logp.cpu().numpy())\n return prob\n\n\n\n","sub_path":"sniplets.py","file_name":"sniplets.py","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"297856325","text":"from bs4 import BeautifulSoup\nfrom requests import get\nimport re\nimport random\nfrom datetime import date\nfrom scrapers.db import get_db\n\nuser_agents = [\n 'Googlebot/2.1 (+http://www.google.com/bot.html)',\n 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405',\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (FM Scene 4.6.1) ',\n 'AltaVista Intranet V2.0 AVS EVAL search@freeit.com',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'\n]\n\n\nclass RootScraper():\n \"\"\"\n Root class to be subclassed by other scrapers. Provide common functionality\n for all scrapers.\n \"\"\"\n def __init__(self):\n self.songs = []\n self.ranking = []\n self.ignorelist = []\n\n def is_scraped(self, url):\n db = get_db()\n already_scraped = False\n\n try:\n cursor = db.cursor()\n available = cursor.execute(\n \"\"\"\n SELECT url FROM urls WHERE url = ? and scraped_at is not null;\n \"\"\",\n (url,)\n ).fetchone()\n\n if available and available[0]:\n already_scraped = True\n\n except Exception as error:\n print(\"Error while checking if url is already scraped: \" + error)\n finally:\n db.close()\n\n return already_scraped\n\n def make_soup(self, url):\n \"\"\"\n Takes a url, and return BeautifulSoup for that Url\n \"\"\"\n header = {\n 'user-agent': random.choice(user_agents)\n }\n print(\"Downloading page: \" + url)\n\n return BeautifulSoup(get(url, headers=header, verify=False)\n .content, 'html.parser')\n\n def parse(self):\n \"\"\"\n Should return list of songs after assigning them to ~self.songs~.\n To be implemented by child scrapers.\n \"\"\"\n raise Exception(\"Implement it dumbfuck\")\n\n def on_success(self, url):\n db = get_db()\n print('Done with', url)\n print(\"------------------\")\n\n try:\n cursor = db.cursor()\n cursor.execute(\n \"\"\"\n UPDATE urls set scraped_at = ? where url = ?;\n \"\"\",\n (date.today(), url)\n )\n except Exception as error:\n print(\"Error while inserting url: \", error)\n finally:\n db.commit()\n db.close()\n\n def scrap_in_future(self, urls):\n \"\"\"\n Insert next scrap link in scraper database\n \"\"\"\n db = get_db()\n\n try:\n cursor = db.cursor()\n cursor.executemany(\n \"\"\"\n INSERT OR IGNORE INTO urls (url, scraped_at) VALUES (?, null);\n \"\"\",\n (urls)\n )\n except Exception as error:\n print(\"error while inserting scraped url: \", error)\n finally:\n db.commit()\n db.close()\n\n def get_next_links(self):\n \"\"\"\n Returns next link from scraper database\n \"\"\"\n def regexp(expr, item):\n reg = re.compile(expr)\n return reg.search(item) is not None\n\n db = get_db()\n db.create_function(\"REGEXP\", 2, regexp)\n\n try:\n while True:\n cursor = db.cursor()\n whitelist = '|'.join(self.whitelist)\n ignorelist = '|'.join(self.ignorelist)\n\n urls = cursor.execute(\n \"\"\"\n SELECT url FROM urls WHERE scraped_at is null AND url REGEXP ? AND url not REGEXP ?;\n \"\"\",\n (whitelist, ignorelist)\n ).fetchmany(100)\n\n for url in urls:\n db.close()\n yield url[0]\n except Exception as error:\n print(\"Error while fetching url from scraper database: \", error)\n","sub_path":"scrapers/RootScraper.py","file_name":"RootScraper.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"526362712","text":"import torch\r\nfrom torch.utils.data import DataLoader\r\nfrom torchvision import datasets, transforms\r\nfrom torch import nn, optim\r\n\r\nfrom resnet import ResNet18\r\n\r\n\r\ndef main():\r\n epoch = 1000\r\n batch_size = 32\r\n\r\n cifar_train = datasets.CIFAR10('./datasets', train=True, transform=transforms.Compose([\r\n transforms.Resize((32, 32)),\r\n transforms.ToTensor()\r\n ]), download=True)\r\n cifar_train = DataLoader(cifar_train, batch_size=batch_size, shuffle=True)\r\n\r\n cifar_test = datasets.CIFAR10('./datasets', train=False, transform=transforms.Compose([\r\n transforms.Resize((32, 32)),\r\n transforms.ToTensor()\r\n ]), download=True)\r\n cifar_test = DataLoader(cifar_test, batch_size=batch_size, shuffle=True)\r\n\r\n x, label = next(iter(cifar_train))\r\n print('x:', x.shape, 'label:', label.shape)\r\n\r\n # device = torch.device('cuda') # 使用gpu计算\r\n model = ResNet18()\r\n print('model结构:', model)\r\n criterion = nn.CrossEntropyLoss()\r\n optimizer = optim.Adam(model.parameters(), lr=1e-3)\r\n\r\n for epoch_id in range(epoch):\r\n # train...\r\n model.train()\r\n for batch_id, (x, label) in enumerate(cifar_train):\r\n logits = model(x) # logits[b,10] label[b]\r\n loss = criterion(logits, label) # logits和pred区别:pred是logits经过了softmax处理后的结果\r\n\r\n # 反向传播\r\n optimizer.zero_grad() # 为什么要清零:每次反向传播时,不是重新写梯度,而是累加梯度\r\n loss.backward()\r\n optimizer.step() # 更新了参数\r\n\r\n print(epoch_id, loss.item())\r\n\r\n # test...\r\n model.eval()\r\n with torch.no_grad():\r\n total_correct = 0\r\n total_num = 0\r\n for x, label in cifar_test:\r\n logits = model(x)\r\n pred = logits.argmax(dim=1) # 取最大值的索引 就是分类结果\r\n total_correct += torch.eq(pred, label).float().sum().item()\r\n total_num += x.size(0)\r\n\r\n acc = total_correct / total_num # 准确率\r\n print(epoch_id, acc)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"pytorch_tutorial/lesson18/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"646515030","text":"import sys\n\nsys.path.append('..')\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils.data import *\nimport time\nfrom model.models import get_efficientnet\nfrom dataset.dataset import DeeperForensicsDataset, get_train_transforms, get_valid_transforms\nfrom loss.losses import LabelSmoothing\nfrom catalyst.data.sampler import BalanceClassSampler\nfrom utils.utils import AverageMeter, calculate_metrics, Logger\n\ndef eval_model(epoch, is_save=True):\n batch_time = AverageMeter()\n losses = AverageMeter()\n acc_score = AverageMeter()\n model.eval()\n num_steps = len(eval_loader)\n print(f'total batches: {num_steps}')\n end = time.time()\n with torch.no_grad():\n for i, (XI, label) in enumerate(eval_loader):\n x = Variable(XI.cuda(device_id))\n # label = Variable(torch.LongTensor(label).cuda(device_id))\n label = Variable(label.cuda(device_id))\n\n # Forward pass: Compute predicted y by passing x to the model\n output = model(x)\n # Compute and print loss\n loss = criterion(output, label)\n losses.update(loss.data.item(), x.size(0))\n # update metrics\n output = nn.Softmax(dim=1)(output)\n confs, predicts = torch.max(output.detach(), dim=1)\n acc_score.update(calculate_metrics(predicts.cpu(), label.cpu()), 1)\n\n lr = optimizer.param_groups[0]['lr']\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % LOG_FREQ == 0:\n print(f'{epoch} [{i}/{num_steps}]\\t'\n f'time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n f'loss {losses.val:.4f} ({losses.avg:.4f})\\t'\n f'acc {acc_score.val:.4f} ({acc_score.avg:.4f})\\t'\n f'lr {lr:.8f}')\n\n print(f' * Eval loss {losses.avg:.4f}\\t'f'acc({acc_score.avg:.4f})')\n if is_save:\n train_logger.log(phase=\"eval\", values={\n 'epoch': epoch,\n 'loss': format(losses.avg, '.4f'),\n 'acc': format(acc_score.avg, '.4f'),\n 'lr': optimizer.param_groups[0]['lr']\n })\n scheduler.step()\n return losses.avg\n\ndef train_model(epoch):\n batch_time = AverageMeter()\n losses = AverageMeter()\n acc_score = AverageMeter()\n model.train()\n num_steps = len(train_loader)\n print(f'total batches: {num_steps}')\n end = time.time()\n\n for i, (XI, label) in enumerate(train_loader):\n x = Variable(XI.cuda(device_id))\n # label = Variable(torch.LongTensor(label).cuda(device_id))\n label = Variable(label.cuda(device_id))\n # Forward pass: Compute predicted y by passing x to the model\n output = model(x)\n # Compute and print loss\n loss = criterion(output, label)\n # update metrics\n losses.update(loss.data.item(), x.size(0))\n confs, predicts = torch.max(output.detach(), dim=1)\n acc_score.update(calculate_metrics(predicts.cpu(), label.cpu()), 1)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n lr = optimizer.param_groups[0]['lr']\n batch_time.update(time.time() - end)\n end = time.time()\n\n if i % LOG_FREQ == 0:\n print(f'{epoch} [{i}/{num_steps}]\\t'\n f'time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n f'loss {losses.val:.4f} ({losses.avg:.4f})\\t'\n f'acc {acc_score.val:.4f} ({acc_score.avg:.4f})\\t'\n f'lr {lr:.8f}')\n\n print(f' * Train loss {losses.avg:.4f}\\t'f'acc({acc_score.avg:.4f})')\n train_logger.log(phase=\"train\", values={\n 'epoch': epoch,\n 'loss': format(losses.avg, '.4f'),\n 'acc': format(acc_score.avg, '.4f'),\n 'lr': optimizer.param_groups[0]['lr']\n })\n scheduler.step()\n return losses.val\n\n\nif __name__ == '__main__':\n LOG_FREQ = 50\n batch_size = 128\n test_batch_size = 128\n device_id = 0\n lr = 0.0001\n epoch_start = 1\n num_epochs = epoch_start + 20\n model_name = 'efficientnet-b0'\n writeFile = '/data1/cby/temp/output_2/logs/' + model_name\n store_name = '/data1/cby/temp/output_2/weights/' + model_name\n if not os.path.isdir(store_name):\n os.makedirs(store_name)\n # model_path = None\n model_path = '/data1/cby/temp/output_3/weights/efficientnet-b0/efn_6_loss_0.2318.pth'\n model = get_efficientnet(model_name=model_name)\n if model_path is not None:\n # model = torch.load(model_path)\n model.load_state_dict(torch.load(model_path, map_location='cpu'))\n print('Model found in {}'.format(model_path))\n else:\n print('No model found, initializing random model.')\n model = model.cuda(device_id)\n train_logger = Logger(model_name=writeFile, header=['epoch', 'loss', 'acc', 'lr'])\n\n criterion = nn.CrossEntropyLoss()\n # criterion = LabelSmoothing(smoothing=0.05).cuda(device_id)\n # optimizer = optim.SGD(model.parameters(), lr=lr, momentum=0.9)\n # optimizer = optim.Adam(model.parameters(), lr=lr)\n optimizer = optim.AdamW(model.parameters(), lr=lr)\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=2, gamma=0.9)\n\n is_train = False\n if is_train:\n xdl = DeeperForensicsDataset(is_one_hot=False, data_type='train', transforms=get_train_transforms())\n train_loader = DataLoader(xdl, batch_size=batch_size, shuffle=False, num_workers=4,\n sampler=BalanceClassSampler(labels=xdl.get_labels(), mode=\"downsampling\"))\n # train_loader = DataLoader(xdl, batch_size=batch_size, shuffle=True, num_workers=4)\n train_dataset_len = len(xdl)\n\n xdl_eval = DeeperForensicsDataset(is_one_hot=False, data_type='val', transforms=get_valid_transforms())\n eval_loader = DataLoader(xdl_eval, batch_size=test_batch_size, shuffle=False, num_workers=4)\n eval_dataset_len = len(xdl_eval)\n print('train_dataset_len:', train_dataset_len, 'eval_dataset_len:', eval_dataset_len)\n min_loss = 100 if epoch_start == 1 else eval_model(epoch=epoch_start, is_save=False)\n for epoch in range(epoch_start, num_epochs):\n train_model(epoch)\n loss = eval_model(epoch)\n if loss < min_loss:\n min_loss = loss\n torch.save(model.state_dict(), '{}/efn_{}_loss_{:.4f}.pth'.format(store_name, epoch, loss))\n print('Current min loss:', min_loss)\n torch.save(model.state_dict(), '{}/efn_{}_loss_{:.4f}.pth'.format(store_name, 'last_20', loss))\n\n else:\n start = time.time()\n epoch_start = 1\n num_epochs = 1\n xdl_test = DeeperForensicsDataset(data_type='val', transforms=get_valid_transforms(), is_one_hot=False)\n eval_loader = DataLoader(xdl_test, batch_size=test_batch_size, shuffle=False, num_workers=4)\n test_dataset_len = len(xdl_test)\n print('test_dataset_len:', test_dataset_len)\n eval_model(epoch=0, is_save=False)\n print('Total time:', time.time() - start)\n\n\n\n\n\n\n\n","sub_path":"train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":7130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"591706578","text":"import os\nimport openpyxl\n\n\ndef criar_paginas():\n nome_pagina = input('Por favor, insira o nome da pagina\\n-> ')\n planilha.create_sheet(str(nome_pagina))\n\n\ndef criar_colunas():\n coluna_planilha = []\n pagina = input('Qual página deseja editar?\\n-> ')\n\n pagina_planilha = planilha[pagina]\n coluna_nome = input('Digite o nome da coluna que deseja criar\\n-> ')\n coluna_planilha.append(coluna_nome)\n\n pagina_planilha.append(coluna_planilha)\n\n\ndef salvar_planilha(planilha):\n nome_planilha = input('Digite o nome do arquivo a ser salvo: ')\n planilha.save(f'{nome_planilha}.xlsx')\n print(f'Planilha {nome_planilha}.xlsx salva com sucesso !!')\n\n\nif __name__ == '__main__':\n planilha = openpyxl.Workbook()\n\n print('Bem vindo ao gerador de planilhas !!')\n print('Vamos criar uma nova pagina !!')\n\n # continua = True\n criar_paginas()\n while True: \n\n escolha = input(str('Deseja criar mais uma pagina? [sim/nao]\\n-> ')).lower()\n\n if escolha == 'sim':\n criar_paginas()\n else:\n print(f'As paginas criadas são\\n -> {planilha.sheetnames}')\n \n break\n\n criar_colunas() \n while True:\n\n escolha = input('Deseja criar mais uma coluna? [sim/nao]\\n-> ')\n if escolha == 'sim':\n criar_colunas()\n else:\n print('As colunas foram criadas !!')\n \n break\n\n\n salvar_planilha(planilha)\n\n\n # print('Digite o nome da coluna')\n\n # print('Deseja criar mais colunas?')\n\n # if True:\n # print('Digite o nome da coluna')\n # else:\n # print('Digite os valores a incluir nas colunas separados por virgulas')\n\n # print('Digite o nome do arquivo a ser salvo')\n\n '''\n Capurar o nome da pagina;\n Perguntar se deseja criar mais uma pagina;\n Mostrar as paginas criadas;\n Perguntar qual pagina para editar;\n Capturar o nome das colunas;\n Perguntar se deseja continuar a criar colunas;\n Capturar os dados para incluir nas linhas das colunas.\n\n Finalizar o programa\n '''","sub_path":"bootcamp_projetos/automacao_planilhas/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"294741335","text":"import qt\nimport logging\nimport queue_item\nimport queue_model_objects_v1 as queue_model_objects\nimport abc\nimport copy\nimport ShapeHistory as shape_history\n\n#from BlissFramework.Utils import widget_colors\n\n\nclass CreateTaskBase(qt.QWidget):\n \"\"\"\n Base class for widgets that are used to create tasks.\n Contains methods for handling the PathTemplate,\n AcqusitionParameters object, and other functionalty for\n creating Task objects.\n\n The members self._acq_widget and self._data_path_widget\n are used to reference the widgets for respective widgets.\n\n Tests for self.acq_widgets and self._data_path_widget is\n be made, to make this class generic for widgets not using\n the objects PathTemplate and AcquisitionParameters.\n \"\"\"\n def __init__(self, parent, name, fl, task_node_name = 'Unamed task-node'):\n qt.QWidget.__init__(self, parent, name, fl)\n \n self._shape_history = None\n self._tree_brick = None\n self._task_node_name = task_node_name\n\n # Centred positons that currently are selected in the parent\n # widget, position_history_brick.\n self._selected_positions = []\n\n # Abstract attributes\n self._acq_widget = None\n self._data_path_widget = None\n self._current_selected_items = []\n self._path_template = None\n self._energy_scan_result = None\n self._session_hwobj = None\n self._beamline_setup_hwobj = None\n \n qt.QObject.connect(qt.qApp, qt.PYSIGNAL('tab_changed'),\n self.tab_changed)\n\n def init_models(self):\n self.init_acq_model()\n self.init_data_path_model()\n\n def init_acq_model(self):\n bl_setup = self._beamline_setup_hwobj\n\n if bl_setup is not None:\n if self._acq_widget:\n self._acq_widget.set_beamline_setup(bl_setup)\n self._acquisition_parameters = bl_setup.get_default_acquisition_parameters()\n else:\n self._acquisition_parameters = queue_model_objects.AcquisitionParameters()\n\n def init_data_path_model(self):\n bl_setup = self._beamline_setup_hwobj\n\n if bl_setup is not None:\n # Initialize the path_template of the widget to default\n # values read from the beamline setup\n if self._data_path_widget:\n self._data_path_widget._base_image_dir = \\\n self._session_hwobj.get_base_image_directory()\n self._data_path_widget._base_process_dir = \\\n self._session_hwobj.get_base_process_directory()\n\n (data_directory, proc_directory) = self.get_default_directory()\n self._path_template = bl_setup.get_default_path_template()\n self._path_template.directory = data_directory\n self._path_template.process_directory = proc_directory\n self._path_template.base_prefix = self.get_default_prefix()\n self._path_template.run_number = bl_setup.queue_model_hwobj.\\\n get_next_run_number(self._path_template)\n else:\n self._path_template = queue_model_objects.PathTemplate()\n\n def tab_changed(self, tab_index, tab):\n # Update the selection if in the main tab and logged in to\n # ISPyB\n if tab_index is 0 and self._session_hwobj.proposal_code:\n self.update_selection()\n\n def set_beamline_setup(self, bl_setup_hwobj):\n self._beamline_setup_hwobj = bl_setup_hwobj\n\n try:\n bl_setup_hwobj.energy_hwobj.connect('energyChanged', self.set_energy)\n bl_setup_hwobj.transmission_hwobj.connect('attFactorChanged', self.set_transmission)\n bl_setup_hwobj.resolution_hwobj.connect('positionChanged', self.set_resolution)\n bl_setup_hwobj.omega_axis_hwobj.connect('positionChanged', self.update_osc_start)\n except AttributeError as ex:\n msg = 'Could not connect to one or more hardware objects' + str(ex)\n logging.getLogger(\"HWR\").warning(msg)\n \n self._shape_history = bl_setup_hwobj.shape_history_hwobj\n self._session_hwobj = bl_setup_hwobj.session_hwobj\n self.init_models()\n\n def update_osc_start(self, new_value):\n acq_widget = self.get_acquisition_widget()\n\n if acq_widget:\n acq_widget.update_osc_start(new_value)\n\n def _prefix_ledit_change(self, new_value):\n item = self._current_selected_items[0]\n model = item.get_model()\n\n if self.isEnabled():\n if isinstance(item, queue_item.TaskQueueItem) and \\\n not isinstance(item, queue_item.DataCollectionGroupQueueItem):\n self._path_template.base_prefix = str(new_value)\n name = self._path_template.get_prefix()\n model.set_name(name)\n item.setText(0, model.get_name())\n \n def _run_number_ledit_change(self, new_value):\n item = self._current_selected_items[0]\n model = item.get_model()\n\n if self.isEnabled():\n if isinstance(item, queue_item.TaskQueueItem) and \\\n not isinstance(item, queue_item.DataCollectionGroupQueueItem):\n if str(new_value).isdigit():\n model.set_number(int(new_value))\n item.setText(0, model.get_name())\n\n def handle_path_conflict(self, widget, new_value):\n self._tree_brick.dc_tree_widget.check_for_path_collisions()\n \n path_conflict = self._beamline_setup_hwobj.queue_model_hwobj.\\\n check_for_path_collisions(self._path_template)\n\n if new_value != '':\n self._data_path_widget.indicate_path_conflict(path_conflict) \n \n def set_tree_brick(self, brick):\n self._tree_brick = brick\n\n @abc.abstractmethod\n def set_energies(self):\n pass\n \n def get_sample_item(self, item):\n if isinstance(item, queue_item.SampleQueueItem):\n return item\n elif isinstance(item, queue_item.TaskQueueItem):\n return item.get_sample_view_item()\n else:\n return None\n\n def get_group_item(self, item):\n if isinstance(item, queue_item.DataCollectionGroupQueueItem):\n return item\n elif isinstance(item, queue_item.TaskQueueItem):\n return self.item.parent()\n else:\n return None\n\n def get_acquisition_widget(self):\n return self._acq_widget\n\n def get_data_path_widget(self):\n return self._data_path_widget\n\n def _item_is_group_or_sample(self):\n result = False\n \n if self._current_selected_items:\n item = self._current_selected_items[0]\n \n if isinstance(item, queue_item.SampleQueueItem) or \\\n isinstance(item, queue_item.DataCollectionGroupQueueItem):\n result = True\n \n return result\n\n def set_energy(self, energy, wavelength): \n if self._item_is_group_or_sample() and energy:\n acq_widget = self.get_acquisition_widget()\n \n if acq_widget:\n acq_widget.previous_energy = energy\n acq_widget.set_energy(energy, wavelength)\n\n def set_transmission(self, trans):\n acq_widget = self.get_acquisition_widget()\n \n if self._item_is_group_or_sample() and acq_widget:\n acq_widget.update_transmission(trans)\n\n def set_resolution(self, res):\n acq_widget = self.get_acquisition_widget()\n \n if self._item_is_group_or_sample() and acq_widget:\n acq_widget.update_resolution(res)\n \n def set_run_number(self, run_number):\n data_path_widget = self.get_data_path_widget()\n\n if data_path_widget:\n data_path_widget.set_run_number(run_number)\n\n def get_default_prefix(self, sample_data_node = None, generic_name = False):\n prefix = self._session_hwobj.get_default_prefix(sample_data_node, generic_name)\n return prefix\n \n def get_default_directory(self, tree_item = None, sub_dir = ''):\n group_name = self._session_hwobj.get_group_name()\n\n if group_name:\n sub_dir = group_name + '/' + sub_dir\n\n if tree_item:\n item = self.get_sample_item(tree_item) \n sub_dir += item.get_model().get_name()\n\n if isinstance(item, queue_item.SampleQueueItem):\n if item.get_model().lims_id == -1:\n sub_dir += ''\n \n data_directory = self._session_hwobj.\\\n get_image_directory(sub_dir)\n\n proc_directory = self._session_hwobj.\\\n get_process_directory(sub_dir)\n \n return (data_directory, proc_directory)\n\n def ispyb_logged_in(self, logged_in):\n self.init_models()\n self.update_selection()\n\n def select_shape_with_cpos(self, cpos):\n self._shape_history.select_shape_with_cpos(cpos)\n \n def selection_changed(self, items):\n if items:\n if len(items) == 1:\n self._current_selected_items = items\n self.single_item_selection(items[0])\n elif len(items) > 1: \n sample_items = []\n\n # Allow mutiple selections on sample items, only.\n for item in items:\n if isinstance(item, queue_item.SampleQueueItem):\n sample_items.append(item)\n\n if sample_items:\n self._current_selected_items = sample_items\n self.multiple_item_selection(sample_items)\n else:\n self.setDisabled(True)\n\n def update_selection(self):\n self.selection_changed(self._current_selected_items)\n\n def single_item_selection(self, tree_item):\n sample_item = self.get_sample_item(tree_item)\n \n if isinstance(tree_item, queue_item.SampleQueueItem):\n sample_data_model = sample_item.get_model()\n self._path_template = copy.deepcopy(self._path_template)\n self._acquisition_parameters = copy.deepcopy(self._acquisition_parameters)\n\n # Sample with lims information, use values from lims\n # to set the data path. Or has a specific user group set.\n if sample_data_model.lims_id != -1:\n (data_directory, proc_directory) = self.get_default_directory(tree_item)\n self._path_template.directory = data_directory\n self._path_template.process_directory = proc_directory\n self._path_template.base_prefix = self.get_default_prefix(sample_data_model)\n elif self._session_hwobj.get_group_name() != '':\n base_dir = self._session_hwobj.get_base_image_directory()\n # Update with group name as long as user didn't specify\n # differnt path.\n if base_dir == self._path_template.directory:\n (data_directory, proc_directory) = self.get_default_directory()\n self._path_template.directory = data_directory\n self._path_template.process_directory = proc_directory\n self._path_template.base_prefix = self.get_default_prefix()\n\n # Get the next available run number at this level of the model.\n self._path_template.run_number = self._beamline_setup_hwobj.queue_model_hwobj.\\\n get_next_run_number(self._path_template)\n\n #Update energy transmission and resolution\n if self._acq_widget:\n self._update_etr()\n sample_data_model = sample_item.get_model()\n energy_scan_result = sample_data_model.crystals[0].energy_scan_result\n self._acq_widget.set_energies(energy_scan_result)\n self._acq_widget.update_data_model(self._acquisition_parameters,\n self._path_template)\n# self.get_acquisition_widget().use_osc_start(False) #JN 20140829, disabled so the old values can be kept\n\n if self._data_path_widget:\n self._data_path_widget.update_data_model(self._path_template)\n\n self.setDisabled(False)\n\n elif isinstance(tree_item, queue_item.DataCollectionGroupQueueItem):\n self.setDisabled(True)\n\n def _update_etr(self):\n energy = self._beamline_setup_hwobj._get_energy()\n transmission = self._beamline_setup_hwobj._get_transmission()\n resolution = self._beamline_setup_hwobj._get_resolution()\n \n self._acquisition_parameters.energy = energy\n self._acquisition_parameters.transmission = transmission\n self._acquisition_parameters.resolution = resolution\n\n def multiple_item_selection(self, tree_items):\n tree_item = tree_items[0]\n \n if isinstance(tree_item, queue_item.SampleQueueItem):\n sample_data_model = tree_item.get_model()\n self._path_template = copy.deepcopy(self._path_template)\n self._acquisition_parameters = copy.deepcopy(self._acquisition_parameters)\n\n # Sample with lims information, use values from lims\n # to set the data path.\n (data_directory, proc_directory) = self.get_default_directory(sub_dir = '') \n self._path_template.directory = data_directory\n self._path_template.process_directory = proc_directory\n self._path_template.base_prefix = self.get_default_prefix(generic_name = True)\n\n # Get the next available run number at this level of the model.\n self._path_template.run_number = self._beamline_setup_hwobj.queue_model_hwobj.\\\n get_next_run_number(self._path_template)\n\n #Update energy transmission and resolution\n if self._acq_widget:\n self._update_etr()\n energy_scan_result = sample_data_model.crystals[0].energy_scan_result\n self._acq_widget.set_energies(energy_scan_result)\n self._acq_widget.update_data_model(self._acquisition_parameters,\n self._path_template)\n# self.get_acquisition_widget().use_osc_start(False) #JN 20140829, disabled so the old value can be kept\n\n if self._data_path_widget:\n self._data_path_widget.update_data_model(self._path_template)\n\n self.setDisabled(False)\n\n # Called by the owning widget (task_toolbox_widget) when\n # one or several centred positions are selected.\n def centred_position_selection(self, positions):\n self._selected_positions = positions\n\n if len(self._current_selected_items) == 1 and len(positions) == 1:\n item = self._current_selected_items[0]\n pos = positions[0]\n\n if isinstance(pos, shape_history.Point):\n if self._acq_widget and isinstance(item, queue_item.TaskQueueItem):\n cpos = pos.get_centred_positions()[0]\n snapshot = self._shape_history.get_snapshot([pos.qub_point])\n cpos.snapshot_image = snapshot \n self._acquisition_parameters.centred_position = cpos\n\n # Should be called by the object that calls create_task,\n # and add_task.\n def approve_creation(self):\n result = True\n \n path_conflict = self._beamline_setup_hwobj.queue_model_hwobj.\\\n check_for_path_collisions(self._path_template)\n\n if path_conflict:\n logging.getLogger(\"user_level_log\").\\\n error('The current path settings will overwrite data' +\\\n ' from another task. Correct the problem before adding to queue')\n result = False\n\n return result\n \n # Called by the owning widget (task_toolbox_widget) to create\n # a task. When a task_node is selected.\n def create_task(self, sample, shape):\n (tasks, sc) = ([], None)\n \n try: \n sample_is_mounted = self._beamline_setup_hwobj.sample_changer_hwobj.\\\n getLoadedSample().getCoords() == sample.location\n\n except AttributeError:\n sample_is_mounted = False\n\n dm = self._beamline_setup_hwobj.diffractometer_hwobj\n fully_automatic = (not dm.user_confirms_centring)\n\n free_pin_mode = sample.free_pin_mode\n temp_tasks = self._create_task(sample, shape)\n\n if (not fully_automatic):\n if ((not free_pin_mode) and (not sample_is_mounted) or (not shape)):\n # No centred positions selected, or selected sample not\n # mounted create sample centring task.\n\n # Check if the tasks requires centring, assumes that all\n # the \"sub tasks\" has the same centring requirements.\n if temp_tasks[0].requires_centring():\n sc = queue_model_objects.SampleCentring('sample-centring')\n tasks.append(sc)\n\n for task in temp_tasks:\n if sc:\n sc.add_task(task)\n tasks.append(task)\n\n return tasks\n\n @abc.abstractmethod\n def _create_task(self, task_node, shape):\n pass\n","sub_path":"Bricks/widgets/create_task_base.py","file_name":"create_task_base.py","file_ext":"py","file_size_in_byte":17493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"213588633","text":"class Solution(object):\n def removeElement(self, nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n length=len(nums)\n ins=0\n pointer =0\n while pointer < len(nums):\n if nums[pointer] !=val:\n pointer+=1\n else:\n del nums[pointer]\n ins+=1\n return length-ins","sub_path":"Easy/27. Remove Element.py","file_name":"27. Remove Element.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"620095888","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom pathlib import Path\r\nimport xlsxwriter\r\n\r\nconditions_list = []\r\n\r\n\r\ndef askConditions():\r\n while True:\r\n try:\r\n conditions = input(\"Please enter the conditions in your study, separated by commas (e.g. Controls, Patients).\\n\")\r\n conditions_split = [w.strip() for w in conditions.split(',')]\r\n global conditions_list\r\n conditions_list = list(map(str, conditions_split))\r\n break\r\n except:\r\n print(\"\\nYour input is not recognized. Please try again.\")\r\n conditions = input(\"\\nPlease enter the conditions in your study, separated by commas (e.g. Controls, Patients).\\n\")\r\n conditions_split = conditions.split(\",\")\r\n conditions_list = list(map(str, conditions_split))\r\n\r\n\r\naskConditions()\r\n\r\n# Request user to input number of each condition in their experiment to process data appropriately\r\nnum_each_condition = []\r\nfor con in range(len(conditions_list)):\r\n while True:\r\n try:\r\n number_entered = int(input(\"How many subjects are in the condition '%s' in your experiment?\\n\" % conditions_list[con]))\r\n num_each_condition.append(number_entered)\r\n break\r\n except ValueError:\r\n print(\"Not an integer! Try again.\")\r\n continue\r\n\r\nif all(subj == 0 for subj in num_each_condition):\r\n exit(1)\r\n\r\n\r\n# class that allows iteration over all objects of a class\r\nclass IterSubject(type):\r\n def __iter__(cls):\r\n return iter(cls._allSubjects)\r\n\r\n\r\n# class that defines a generic Subject\r\nclass Subject(metaclass=IterSubject):\r\n _allSubjects = []\r\n\r\n def __init__(self, subjectID): # initializer (requires Subject ID as an argument when creating an object)\r\n self._allSubjects.append(self)\r\n self.subjectID = subjectID\r\n\r\n def setData(self, file): # function to pass in name of text file and load data into array\r\n with open(file) as f:\r\n for i,l in enumerate(f):\r\n pass\r\n r = i+1\r\n c = f.readline()\r\n cs = [int(n) for n in c.split()]\r\n\r\n self.data = np.zeros(r,cs)\r\n\r\n self.data = np.loadtxt(file)\r\n backwards = str(file)[::-1]\r\n backwards = backwards.split('\\\\')\r\n forwards = backwards[0][::-1]\r\n forwards = forwards.split('.')\r\n self.name = forwards[0]\r\n\r\n def getData(self): # function that return array\r\n return self.data\r\n\r\n def printData(self): # function to print array\r\n print(self.data)\r\n\r\n def printID(self): # function print Subject ID\r\n print(self.subjectID)\r\n\r\n def getName(self):\r\n return(self.name)\r\n\r\n def trimData(self, new_size_x, new_size_y):\r\n temp = np.copy(self.data)\r\n self.data = temp[:new_size_x,:new_size_y]\r\n\r\n\r\ndata_folder = Path(r\"//utdfs01/UTD/Dept/BBSResearch/LabCLINT/SandBox/Python toolbox project\")\r\n\r\nsubjects_of_each_condition = []\r\nfor each_condition in range(len(conditions_list)):\r\n subjects_of_each_condition.append([])\r\n # list to store a specific group of instances of class Subject\r\n print(\"\\nData entry for %s:\" % conditions_list[each_condition])\r\n for x in range(\r\n num_each_condition[each_condition]): # loop through number of Controls that user inputted and get data files for each Control subject\r\n file_Location = input(\r\n \"\\nPlease enter the path to the data file for Subject %s in '%s' in the folder 'Python toolbox project': \\n\" % ((str)(x + 1),conditions_list[each_condition])) # request user to input path to data file; example can be found hard-coded below\r\n fileName = data_folder / file_Location # compile full path of data file\r\n subjects_of_each_condition[each_condition].append(\r\n Subject(\"%s %s\" % (conditions_list[each_condition], (str)(x + 1)))) # Create a new instance of class Subject and add it to Controls list\r\n while True:\r\n try:\r\n subjects_of_each_condition[each_condition][x].setData(fileName) # read data from corresponding data file and store in array for that Control\r\n break\r\n except:\r\n print(\"\\nFile not found in the specified path: %s\" % fileName)\r\n file_Location = input(\r\n \"\\nPlease try again. \\n\") # request user to input path to data file; example can be found hard-coded below\r\n fileName = data_folder / file_Location # compile full path of data file\r\n\r\n# Control1 \"Sample data/Controls/avv_045_restZT_data-sLorRoiLog.txt\"\r\n# Control2 \"Sample data/Controls/cak_011_restZT_data-sLorRoiLog.txt\"\r\n# Control3 \"Sample Data/Controls/nck_020_restZT_data-sLorRoiLog.txt\"\r\n# Control4 \"Sample Data/Controls/oxs_036_restZT_data-sLorRoiLog.txt\"\r\n# Control5 \"Sample Data/Controls/sew_023_restZT_data-sLorRoiLog.txt\"\r\n# Control6 \"Sample Data/Controls/uxk_001_restZT_data-sLorRoiLog.txt\"\r\n\r\n# Patient1 \"Sample data/Patients/ark_016_restZT_data-sLorRoiLog.txt\"\r\n# Patient2 \"Sample data/Patients/ctc_007_restZT_data-sLorRoiLog.txt\"\r\n# Patient3 \"Sample data/Patients/cxt_019_restZT_data-sLorRoiLog.txt\"\r\n# Patient4 \"Sample data/Patients/kjs_037_restZT_data-sLorRoiLog.txt\"\r\n# Patient5 \"Sample data/Patients/kxm_047_restZT_data-sLorRoiLog.txt\"\r\n# Patient6 \"Sample data/Patients/mxn_002_restZT_data-sLorRoiLog.txt\"\r\n# Patient7 \"Sample data/Patients/scj_009_restZT_data-sLorRoiLog.txt\"\r\n\r\n\r\n# list to hold the user's desired frequencies, in the order entered\r\nchosenFrequencies = []\r\n\r\n\r\n# function to take user input for frequency bands used in their experiment\r\ndef ask_for_frequencies():\r\n print(\r\n \"\\nWhat frequency bands are you evaluating in your data? Please enter them in the order in which they are present in the input files. Enter all frequency bands in one line (e.g. ABCGK).\")\r\n\r\n # function to return chosen frequency band, which can then be added to the chosenFrequencies list\r\n def frequencyChoice(c):\r\n switcher = {\r\n \"A\": 'Delta',\r\n \"a\": 'Delta',\r\n \"B\": 'Theta',\r\n \"b\": 'Theta',\r\n \"C\": 'Alpha',\r\n \"c\": 'Alpha',\r\n \"D\": 'Alpha1',\r\n \"d\": 'Alpha1',\r\n \"E\": 'Alpha2',\r\n \"e\": 'Alpha2',\r\n \"F\": 'Alpha3',\r\n \"f\": 'Alpha3',\r\n \"G\": 'Beta',\r\n \"g\": 'Beta',\r\n \"H\": 'Beta1',\r\n \"h\": 'Beta1',\r\n \"I\": 'Beta2',\r\n \"i\": 'Beta2',\r\n \"J\": 'Beta3',\r\n \"j\": 'Beta3',\r\n \"K\": 'Gamma',\r\n \"k\": 'Gamma',\r\n \"L\": 'Low Gamma',\r\n \"l\": 'Low Gamma',\r\n \"M\": 'High Gamma',\r\n \"m\": 'High Gamma',\r\n \"N\": 'Mu',\r\n \"n\": 'Mu',\r\n }\r\n return switcher.get(c, 0)\r\n\r\n # variable to process input validation\r\n valid = True\r\n\r\n # function to display all frequency bands to user and request selection of desired bands\r\n def inputFreq():\r\n choice = input(\"\"\"\r\n A: Delta\r\n B: Theta\r\n C: Alpha\r\n D: Alpha1\r\n E: Alpha2\r\n F: Alpha3\r\n G: Beta\r\n H: Beta1\r\n I: Beta2\r\n J: Beta3\r\n K: Gamma\r\n L: Low Gamma\r\n M: High Gamma\r\n N: Mu\"\"\"\r\n\r\n \"\\n\\n\\nPlease enter your desired bands: \\n\")\r\n return choice\r\n\r\n # list of all valid entries to query\r\n frequencyList = ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j',\r\n 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n']\r\n\r\n # parse inputted frequencies into an itemized list and add each frequency band to chosenFrequencies list\r\n c = list(inputFreq())\r\n for cv in range(len(c)):\r\n if c[cv] in frequencyList:\r\n valid = True\r\n else:\r\n valid = False\r\n\r\n # if input is invalid, continue requesting user to input valid frequencies until they do so\r\n while (not valid):\r\n print(\"\\nYou have entered invalid frequencies. Please try again.\\n\")\r\n c = list(inputFreq())\r\n for cv in range(len(c)):\r\n if c[cv] in frequencyList:\r\n valid = True\r\n else:\r\n valid = False\r\n\r\n # add selected frequency band names into chosenFrequencies list\r\n for bands in range(len(c)):\r\n chosenFrequencies.append(frequencyChoice(c[bands]))\r\n\r\n# run the function to get frequencies from user\r\nask_for_frequencies()\r\nprint(\"\\nThese are the frequency bands chosen, in order:\", chosenFrequencies)\r\n\r\n#Making an excel file and sorting data\r\ndef export_to_excel():\r\n data_organized = []\r\n sheets = []\r\n for organized in range(len(conditions_list)):\r\n data_organized.append(xlsxwriter.Workbook(\"%s_Organized.xlsx\" % conditions_list[organized]))\r\n sheets.append([])\r\n for number_of_freq in range(len(chosenFrequencies)):\r\n for each_condition in range(len(conditions_list)):\r\n sheets[each_condition].append(data_organized[each_condition].add_worksheet(str(chosenFrequencies[number_of_freq])))\r\n for row in range(num_each_condition[each_condition]):\r\n sheets[each_condition][number_of_freq].write(row+1, 0, subjects_of_each_condition[each_condition][row].getName())\r\n for column in range(np.size(subjects_of_each_condition[each_condition][row].getData(), 1)):\r\n if row == 0:\r\n sheets[each_condition][number_of_freq].write(row, column + 1,\r\n 'ROI %s' % str(column + 1))\r\n sheets[each_condition][number_of_freq].write(row + 1, column + 1,\r\n subjects_of_each_condition[each_condition][row].getData()[\r\n number_of_freq, column])\r\n for organized in range(len(conditions_list)):\r\n data_organized[organized].close()\r\n print(\"\\nYour data has been organized for each condition. Each frequency band is its own sheet and the data is sorted into Subjects x ROIs. The files have been saved in the working directory.\")\r\n\r\nwhile True:\r\n try:\r\n export_to_excel()\r\n break\r\n except IndexError:\r\n chosenFrequencies = []\r\n print(\"\\nYour data doesn't have this many frequencies. Please try again.\")\r\n ask_for_frequencies()\r\n print(chosenFrequencies)\r\n except PermissionError:\r\n print(\"\\nThe file you're attempting to create already exists and is currently in use. Please close it and try again.\")\r\n exit(1)\r\n\r\n#Making the graph\r\nfor each_condition in range(len(conditions_list)):\r\n for trim in range(num_each_condition[each_condition]):\r\n subjects_of_each_condition[each_condition][trim].trimData(len(chosenFrequencies), np.size(subjects_of_each_condition[each_condition][trim].getData(),1))\r\n\r\nsumMatrices = []\r\nfor each_condition in range(len(conditions_list)):\r\n sumMatrices.append(np.zeros((len(chosenFrequencies), np.size(subjects_of_each_condition[each_condition][0].getData(),1))))\r\n for subjects in subjects_of_each_condition[each_condition]:\r\n sumMatrices[each_condition] += np.array(subjects.getData())\r\n\r\naverageMatrices = []\r\nfor matrix in range(len(sumMatrices)):\r\n averageMatrices.append(sumMatrices[matrix] / num_each_condition[matrix])\r\n list(averageMatrices[matrix])\r\n averageMatrices[matrix].tolist()\r\n\r\ngap = 0.4\r\n\r\nprint_graphs = input(\"\\nDo you want any of the data graphed? Enter Y for yes and N for no.\\n\")\r\nvalid_graph_inputs = {'Y', 'y', 'N', 'n'}\r\nwhile print_graphs not in valid_graph_inputs:\r\n print_graphs = input(\"That is not a valid response. Please try again. Enter Y for yes and N for no.\")\r\n\r\ndef makeGraphs():\r\n ROIs = input(\"\\nPlease enter the numbers of the ROIs that you wanted graphed, in order, separated by commas.\\n\")\r\n ROIs_split = ROIs.split(\",\")\r\n num_of_graphs = list(map(int, ROIs_split))\r\n\r\n valid_num_of_graphs = True\r\n for each_condition in range(len(conditions_list)):\r\n if len(num_of_graphs) > np.size(subjects_of_each_condition[each_condition][0].getData(),1):\r\n valid_num_of_graphs = False\r\n\r\n if valid_num_of_graphs:\r\n for graphs in range(len(num_of_graphs)):\r\n plotMatrices = []\r\n for each_condition in range(len(conditions_list)):\r\n plotMatrices.append([0] * len(chosenFrequencies))\r\n for x in range(len(chosenFrequencies)):\r\n plotMatrices[each_condition][x] = averageMatrices[each_condition][x, num_of_graphs[graphs]-1] \r\n y_pos = np.arange(len(chosenFrequencies))\r\n plt.figure(graphs + 1)\r\n for plot in range(len(plotMatrices)):\r\n plt.bar(y_pos + (gap * plot), plotMatrices[plot], align='center', alpha=0.5, width=0.4)\r\n plt.xticks(y_pos + (gap / len(plotMatrices)), chosenFrequencies)\r\n plt.ylabel('Average')\r\n plt.title('ROI %d' % num_of_graphs[graphs])\r\n plt.savefig('ROI %d.png' % num_of_graphs[graphs])\r\n print(\"\\nYour graphs have been created and saved successfully.\")\r\n else:\r\n raise Exception\r\n\r\n\r\nif print_graphs == 'Y' or print_graphs == 'y':\r\n while True:\r\n try:\r\n makeGraphs()\r\n break\r\n except (Exception, IndexError):\r\n num_of_graphs = []\r\n print(\"\\nYou don't have this many ROIs in your data. Please try again.\")\r\n","sub_path":"Old Versions/Average3.py","file_name":"Average3.py","file_ext":"py","file_size_in_byte":13888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"588989949","text":"\"\"\"\nSQS Consumer to create Gitlab merge requests.\n\"\"\"\n\nimport json\nimport logging\n\nimport reconcile.queries as queries\n\nfrom reconcile.utils import mr\nfrom reconcile.utils.sqs_gateway import SQSGateway\nfrom reconcile.utils.gitlab_api import GitLabApi\n\n\nQONTRACT_INTEGRATION = 'gitlab-mr-sqs-consumer'\n\n\ndef run(dry_run, gitlab_project_id):\n settings = queries.get_app_interface_settings()\n\n accounts = queries.get_aws_accounts()\n sqs_cli = SQSGateway(accounts, settings=settings)\n\n instance = queries.get_gitlab_instance()\n saas_files = queries.get_saas_files_minimal(v1=True, v2=True)\n gitlab_cli = GitLabApi(instance, project_id=gitlab_project_id,\n settings=settings, saas_files=saas_files)\n\n while True:\n messages = sqs_cli.receive_messages()\n logging.info('received %s messages', len(messages))\n\n if not messages:\n break\n\n for message in messages:\n # Let's first delete all the message we received,\n # otherwise they will come back in 30s.\n receipt_handle = message[0]\n sqs_cli.delete_message(str(receipt_handle))\n\n for message in messages:\n # Time to process the messages. Any failure here is not\n # critical, even though we already deleted the messaged,\n # since the producers will keep re-sending the message\n # until the MR gets merged to app-interface\n receipt_handle, body = message[0], message[1]\n logging.info('received message %s with body %s',\n receipt_handle[:6], json.dumps(body))\n\n if not dry_run:\n merge_request = mr.init_from_sqs_message(body)\n merge_request.submit_to_gitlab(gitlab_cli=gitlab_cli)\n","sub_path":"reconcile/gitlab_mr_sqs_consumer.py","file_name":"gitlab_mr_sqs_consumer.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"596878301","text":"# -*- coding: utf-8 -*-\n# 第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?\n\nimport random, string\n\n#随机生成激活码\ndef randomActivationCode(leng):\n str = string.ascii_letters + string.digits\n createStr = ''\n for i in range(leng):\n # randomStr = str[random.randint(0, len(str))]\n randomStr = random.choice(str)\n createStr += randomStr\n return createStr\n\n#随机生成num个激活码\ndef activationCodeCount(num, leng):\n for i in range(num):\n yield randomActivationCode(leng)\n\nfor i in activationCodeCount(2, 16):\n print(i)","sub_path":"0007/0001.py","file_name":"0001.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"237358358","text":"# 설치한 OpenCV 패키지 불러오기\nimport cv2\n\n# 인식률을 높이기 위한 전처리\ndef preprocessing():\n\n # 분석하기 위한 이미지 불러오기\n image = cv2.imread(\"image/my_face.jpg\", cv2.IMREAD_COLOR)\n\n # 이미지가 존재하지 않으면, 에러 반환\n if image is None:\n return None, None\n\n # 이미지 크기 사이즈 변경하기\n image = cv2.resize(image, (700, 700))\n\n # 흑백사진으로 변경\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # 변환한 흑백사진으로부터 히스토그램 평활화\n gray = cv2.equalizeHist(gray)\n\n return image, gray\n\n# 학습된 얼굴 정면검출기 사용하기\nface_cascade = cv2.CascadeClassifier(\"data/haarcascade_frontalface_alt2.xml\")\n\n# 인식률을 높이기 위한 전처리 함수 호출\nimage, gray = preprocessing() # 전처리\n\nif image is None:\n raise Exception(\"영상 파일 읽기 에러\")\n\n# 이미지 내 모든 얼굴을 인식\n# 얼굴 검출 수행(정확도 높이는 방법의 아래 파라미터를 조절함)\n# 얼굴 검출은 히스토그램 평활화한 이미지 사용\n# scaleFactor : 1.1\n# minNeighbors : 인근 유사 픽셀 발견 비율이 2번 이상\n# flags : 0 => 더이상 사용하지 않는 인자값\n# 분석할 이미지의 최소 크기 : 가로 100, 세로 100\nfaces = face_cascade.detectMultiScale(gray, 1.1, 2, 0, (100, 100))\n\n# 얼굴이 검출되었다면,\nif faces.any():\n\n # 얼굴 위치 값을 가져오기\n x, y, w, h = faces[0]\n\n # 원본 이미지로부터 얼굴 영역 가져오기\n face_image = image[y:y + h, x:x + w]\n\n # 모자이크 비율(픽셀크기 증가로 모자이크 만들기)\n mosaic_rate = 30\n\n # 얼굴 영역의 픽셀을 mosaic_rate에 따라 나눠서 픽셀 확대\n face_image = cv2.resize(face_image, (w // mosaic_rate, h // mosaic_rate))\n\n # 확대한 얼굴 이미지(픽셀)을 얼굴 크기에 덮어쓰기\n face_image = cv2.resize(face_image, (w, h), interpolation=cv2.INTER_AREA)\n\n # 원본이미지에 모자이크 처리한 얼굴 이미지 붙이기\n image[y:y + h, x:x + w] = face_image\n\n # 모자이크 처리된 이미지 파일 생성하기\n cv2.imwrite(\"result/my_image_mosaic.jpg\", image)\n\n # 모자이크 처리된 이미지 보여주기\n cv2.imshow(\"mosaic_image\", cv2.imread(\"result/my_image_mosaic.jpg\", cv2.IMREAD_COLOR))\n\nelse:\n print(\"얼굴 미검출\")\n\n# 입력받는 것 대기하기, 작성 하지 않으면 결과창이 바로 닫힘\ncv2.waitKey(0)","sub_path":"OpenCV/face_mosaic.pydetect.py","file_name":"face_mosaic.pydetect.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"281989191","text":"import matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FormatStrFormatter\nimport numpy as np\nimport scipy\nfrom scipy.integrate import odeint\nimport sys; sys.path.insert(0, '../../'); import PEUQSE as PEUQSE\nimport PEUQSE.UserInput as UserInput\n\nif __name__ == \"__main__\":\n \n observed_data_Filename = 'ExperimentalDataAcetaldehydeTPDCeO2111MullinsTruncatedConstantErrors.csv'\n \n import processing_function_mem_reactor_km_only as fun\n\n UserInput.responses['responses_observed_uncertainties'] = [0.04]\n \n UserInput.simulated_response_plot_settings['x_label'] = r'$reactor outlet$'\n UserInput.simulated_response_plot_settings['y_label'] = r'$ln(C_A)i$'\n #UserInput.simulated_response_plot_settings['y_range'] = [0.00, 0.025] #optional.\n UserInput.simulated_response_plot_settings['figure_name'] = 'Posterior_Example12' #This creates the filename, also.\n\n UserInput.model['parameterNamesAndMathTypeExpressionsDict'] = {'delta_G':r'$\\deltaG (eV)$'}\n UserInput.model['InputParameterPriorValues'] = [2e3] # eV\n UserInput.model['InputParametersPriorValuesUncertainties'] = [1e3] #If user wants to use a prior with covariance, then this must be a 2D array/ list. To assume no covariance, a 1D This is a standard deviation!\n UserInput.model['InputParameterInitialGuess'] = [3e3] #This is where the mcmc chain will start.\n #InputParameterInitialValues = [41.5, 41.5, 13.0, 13.0, 0.1, 0.1] # Ea1_mean, Ea2_mean, log_A1_mean, log_A2_mean, gamma_1_mean, gamma_2_mean \n \n #InputParametersInitialValuesUncertainties = [200, 200, 13, 13, 0.1, 0.1] #If user wants to use a prior with covariance, then this must be a 2D array/ list. To assume no covariance, a 1D array can be used.\n UserInput.model['simulateByInputParametersOnlyFunction'] = fun.mem_reactor #This must simulate with *only* the parameters listed above, and no other arguments.\n #UserInput.model['simulationOutputProcessingFunction'] = processing_functions_tpd_odeint.no_log_wrapper_func #Optional: a function to process what comes out of the simulation Function and then return an observable vector.\n \n UserInput.parameter_estimation_settings['scaling_uncertainties_type'] = \"1e5\"\n UserInput.parameter_estimation_settings['verbose'] = False \n UserInput.parameter_estimation_settings['mcmc_checkPointFrequency'] = 100\n \n UserInput.parameter_estimation_settings['mcmc_mode'] = 'unbiased'\n UserInput.parameter_estimation_settings['mcmc_random_seed'] = 0 #Normally set to None so that mcmc is set to be random. To get the same results repeatedly, such as for testing purposes, set the random seed to 0 or another integer for testing purposes.\n UserInput.parameter_estimation_settings['mcmc_burn_in'] = 10 #normally 1000 \n UserInput.parameter_estimation_settings['mcmc_length'] = 100 #normally 10000\n UserInput.parameter_estimation_settings['mcmc_relative_step_length'] = 0.05\n UserInput.parameter_estimation_settings['mcmc_modulate_accept_probability'] = 0 #Default value of 0. Changing this value sharpens or flattens the posterior. A value greater than 1 flattens the posterior by accepting low values more often. It can be useful when greater sampling is more important than accuracy. One way of using this feature is to try with a value of 0, then with the value equal to the number of priors for comparison, and then to gradually decrease this number as low as is useful (to minimize distortion of the result). A downside of changing changing this variable to greater than 1 is that it slows the the ascent to the maximum of the prior, so there is a balance in using it. In contrast, numbers increasingly less than one (such as 0.90 or 0.10) will speed up the ascent to the maximum of the posterior, but will also result in fewer points being retained.\n UserInput.parameter_estimation_settings['mcmc_info_gain_cutoff'] = 1E-4\n \n UserInput.contour_plot_settings['parameter_pairs'] = [[0, 0]]\n UserInput.contour_plot_settings['contours_normalized'] = False\n UserInput.contour_plot_settings['figure_name'] = 'Mumpce_contour_plot_mem_reactor'\n #After making the UserInput, now we make a 'parameter_estimation' object from it.\n global T\n global volume\n global F0\n global P0\n global R\n global kB\n global k_1\n global k_minus_1\n kB = 8.61733035E-5 #eV/K\\n\n k_1 = 1e2\n k_minus_1 = 1\n k_m = 3e3\n F0 = np.array([5, 0])\n temperatures = np.linspace(298.15,698.15,5)\n volumes = np.linspace(100,1100,5)\n\n flow_rates_a=[]\n for v in volumes:\n for t in temperatures:\n sol = odeint(fun.cmr, F0, np.linspace(0,v,50), args=(k_1,k_minus_1,k_m,t))\n conc_sol_last=sol[-1,0].T\n flow_rates_a.append(conc_sol_last)\n\n #fig = plt.figure(figsize = (5,5))\n #ax = fig.add_subplot(111, projection='3d')\n fig1,ax1 = plt.subplots(figsize=(5,5))\n TT, V = np.meshgrid(temperatures, volumes)\n flow_rates_a=np.asarray(flow_rates_a)\n FRA = flow_rates_a.reshape(TT.shape)\n surf = ax1.pcolor(TT,V,FRA,cmap=matplotlib.cm.coolwarm)\n ax1.set_xlabel('Temperature')\n ax1.set_ylabel('Volume')\n #ax1.set_zlabel('Flow Rate')\n ax1.set_title('Surface Plot of F_A')\n fig1.colorbar(surf, shrink=0.5, aspect=5)\n fig1.savefig('synthetic_observables.png',dpi=220)\n\n fun.k_1 = 1e2\n fun.k_minus_1 = 1\n prior = np.random.normal(2e3,1e3,10000)\n info_gains=[]\n PE_object_list = []\n for v in volumes:\n for t in temperatures:\n sol = odeint(fun.cmr, F0, np.linspace(0,v,50), args=(k_1,k_minus_1,k_m,t))\n conc_sol_last=sol[-1,0].T\n print('conc_sol_last',conc_sol_last)\n UserInput.responses['responses_observed'] = [conc_sol_last]\n PE_object_list.append(PEUQSE.parameter_estimation(UserInput))\n fun.T = t\n fun.volume = v\n [map_parameter_set, muap_parameter_set, stdap_parameter_set, evidence, info_gain, samples, logP] = PE_object_list[-1].doMetropolisHastings()\n info_gains.append(info_gain)\n fig, ax = plt.subplots()\n (density0,bins0,pathces0)=ax.hist([prior,PE_object_list[-1].post_burn_in_samples.flatten()],bins=100,label=['prior','posterior'],density=True)\n ax.legend()\n ax.set_ylabel('Probability density')\n ax.set_title('Prior and Posterior Density Plot at T = {} (K) volume = {} cm^3'.format(str(t),str(v)))\n fig.savefig('km_only_figures/prior_and_posterior_histogram_T_{}_V_{}.png'.format(str(t),str(v)), dpi=300)\n fig,ax = plt.subplots(figsize=(5,5))\n #ax = fig.add_subplot(111, projection='3d')\n T, V = np.meshgrid(temperatures, volumes)\n info_gains=np.asarray(info_gains)\n IG = info_gains.reshape(T.shape)\n surf = ax.pcolor(T,V,IG,cmap=matplotlib.cm.coolwarm)\n\n ax.set_xlabel('Temperature')\n ax.set_ylabel('Volume')\n #ax.set_zlabel('Information Gain')\n ax.set_xticks(temperatures)\n ax.xaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n ax.set_title('Information Gain Surface')\n fig.colorbar(surf, shrink=0.5, aspect=5) \n fig.savefig('info_gain_surface_mem_reactor.png', dpi=220)\n","sub_path":"Examples/Example12withScaling1E5/runfile_Example12_km_only_fixed_scaling.py","file_name":"runfile_Example12_km_only_fixed_scaling.py","file_ext":"py","file_size_in_byte":7175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"390030604","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/Mardix/Dropbox/Projects/Python/Flasik/flasik/ext/flasik_db.py\n# Compiled at: 2019-08-24 12:05:10\n\"\"\"\nActive Alchemy with some custom types\n\nJust like sqlalchemy_utils, this module contains some custom types to\nsave in the db\n\"\"\"\nimport active_alchemy\nfrom sqlalchemy.engine.url import make_url as sa_make_url\nimport sqlalchemy_utils as sa_utils, flask_cloudy, redis\n\nclass FlasikDB(active_alchemy.ActiveAlchemy):\n \"\"\"\n A custom ActiveAlchemy wrapper which defers the connection\n \"\"\"\n\n def __init__(self):\n self.Model = active_alchemy.declarative_base(cls=active_alchemy.Model, name='Model')\n self.BaseModel = active_alchemy.declarative_base(cls=active_alchemy.BaseModel, name='BaseModel')\n self._initialized = False\n self._IS_OK_ = False\n self.redis = {}\n\n def connect__(self, uri, app):\n self.uri = uri\n self.info = sa_make_url(uri)\n self.options = self._cleanup_options(echo=False, pool_size=None, pool_timeout=None, pool_recycle=None, convert_unicode=True)\n self._initialized = True\n self._IS_OK_ = True\n self.connector = None\n self._engine_lock = active_alchemy.threading.Lock()\n self.session = active_alchemy._create_scoped_session(self, query_cls=active_alchemy.BaseQuery)\n self.Model.db, self.BaseModel.db = self, self\n self.Model._query, self.BaseModel._query = self.session.query, self.session.query\n self.init_app(app)\n active_alchemy._include_sqlalchemy(self)\n self.StorageObjectType = StorageObjectType\n return\n\n def connect_redis(self, name, url=None, decode_responses=True, **kwargs):\n \"\"\"\n To connect to a Redis instance and attach it to db.redis \n Example: \n\n # Establish the connection\n db.connect_redis('cache', 'https://u:p@url/db')\n \n # Access it\n db.redis.cache.set('key', 'value')\n \"\"\"\n connect = redis.from_url(url, decode_responses=decode_responses, **kwargs)\n setattr(self.redis, name, connect)\n return connect\n\n\nclass StorageObjectType(sa_utils.JSONType):\n \"\"\"\n A type to store flask_cloudy Storage Object Type:\n -> https://github.com/mardix/flask-cloudy\n\n It provides a convenient way to store object and retrieve it as you would\n in the Flasik's storage.\n\n By default it will hold basic info such as name and url, size, extension\n Querying object.url, will not query the storage but use the default data\n this way it prevents certain overhead when dealing with multiple items\n\n Once an object is not found, it will try to connect to the storage and pull\n the file data\n\n If object is not found, it will return None.\n\n Example:\n from flasik import db\n\n class Image(db.Model):\n name = db.Column(db.String(255))\n image = db.Column(db.StorageObjectType)\n ...\n\n # Setting the object\n file = request.files.get(\"file\")\n if file:\n upload = storage.upload(file)\n if upload is not None:\n new_img = Image.create(name=\"New Upload\", image=upload)\n\n # Getting the object. By default, most keys are cached,\n # if not found it will load from the storage\n\n img = Image.get(1234)\n if img.image:\n url = img.image.url\n size = img.image.size\n full_url = img.image.full_url\n download_url = img.image.download_url\n\n # Force loading of the storage\n img.image.from_storage(my_other_storage)\n\n img.image.url (will get it from my_other_storage)\n\n \"\"\"\n DEFAULT_KEYS = [\n 'name', 'size', 'hash', 'url', 'full_url',\n 'extension', 'type', 'path', 'provider_name']\n\n def process_bind_param(self, obj, dialect):\n \"\"\"Get a flask_cloudy.Object and save it as a dict\"\"\"\n value = obj or {}\n if isinstance(obj, flask_cloudy.Object):\n value = {}\n for k in self.DEFAULT_KEYS:\n value[k] = getattr(obj, k)\n\n return super(self.__class__, self).process_bind_param(value, dialect)\n\n def process_result_value(self, value, dialect):\n value = super(self.__class__, self).process_result_value(value, dialect)\n if value:\n return StorageObject(value)\n else:\n return\n\n\nclass StorageObject(dict):\n \"\"\"\n This object will be loaded when querying the table\n It also extends dict so it can json serialized when being copied\n \"\"\"\n\n def __init__(self, data):\n \"\"\"\n :param data: dict\n name (required)\n ...\n \"\"\"\n self._storage_obj = None\n self._storage_loaded = False\n self._data = data\n super(self.__class__, self).__init__(data)\n return\n\n def __getattr__(self, item):\n if item in self._data and not self._storage_loaded:\n return self._data.get(item)\n if not self._storage_loaded:\n from flasik.ext import storage\n self.from_storage(storage)\n return getattr(self._storage_obj, item)\n\n def from_storage(self, storage):\n \"\"\"\n To use a different storage\n :param storage: flask_cloudy.Storage instance\n \"\"\"\n self._storage_obj = storage.get(self._data['name'])\n self._storage_loaded = True","sub_path":"pycfiles/flask_assembly-0.0.0-py2-none-any/flasik_db.py","file_name":"flasik_db.py","file_ext":"py","file_size_in_byte":5529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"155531652","text":"from math import sqrt\n\nprimes = [2,3,5,7]\n\ndef is_prime(num):\n for prime in primes:\n if prime > sqrt(num):\n break\n if num % prime == 0:\n return False\n return True\n\nmi = 11\nma = 100\nfor i in range(3):\n counter = 0\n for j in range(mi,ma):\n if is_prime(j):\n primes += [j]\n if primes[-1] - primes[-4] == 8:\n counter += 1\n if counter % 500 == 0:\n print([primes[-4], primes[-3], primes[-2], primes[-1]])\n mi, ma = ma + 1, ma ** 2\n\n","sub_path":"prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"116581512","text":"\"\"\"We lunch, recup all data and stock it into database.\r\nFor that we call all files.\"\"\"\r\n\r\nimport datetime\r\nimport psycopg2\r\n\r\n\r\nfrom angrais import periode_angrais\r\n\r\nfrom climat import saison\r\nfrom climat import recuperation_donnee_temperature\r\n\r\nfrom diesel import recup_tag\r\nfrom eruption import eruption\r\nfrom incendie import incendie\r\nfrom jour_nuit import nuit_jour\r\n\r\nfrom meteo import pression\r\nfrom meteo import vent\r\nfrom meteo import recuperation_donnee_meteo\r\n\r\nfrom particule import particule2\r\nfrom particule import france\r\nfrom particule import industrie\r\n\r\nfrom polenne import polenne\r\nfrom socio import habitant\r\n\r\nfrom trafique import trafique_circulation\r\nfrom trafique import heure_de_pointe\r\nfrom trafique import habitude\r\nfrom trafique import bouchons\r\nfrom trafique import activite_execptionnelle\r\n\r\nfrom CONFIG import DATABASE\r\nfrom CONFIG import USER\r\nfrom CONFIG import HOST\r\nfrom CONFIG import PASSWORD\r\n\r\ndef heure_jour_function():\r\n \"\"\"We define the current time day and hour for\r\n have a repair into the database\"\"\"\r\n\r\n date = datetime.datetime.now()\r\n jour = date.day\r\n mois = date.month\r\n annee = date.year\r\n\r\n heure = date.hour\r\n minute = date.minute\r\n\r\n jour = str(jour)+'_'+str(mois)+'_'+str(annee)\r\n heure = str(heure)+'_'+str(minute)\r\n\r\n return jour, heure\r\n\r\n\r\nHEURE_JOUR = heure_jour_function()\r\n\r\n\r\nliste = ['lyon', 'paris','marseille']\r\n#liste = ['marseille']\r\n#liste = ['lyon']\r\n#liste = ['paris']\r\n\r\n\r\nfor i in liste:\r\n\r\n print('TOUR: ', i)\r\n data_m = particule2(i)\r\n\r\n\r\n data_a = periode_angrais()\r\n print('période engrais ?', data_a)\r\n\r\n data_c = saison()\r\n print('saison : ', data_c)\r\n\r\n data_d = recup_tag()\r\n print('augmentation du prix barille de diesel, du d+ et du dollar : ',\r\n data_d)\r\n\r\n data_e = eruption()\r\n print('erruption cet semaine ? le :', data_e)\r\n\r\n data_g = nuit_jour()\r\n print('nous sommes en periode de :', data_g)\r\n\r\n data_r = trafique_circulation()\r\n print('aujourd\\'hui est il un départ routier ?', data_r)\r\n\r\n data_s = heure_de_pointe()\r\n print('est ce une heure de pointe ?', data_s)\r\n\r\n data_t = habitude()\r\n print('quel periode de la semaine ?', data_t)\r\n\r\n data_u = bouchons(i)\r\n print('a', i, 'il y a un', '', data_u, 'bouchon')\r\n\r\n data_v = activite_execptionnelle(i)\r\n print('a', i, 'il y a manif ou pas ?', data_v)\r\n\r\n data_q = habitant(i)\r\n print('population active de', i, 'de :', data_q)\r\n\r\n data_n = industrie(i)\r\n print(i, 'est dans une zone industrielle polluante ?', data_n)\r\n\r\n data_o = polenne(i)\r\n print('le taux de polenne a ', i, 'est : ', data_o)\r\n\r\n data_l = france(i)\r\n print(i, 'est', data_l, 'en france')\r\n\r\n data_h = recuperation_donnee_meteo(i)\r\n print('il fait', data_h, 'à', i)\r\n\r\n data_j = vent(i)\r\n print('le vent est :', data_j, 'a', i)\r\n\r\n data_k = pression(i)\r\n print('la pression est', data_k, 'a', i)\r\n\r\n data_b = recuperation_donnee_temperature(i)\r\n print('la température est dans une plage de: ', data_b)\r\n\r\n data_f = incendie(i)\r\n print('incendie a', i, 'ojd ?', data_f)\r\n\r\n\r\n\r\n #print('\\n')\r\n\r\n\r\n\r\n #We insert data into the database !\r\n conn = psycopg2.connect(database=DATABASE,\r\n user=USER,\r\n host=HOST,\r\n password=PASSWORD)\r\n cursor = conn.cursor()\r\n\r\n sql = (\"\"\"INSERT INTO conditions2\r\n (nom_ville, pression, vent,\r\n météo, climat, saison,\r\n REGION_INDUSTRIEL_POLLUEE,\r\n POPULATION_ACTIVE_HABITANT,\r\n TRAFIQUE, HEURE, WEEKEND,\r\n BOUCHON, ACTIVITE_EXEPTIONNELLE\r\n , angrais, diesel,\r\n eruption,incendie,\r\n jour_nuit, polenne,\r\n pos, heure_donnée, date,\r\n nombre_particule)\r\n VALUES (%s,%s,%s,\r\n %s,%s,%s,%s,\r\n %s,%s,\r\n %s,%s,%s,%s,\r\n %s,%s,%s,%s,\r\n %s,%s,\r\n %s,%s, %s, %s);\r\n \"\"\")\r\n\r\n\r\n values = (i, data_k, data_j, data_h, data_b, data_c,\r\n data_n, data_q,\r\n data_r, data_s, data_t, data_u, data_v\r\n , data_a, data_d, data_e, data_f, data_g,\r\n data_o, data_l, HEURE_JOUR[1], HEURE_JOUR[0], data_m)\r\n\r\n cursor.execute(sql, values)\r\n conn.commit()\r\n","sub_path":"bobo/polution/test/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"623321483","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jun 24 13:58:17 2017\r\n\r\n@author: kashu\r\n\"\"\"\r\n\r\nimport os\r\nimport numpy as np\r\nimport pandas as pd\r\nimport tensorflow as tf\r\nimport matplotlib.pyplot as plt\r\nfilenameTrain = 'all_train.csv'\r\nfilenameTest = 'all_test.csv'\r\ndata_root = 'C:/MASTERS/AdvancedML/Exercise/all_massData'\r\ndest_filenameTrain = os.path.join(data_root,filenameTrain)\r\ndest_filenameTest = os.path.join(data_root,filenameTest)\r\ndataTrain = pd.read_csv(dest_filenameTrain)\r\ndataTest = pd.read_csv(dest_filenameTest)\r\ncompleteDataTrain= np.array(dataTrain,dtype ='float32')\r\ncompleteDataTest = np.array(dataTest,dtype ='float32')\r\nlablesTrain = completeDataTrain[:,0:1]\r\nlablesTrain=np.reshape(lablesTrain,7000000)\r\ncompleteDataTrain = completeDataTrain[:,1:29]\r\nlablesTest = completeDataTest[:,0:1]\r\nlablesTest=np.reshape(lablesTest,3500000)\r\ncompleteDataTest = completeDataTest[:,1:29]\r\nnum_labels = 2\r\nnum_features =28\r\nlablesTrain = (np.arange(num_labels) == lablesTrain[:,None]).astype(np.float32)\r\nlablesTest = (np.arange(num_labels) == lablesTest[:,None]).astype(np.float32)\r\ndef accuracy(predictions, labels):\r\n return (100.0 * np.sum(np.argmax(predictions, axis=1) == np.argmax(labels, axis=1))\r\n / predictions.shape[0])\r\n \r\n#twoThird = int((2/3)*completeDataTrain.shape[0])\r\n#trainingData = completeDataTrain[:twoThird]\r\n#trainingLabels = lablesTrain[:twoThird]\r\n#validData = completeDataTrain[twoThird:]\r\n#validLabels = lablesTrain[twoThird:] \r\n\r\ntwoThird = int((2/3)*completeDataTrain.shape[0])\r\ntrainingData = completeDataTrain[:twoThird]\r\ntrainingLabels = lablesTrain[:twoThird]\r\nvalidData = completeDataTrain[twoThird:]\r\nvalidLabels = lablesTrain[twoThird:]\r\ntestData = completeDataTest\r\ntestLabels = lablesTest\r\n\r\nnum_nodes_1= 10\r\nnum_nodes_2 = 3\r\nbatch_size = 128\r\n\r\ngraph = tf.Graph()\r\nwith graph.as_default():\r\n\r\n # Input data. For the training data, we use a placeholder that will be fed\r\n # at run time with a training minibatch.\r\n tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, num_features))\r\n tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels))\r\n tf_valid_dataset = tf.constant(validData)\r\n tf_test_dataset = tf.constant(testData)\r\n\r\n # Variables.\r\n weights_1 = tf.Variable(tf.zeros([num_features, num_nodes_1]))\r\n biases_1 = tf.Variable(tf.zeros([num_nodes_1]))\r\n weights_2 = tf.Variable(tf.zeros([num_nodes_1, num_nodes_2]))\r\n biases_2 = tf.Variable(tf.zeros([num_nodes_2]))\r\n \r\n #adding extra layer\r\n weights_3 = tf.Variable(tf.zeros([num_nodes_2, num_labels]))\r\n biases_3 = tf.Variable(tf.zeros([num_labels]))\r\n\r\n # Training computation.\r\n logits_1 = tf.matmul(tf_train_dataset, weights_1) + biases_1\r\n #(128,784)*(784,1024)+(1024,1)= Dimension of logit_1 =(128,1)\r\n sigmoid_layer_1= tf.nn.sigmoid(logits_1)\r\n #output of sigmoid layer would be (128,1024) \r\n logits_2 = tf.matmul(sigmoid_layer_1, weights_2) + biases_2\r\n #(128,1024)*(1024,10)+(10,1)= Dimension of logit_2 = (128,1)\r\n \r\n #adding extra layer\r\n \r\n sigmoid_layer_2= tf.nn.sigmoid(logits_2)\r\n \r\n logits_3 = tf.matmul(sigmoid_layer_2, weights_3) + biases_3\r\n \r\n# loss = tf.reduce_mean(\r\n# tf.nn.sigmoid_cross_entropy_with_logits(labels=tf_train_labels, logits=logits_2))\r\n loss = tf.reduce_mean(\r\n tf.nn.sigmoid_cross_entropy_with_logits(labels=tf_train_labels, logits=logits_3))\r\n\r\n # Optimizer.\r\n optimizer = tf.train.AdadeltaOptimizer(0.2).minimize(loss)\r\n# global_step = tf.Variable(0) # count the number of steps taken.\r\n# start_learning_rate = 0.5\r\n# learning_rate = tf.train.exponential_decay(start_learning_rate, global_step, 100000, 0.96, staircase=True)\r\n# optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)\r\n\r\n # Predictions for the training\r\n #train_prediction = tf.nn.sigmoid(logits_2)\r\n train_prediction = tf.nn.sigmoid(logits_3)\r\n \r\n # Predictions for validation \r\n logits_1 = tf.matmul(tf_valid_dataset, weights_1) + biases_1\r\n sigmoid_layer_1= tf.nn.sigmoid(logits_1)\r\n logits_2 = tf.matmul(sigmoid_layer_1, weights_2) + biases_2\r\n sigmoid_layer_2= tf.nn.sigmoid(logits_2)\r\n logits_3 = tf.matmul(sigmoid_layer_2, weights_3) + biases_3\r\n \r\n \r\n \r\n valid_prediction = tf.nn.sigmoid(logits_3)\r\n \r\n \r\n # Predictions for test\r\n logits_1 = tf.matmul(tf_test_dataset, weights_1) + biases_1\r\n sigmoid_layer_1= tf.nn.sigmoid(logits_1)\r\n logits_2 = tf.matmul(sigmoid_layer_1, weights_2) + biases_2\r\n sigmoid_layer_2= tf.nn.sigmoid(logits_2)\r\n logits_3 = tf.matmul(sigmoid_layer_2, weights_3) + biases_3\r\n \r\n test_prediction = tf.nn.sigmoid(logits_3)\r\n \r\n \r\nnum_steps = 100000\r\n\r\nwith tf.Session(graph=graph) as session:\r\n tf.global_variables_initializer().run()\r\n print(\"Initialized\")\r\n for step in range(num_steps):\r\n # Pick an offset within the training data, which has been randomized.\r\n # Note: we could use better randomization across epochs.\r\n offset = (step * batch_size) % (trainingLabels.shape[0] - batch_size)\r\n #offset is a kind of window whnever it is greater than 200000 it is taking reminder \r\n #of (step(chnaging every iteration) * batch_size) % (train_labels.shape[0](fixedvalue=200000) - batch_size(128))\r\n # Generate a minibatch.\r\n batch_data = trainingData[offset:(offset + batch_size), :]\r\n batch_labels = trainingLabels[offset:(offset + batch_size), :]\r\n # Prepare a dictionary telling the session where to feed the minibatch.\r\n # The key of the dictionary is the placeholder node of the graph to be fed,\r\n # and the value is the numpy array to feed to it.\r\n feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels}\r\n _, l, predictions = session.run([optimizer, loss, train_prediction], feed_dict=feed_dict)\r\n if (step % 1000 == 0):\r\n print('offset',offset) \r\n print(trainingLabels.shape[0])\r\n print(\"Minibatch loss at step %d: %f\" % (step, l))\r\n print(\"Minibatch accuracy: %.1f%%\" % accuracy(predictions, batch_labels))\r\n #plt.plot(accuracy(predictions, batch_labels), label = 'accuracy')\r\n print(\"Validation accuracy: %.1f%%\" % accuracy(valid_prediction.eval(), validLabels))\r\n print(\"Test accuracy: %.1f%%\" % accuracy(test_prediction.eval(), testLabels))\r\n #plt.show()","sub_path":"HepmassANN_version3.py","file_name":"HepmassANN_version3.py","file_ext":"py","file_size_in_byte":6414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"469023688","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Author Davide Caputo\n# Copyright nessuno\n\n\"\"\"\nModulo contetente la classe ListRequirements\nche identifica la lista dei requisiti del file\nassociato alla traduzione\n\"\"\"\n\nfrom ListStatements import ListStatements\nfrom RequirementDef import RequirementDef\nimport os\n\n__author__ = \"Davide Caputo\"\n__version__ = \"1.0.0\"\n\n\nclass ListRequirements(ListStatements):\n \"\"\"Class ListRequirements,\n classe che serve per la gestione\n del file dei requisiti ottenuto come input,\n \"\"\"\n # Attributes:\n __nomeFile = None # (String)\n __fileRequisiti = None # (File)\n __size = None # (int)\n\n # Costruttore\n def __init__(self, nomeFile=None, fileRequisiti=None):\n self.__nomeFile = nomeFile\n self.__fileRequisiti = fileRequisiti\n self.__requisiti = []\n\n # Operations\n def readFile(self):\n \"\"\"function readFile legge il file dei requisiti\n e li aggiunge a self,\n associando ad ognuno di essi un id univoco\n \"\"\"\n i = 1 # set id to 0\n if self.__fileRequisiti is not None:\n contenuto = self.__fileRequisiti.readlines()\n self.__size = len(contenuto)\n for tempReq in contenuto:\n if tempReq.strip(): # ignoro la linea vuota\n self.addRequisito(tempReq.strip(), i)\n i = i + 1\n\n def openFile(self):\n \"\"\"function openFile\n\n :param nomeFile\n :type String\n\n returns boolean\n \"\"\"\n if self.__nomeFile is not None:\n openFile = os.path.exists(self.__nomeFile)\n return openFile # should raise NotImplementedError()\n else:\n return False\n\n def addRequisito(self, requisito=None, index=None):\n \"\"\"function addRequisito\n aggiunge il requisito passato come parametro\n alla lista dei requisiti da processare\n\n :param requisito una stringa corrispondente ad una riga\n del requisito\n :type String\n :param id univoco del requisito\n :type int\n \"\"\"\n if requisito is not None:\n tempRequisito = RequirementDef(id=index, requisito=requisito)\n self.__requisiti.append(tempRequisito)\n\n def getNameFile(self):\n \"\"\"function getName\n funzione che ritorna il nome\n del file dei requisiti\n :return nameFile\n _rtype String\n \"\"\"\n return self.__nomeFile\n\n def printAllRequisiti(self):\n \"\"\"functions printAllRequsiti\n stampa tutti i requisiti memorizzati\n \"\"\"\n for temp in self.__requisiti:\n print(temp.getRequisito())\n\n def getRequisiti(self):\n \"\"\" function getRequisiti\n funzione per ottenere tutti i requisiti\n memorizzati\n\n :returns List RequirementDef\n \"\"\"\n return self.__requisiti\n\n def getRequisitiValidi(self):\n \"\"\" function getRequisitiValidi\n funzione per ottenere i soli requisiti che sono processabili\n per poter essere tradotti\n :returns List RequirementDef\n \"\"\"\n listRequisitiValidi = []\n for req in self.__requisiti:\n if req.getValido():\n listRequisitiValidi.append(req)\n return listRequisitiValidi","sub_path":"src/ListRequirements.py","file_name":"ListRequirements.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598862976","text":"VOWELS = \"aeiouy\"\r\nCNSNNTS = \"bcdfghjklmnpqrstvwxz\"\r\n\r\ndef translate(phrase):\r\n index, new_phrase = 0, ''\r\n while index < len(phrase):\r\n new_phrase += phrase[index]\r\n if phrase[index] in CNSNNTS:\r\n index += 2\r\n elif phrase[index] in VOWELS:\r\n index += 3\r\n else:\r\n index += 1\r\n\r\n return new_phrase\r\n\r\nif __name__ == '__main__':\r\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\r\n assert translate(\"hieeelalaooo\") == \"hello\", \"Hi!\"\r\n assert translate(\"hoooowe yyyooouuu duoooiiine\") == \"how you doin\", \"Joey?\"\r\n assert translate(\"aaa bo cy da eee fe\") == \"a b c d e f\", \"Alphabet\"\r\n assert translate(\"sooooso aaaaaaaaa\") == \"sos aaa\", \"Mayday, mayday\"\r\n","sub_path":"Incinerator/Bird_Language.py","file_name":"Bird_Language.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"292955642","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport urllib2\nimport tarfile\nimport time\nimport subprocess\nimport argparse\nimport multiprocessing\n\n# check python ver 2.6+\nif sys.version_info < (2, 6):\n print('need python 2.6+')\n sys.exit(0)\n# check python ver < 3\nif sys.version_info > (3, 0):\n print('need python 2')\n sys.exit(0)\n\n# TODO - tidy this up/move into class\n# check for git\np = subprocess.Popen('which git', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\ndata = p.communicate()[0]\nif data.count('which') > 0:\n print('unable to find git')\n sys.exit(0)\n\nclass ffmpeg_build():\n\n # TODO - check for git\n # TODO - check for library file output, so we can stop build on failure\n # TODO - have libraries build both shared and static?\n\n def __init__(self, nonfree=False, cflags='', build_static=True):\n self.nonfree = nonfree\n self.cflagsopt = cflags\n self.build_static = build_static\n\n self.web_server = 'http://www.ghosttoast.com/pub/ffmpeg'\n\n self.cpuCount = multiprocessing.cpu_count()\n\n self.app_list()\n self.setup_folder_vars()\n self.setup_env_vars()\n\n # print env\n #os.system('export 2>/dev/null')\n\n #cflagsopt = ''\n # native\n #cflagsopt = '-march=native'\n #cflagsopt = '-march=native -fPIC'\n # dcs24 tape2\n #cflagsopt = '-march=core2 -msse4.1'\n #cflagsopt = '-march=core2 -msse4.1 -fPIC'\n # ts\n #cflagsopt = '-march=corei7'\n #clfagsopt = '-march=corei7 -fPIC'\n\n def app_list(self):\n self.downloadList = []\n self.downloadAuxList = []\n self.gitList = []\n self.fileList = []\n self.downloadListGz = []\n self.fileListGz = []\n\n\n self.xz = 'xz-5.2.2'\n self.downloadListGz.append(self.xz)\n\n self.yasm = 'yasm-1.3.0'\n self.downloadListGz.append(self.yasm)\n\n self.openssl = 'openssl-1.0.2j'\n self.downloadList.append(self.openssl)\n\n self.cmake = 'cmake-3.6.3'\n self.downloadList.append(self.cmake)\n\n self.zlib = 'zlib-1.2.8'\n self.downloadList.append(self.zlib)\n\n self.bzip2 = 'bzip2-1.0.6'\n self.downloadList.append(self.bzip2)\n\n self.ncurses = 'ncurses-6.0'\n self.downloadList.append(self.ncurses)\n\n #self.snappy = 'snappy-1.1.3'\n #self.downloadList.append(self.snappy)\n\n self.libpng = 'libpng-1.6.26'\n self.downloadList.append(self.libpng)\n\n self.openjpeg = 'openjpeg-1.5.2' # ffmpeg works with 1.x, not 2.x\n self.downloadList.append(self.openjpeg)\n\n self.libtiff = 'tiff-4.0.6'\n self.downloadList.append(self.libtiff)\n\n self.libogg = 'libogg-1.3.2'\n self.downloadList.append(self.libogg)\n\n self.libvorbis = 'libvorbis-1.3.5'\n self.downloadList.append(self.libvorbis)\n\n self.libtheora = 'libtheora-1.1.1'\n self.downloadList.append(self.libtheora)\n\n self.libvpx = 'libvpx-1.6.0'\n self.downloadList.append(self.libvpx)\n\n self.speex = 'speex-1.2rc2'\n self.downloadList.append(self.speex)\n\n self.lame = 'lame-3.99.5'\n self.downloadList.append(self.lame)\n\n self.twolame = 'twolame-0.3.13'\n self.downloadList.append(self.twolame)\n\n self.soxr = 'soxr-0.1.2'\n self.downloadList.append(self.soxr)\n\n self.wavpack = 'wavpack-4.80.0'\n self.downloadList.append(self.wavpack)\n\n self.fdkaac = 'fdk-aac-0.1.4'\n self.downloadList.append(self.fdkaac)\n\n self.x264 = 'https://git.videolan.org/git/x264.git'\n self.gitList.append(['x264', self.x264])\n self.x264BitDepth = '8'\n self.x264Chroma = 'all'\n\n self.x265 = 'https://github.com/videolan/x265.git'\n self.gitList.append(['x265', self.x265])\n\n self.xvid = 'xvid-1.3.4'\n self.downloadList.append(self.xvid)\n self.downloadAuxList.append('xvid_Makefile.patch')\n\n self.nvenc = 'nvidia_video_sdk_7.0.1'\n self.downloadList.append(self.nvenc)\n\n self.blackmagic = 'Blackmagic_DeckLink_SDK_10.8'\n self.downloadList.append(self.blackmagic)\n\n self.libgsm = 'libgsm-1.0.13-4'\n self.downloadList.append(self.libgsm)\n\n self.libilbc = 'libilbc-20141214-git-ef04ebe'\n self.downloadList.append(self.libilbc)\n\n self.webp = 'libwebp-0.5.1'\n self.downloadList.append(self.webp)\n\n self.opus = 'opus-1.1.3'\n self.downloadList.append(self.opus)\n\n self.kvazaar = 'kvazaar-1.0.0'\n self.downloadList.append(self.kvazaar)\n\n self.expat = 'expat-2.2.0'\n self.downloadList.append(self.expat)\n\n self.freetype = 'freetype-2.7'\n self.downloadList.append(self.freetype)\n\n self.fontconfig = 'fontconfig-2.12.1'\n self.downloadList.append(self.fontconfig)\n\n self.libebur128 = 'libebur128-1.2.0'\n self.downloadList.append(self.libebur128)\n\n self.faac = 'faac-1.28'\n self.downloadList.append(self.faac)\n\n self.ffmpeg = 'https://github.com/lbdroid/ffmpeg.git'\n self.gitList.append(['ffmpeg', self.ffmpeg])\n\n self.ffmbc = 'https://github.com/bcoudurier/FFmbc.git'\n self.gitList.append(['FFmbc', self.ffmbc])\n\n for item in self.downloadList:\n self.fileList.append('%s.tar.xz' % item)\n for item in self.downloadAuxList:\n self.fileList.append('%s.xz' % item)\n for item in self.downloadListGz:\n itemFn = '%s.tar.gz' % item\n self.fileList.append(itemFn)\n self.fileListGz.append(itemFn)\n\n def setup_folder_vars(self):\n self.ENV_ROOT = os.getcwd()\n self.TARGET_DIR = os.path.join(self.ENV_ROOT, 'target')\n self.BUILD_DIR = os.path.join(self.ENV_ROOT, 'compile')\n self.BUILD_GIT_DIR = os.path.join(self.ENV_ROOT, 'sourcegit')\n self.TAR_DIR = os.path.join(self.ENV_ROOT, 'sourcetar')\n\n self.OUT_FOLDER = 'output'\n self.OUT_DIR = os.path.join(self.ENV_ROOT, self.OUT_FOLDER)\n\n def setup_env_vars(self):\n # setup ENV\n self.ENV_PATH_ORIG = os.getenv('PATH')\n self.ENV_LD_ORIG = os.getenv('LD_LIBRARY_PATH')\n #if sys.platform.startswith('darwin'): # TODO - fix darwin vars\n # addpath += ':/opt/local/bin'\n os.putenv('PATH', '%s:%s' % (os.path.join(self.TARGET_DIR, 'bin'), self.ENV_PATH_ORIG))\n os.putenv('LD_LIBRARY_PATH', '%s:%s' % (os.path.join(self.TARGET_DIR, 'lib'), self.ENV_LD_ORIG))\n os.putenv('PKG_CONFIG_PATH', os.path.join(self.TARGET_DIR, 'lib', 'pkgconfig'))\n self.ENV_CFLAGS = '-I%s' % (os.path.join(self.TARGET_DIR, 'include'),)\n os.putenv('CFLAGS', self.ENV_CFLAGS)\n os.putenv('CPPFLAGS', self.ENV_CFLAGS)\n self.ENV_LDFLAGS_STD = ''\n self.ENV_LDFLAGS_STD += '-L%s' % os.path.join(self.TARGET_DIR, 'lib')\n self.ENV_LDFLAGS_STATIC = ' -static -static-libgcc -static-libstdc++'\n\n self.ENV_LDFLAGS = self.ENV_LDFLAGS_STD\n if self.build_static is True:\n self.ENV_LDFLAGS += self.ENV_LDFLAGS_STATIC\n\n os.putenv('LDFLAGS', self.ENV_LDFLAGS)\n os.system('export')\n\n def setupDIR(self):\n for item in [self.ENV_ROOT, self.TARGET_DIR, self.BUILD_DIR, self.BUILD_GIT_DIR, self.TAR_DIR, self.OUT_DIR]:\n os.system('mkdir -p %s' % item)\n old_dir = os.getcwd()\n os.chdir(self.TARGET_DIR)\n os.system('mkdir -p lib')\n os.system('ln -s lib lib64')\n os.chdir(old_dir)\n\n def cleanTARGET_DIR(self):\n os.system('rm -rf %s' % self.TARGET_DIR)\n\n def cleanBUILD_DIR(self):\n os.system('rm -rf %s' % self.BUILD_DIR)\n\n def cleanBUILDGIT_DIR(self):\n os.system('rm -rf %s' % self.BUILD_GIT_DIR)\n\n def cleanTAR_DIR(self):\n os.system('rm -rf %s' % self.TAR_DIR)\n\n def cleanOUT_DIR(self):\n os.system('rm -rf %s' % self.OUT_DIR)\n\n def cleanOUT_DIR_FILES(self):\n os.system('rm -f %s.tar' % self.OUT_DIR)\n os.system('rm -f %s.tar.xz' % self.OUT_DIR)\n\n def cleanALL(self):\n self.cleanTARGET_DIR()\n self.cleanBUILD_DIR()\n self.cleanTAR_DIR()\n self.cleanOUT_DIR()\n self.cleanOUT_DIR_FILES()\n\n @staticmethod\n def prewarn():\n print('\\nneeded packages:\\ngcc git glibc-static (libstdc++-static on some os-es)\\n\\n')\n x = 2\n while x > 0:\n print(x)\n x = x - 1\n time.sleep(1)\n\n def f_getfiles(self):\n print('\\n*** Downloading files ***\\n')\n os.chdir(self.TAR_DIR)\n for fileName in self.fileList:\n fileNamePre, fileNameExt = os.path.splitext(fileName)\n if os.path.exists(os.path.join(self.TAR_DIR, fileName.rstrip('.%s' % fileNameExt))) is False:\n try:\n print('%s/%s' % (self.web_server, fileName))\n response = urllib2.urlopen('%s/%s' % (self.web_server, fileName))\n data = response.read()\n except urllib2.HTTPError as e:\n print('error downloading %s/%s %s' % (self.web_server, fileName, e))\n sys.exit(1)\n f = open(fileName, 'wb')\n f.write(data)\n f.close()\n else:\n print('%s already downloaded' % fileName.rstrip('.%s' % fileNameExt))\n self.f_sync()\n\n def f_decompressfiles_gz(self):\n print('\\n*** Decompressing gz files ***\\n')\n os.chdir(self.BUILD_DIR)\n for fileName in self.fileListGz:\n if os.path.exists(os.path.join(self.TAR_DIR, fileName.rstrip('.gz'))) is False:\n os.system('gunzip -v %s' % os.path.join(self.TAR_DIR, fileName))\n else:\n print('%s already uncompressed' % fileName)\n self.f_sync()\n\n def f_decompressfiles_xz(self):\n print('\\n*** Decompressing xz files ***\\n')\n os.chdir(self.BUILD_DIR)\n for fileName in self.fileList:\n if fileName.endswith('.xz'):\n if os.path.exists(os.path.join(self.TAR_DIR, fileName.rstrip('.xz'))) is False:\n os.system('%s -dv %s' % (os.path.join(self.TARGET_DIR, 'bin', 'xz'), os.path.join(self.TAR_DIR, fileName)))\n else:\n print('%s already uncompressed' % fileName)\n self.f_sync()\n\n def f_repo_clone(self):\n # clone git repos\n for item in self.gitList:\n self.git_clone(item[0], item[1])\n self.f_sync()\n\n def f_extractfiles(self, gzipMode=False):\n print('\\n*** Extracting tar files ***\\n')\n os.chdir(self.BUILD_DIR)\n if gzipMode is True:\n fileList = self.fileListGz\n else:\n fileList = self.fileList\n for fileName in fileList:\n fileNamePre, fileNameExt = os.path.splitext(fileName)\n if fileNamePre.lower().endswith('.tar'):\n print(fileNamePre)\n tar = tarfile.open(os.path.join(self.TAR_DIR, fileNamePre))\n tar.extractall()\n tar.close()\n\n def f_repo_deploy(self):\n for item in self.gitList:\n self.git_deploy(item[0])\n self.f_sync()\n\n def git_clone(self, name, url):\n print('\\n*** Cloning %s ***\\n' % name)\n if os.path.exists(os.path.join(self.BUILD_GIT_DIR, name)):\n print('git pull')\n os.chdir(os.path.join(self.BUILD_GIT_DIR, name))\n os.system('git pull')\n else:\n print('git clone')\n os.chdir(self.BUILD_GIT_DIR)\n os.system('git clone %s' % url)\n\n def git_deploy(self, name):\n print('\\n*** Deploy %s git to BUILD_DIR ***\\n' % name)\n os.chdir(self.BUILD_GIT_DIR)\n os.system('cp -rf ./%s %s' % (name, self.BUILD_DIR))\n\n @staticmethod\n def f_sync():\n print('\\n*** Syncinig Hard Drive ***\\n')\n os.system('sync')\n\n def b_yasm(self):\n print('\\n*** Building yasm ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.yasm))\n os.system('./configure --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_xz(self):\n print('\\n*** Building xz/liblzma ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.xz))\n os.system('./configure --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_curl(self):\n print('\\n*** Building curl ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.curl))\n os.putenv('LDFLAGS', self.ENV_LDFLAGS_STD)\n os.system('./configure --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n os.putenv('LDFLAGS', self.ENV_LDFLAGS)\n self.f_sync()\n\n def b_git(self):\n print('\\n*** Building git ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.git))\n os.putenv('LDFLAGS', self.ENV_LDFLAGS_STD)\n os.system('./configure --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n os.putenv('LDFLAGS', self.ENV_LDFLAGS)\n self.f_sync()\n\n def b_cmake(self):\n print('\\n*** Building cmake ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.cmake))\n os.putenv('LDFLAGS', self.ENV_LDFLAGS_STD)\n os.system('./configure --prefix=%s --parallel=%s' % (self.TARGET_DIR, self.cpuCount))\n os.system('make -j %s && make install' % self.cpuCount)\n os.putenv('LDFLAGS', self.ENV_LDFLAGS)\n\n def b_zlib(self):\n print('\\n*** Building zlib ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.zlib))\n cfgcmd = 'export CFLAGS=\"$CFLAGS -fPIC\";./configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --static'\n os.system(cfgcmd)\n os.system('export CFLAGS=\"$CFLAGS -fPIC\";make -j %s && make install' % self.cpuCount)\n\n def b_bzip2(self):\n print('\\n*** Building bzip2 ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.bzip2))\n os.system('make CFLAGS=\"-Wall -Winline -O2 -g -D_FILE_OFFSET_BITS=64 -fPIC\"')\n os.system('make install PREFIX=%s' % self.TARGET_DIR)\n\n def b_ncurses(self):\n print('\\n*** Building ncurses ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.ncurses))\n os.system('./configure --with-termlib --with-ticlib --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_openssl(self):\n print('\\n*** Building openssl ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.openssl))\n cfgcmd = './Configure --prefix=%s linux-x86_64' % (self.TARGET_DIR)\n if self.build_static is True:\n cfgcmd += ' no-shared'\n else:\n cfgcmd += ' shared'\n os.system(cfgcmd)\n os.system('make depend')\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_libpng(self):\n print('\\n*** Building libpng ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libpng))\n os.system('./configure --prefix={0}'.format(self.TARGET_DIR))\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_openjpeg(self):\n print('\\n*** Building openjpeg ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.openjpeg))\n os.system('./bootstrap.sh')\n os.system('./configure --disable-png --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_libtiff(self):\n print('\\n*** Building libtiff ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libtiff))\n if self.build_static is True:\n os.system('export CFLAGS=\"--static -I%s\";export LDFLAGS=\"-L%s -static -static-libgcc\";./configure --prefix=%s --enable-shared=no --enable-static=yes' % (os.path.join(self.TARGET_DIR, 'include'), os.path.join(self.TARGET_DIR, 'lib'), self.TARGET_DIR))\n os.system('export CFLAGS=\"--static -I%s\";export LDFLAGS=\"-L%s -static -static-libgcc\";make -j %s && make install' % (os.path.join(self.TARGET_DIR, 'include'), os.path.join(self.TARGET_DIR, 'lib'), self.cpuCount))\n else:\n os.system('export CFLAGS=\"-I%s\";export LDFLAGS=\"-L%s\";./configure --prefix=%s --enable-shared=yes --enable-static=no' % (os.path.join(self.TARGET_DIR, 'include'), os.path.join(self.TARGET_DIR, 'lib'), self.TARGET_DIR))\n os.system('export CFLAGS=\"-I%s\";export LDFLAGS=\"-L%s\";make -j %s && make install' % (os.path.join(self.TARGET_DIR, 'include'), os.path.join(self.TARGET_DIR, 'lib'), self.cpuCount))\n\n def b_libogg(self):\n print('\\n*** Building libogg ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libogg))\n os.system('./configure --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_libvorbis(self):\n print('\\n*** Building libvorbis ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libvorbis))\n os.system('./configure --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_libtheora(self):\n print('\\n*** Building libtheora ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libtheora))\n cfgcmd = './configure --prefix=%s --disable-examples' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --enable-static --disable-shared'\n else:\n cfgcmd += ' --disable-static'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_libvpx(self):\n print('\\n*** Building libvpx ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libvpx))\n cfgcmd = './configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --enable-static --disable-shared'\n else:\n cfgcmd += ' --disable-static --enable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_speex(self):\n print('\\n*** Building speex ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.speex))\n os.system('./configure --prefix=%s --enable-sse' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_lame(self):\n print('\\n*** Building lame ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.lame))\n cfgcmd = './configure --disable-frontend --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --enable-shared=no --enable-static=yes'\n else:\n cfgcmd += ' --enable-shared=yes --enable-static=no'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_twolame(self):\n print('\\n*** Building twolame ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.twolame))\n cfgcmd = './configure --prefix=%s' % (self.TARGET_DIR)\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_soxr(self):\n print('\\n*** Building soxr ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.soxr))\n os.system('mkdir Release')\n os.chdir(os.path.join(self.BUILD_DIR, self.soxr, 'Release'))\n if self.build_static is True:\n os.system('cmake -DCMAKE_BUILD_TYPE=Release -Wno-dev -DCMAKE_INSTALL_PREFIX=\"%s\" -DBUILD_SHARED_LIBS:bool=off ..' % self.TARGET_DIR)\n else:\n os.system('cmake -DCMAKE_BUILD_TYPE=Release -Wno-dev -DCMAKE_INSTALL_PREFIX=\"%s\" ..' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_wavpack(self):\n print('\\n*** Building wavpack ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.wavpack))\n cfgcmd = './configure --prefix=%s' % (self.TARGET_DIR)\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_fdkaac(self):\n print('\\n*** Building fdk-aac ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.fdkaac))\n cfgcmd = './configure --prefix=%s' % (self.TARGET_DIR)\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_x264(self):\n print('\\n*** Building x264 ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, 'x264')) # for git checkout\n cfgcmd = './configure --prefix=%s --enable-static --disable-cli --disable-opencl --disable-swscale --disable-lavf --disable-ffms --disable-gpac --bit-depth=%s --chroma-format=%s' % (self.TARGET_DIR, self.x264BitDepth, self.x264Chroma)\n if self.build_static is True:\n cfgcmd += ' --enable-static'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_x265(self):\n print('\\n*** Build x265 ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, 'x265', 'build', 'linux')) # for git checkout\n if self.build_static is True:\n os.system('cmake -G \"Unix Makefiles\" -Wno-dev -DCMAKE_INSTALL_PREFIX=\"%s\" -DENABLE_SHARED:bool=off ../../source' % self.TARGET_DIR)\n else:\n os.system('cmake -G \"Unix Makefiles\" -Wno-dev -DCMAKE_INSTALL_PREFIX=\"%s\" ../../source' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_kvazaar(self):\n print('\\n*** Build kvazaar ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.kvazaar))\n os.system('./autogen.sh')\n cfgcmd = './configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_xvid(self):\n print('\\n*** Building xvid ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.xvid, 'build', 'generic'))\n if self.build_static is True:\n # apply patch for static only build\n os.system('cp -f %s ./' % os.path.join(self.TAR_DIR, 'xvid_Makefile.patch'))\n os.system('patch -f < xvid_Makefile.patch')\n os.system('./configure --prefix=%s' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n #os.system('rm -f %s' % os.path.join(TARGET_DIR, 'lib', 'libxvidcore.so.*'))\n\n def b_snappy(self):\n print('\\n*** Building snappy ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.snappy))\n # CXX FLAGS\n os.putenv('CXXFLAGS', self.ENV_CFLAGS) # TODO, check if this is actually useful\n os.system('make clean')\n cfgcmd = './configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_blackmagic(self):\n print('\\n*** Deploying Blackmagic SDK ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.blackmagic, 'Linux', 'include'))\n os.system('cp -f ./* %s' % os.path.join(self.TARGET_DIR, 'include'))\n\n def b_nvenc(self):\n print('\\n*** Deploying nvenc (Nvidia Video SDK) ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.nvenc, 'Samples', 'common', 'inc'))\n os.system('cp -f ./nvEncodeAPI.h %s' % os.path.join(self.TARGET_DIR, 'include'))\n\n def b_libgsm(self):\n print('\\n*** Building libgsm ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libgsm))\n os.putenv('INSTALL_ROOT', self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n os.unsetenv('INSTALL_ROOT')\n\n def b_libilbc(self):\n print('\\n*** Building libilbc ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libilbc))\n cfgcmd = './configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_webp(self):\n print('\\n*** Building webp ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.webp))\n cfgcmd = './configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_opus(self):\n print('\\n*** Building opus ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.opus))\n cfgcmd = './configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_expat(self):\n print('\\n*** Building expat ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.expat))\n cfgcmd = './configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' '\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_freetype(self):\n print('\\n*** Building freetype ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.freetype))\n cfgcmd = './configure --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --enable-shared=no'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_fontconfig(self):\n print('\\n*** Building fontconfig ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.fontconfig))\n cfgcmd = './configure --disable-docs --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_libebur128(self):\n print('\\n*** Building libebur128 ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.libebur128))\n os.system('mkdir build')\n os.chdir(os.path.join(self.BUILD_DIR, self.libebur128, 'build'))\n os.putenv('LDFLAGS', self.ENV_LDFLAGS_STD)\n if self.build_static is True:\n os.system('cmake -DCMAKE_BUILD_TYPE=Release -Wno-dev -DCMAKE_INSTALL_PREFIX=\"%s\" -DBUILD_STATIC_LIBS:bool=on -DWITH_STATIC_PIC:bool=on ..' % self.TARGET_DIR)\n else:\n os.system('cmake -DCMAKE_BUILD_TYPE=Release -Wno-dev -DCMAKE_INSTALL_PREFIX=\"%s\" ..' % self.TARGET_DIR)\n os.system('make -j %s && make install' % self.cpuCount)\n os.putenv('LDFLAGS', self.ENV_LDFLAGS)\n\n def b_faac(self):\n print('\\n*** Building faac ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, self.faac))\n cfgcmd = './configure --without-mp4v2 --prefix=%s' % self.TARGET_DIR\n if self.build_static is True:\n cfgcmd += ' --enable-static --disable-shared'\n os.system(cfgcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n\n def b_ffmpeg(self):\n print('\\n*** Building ffmpeg ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, 'ffmpeg'))\n\n # modify env\n\n ENV_CFLAGS_NEW = '%s' % self.ENV_CFLAGS\n if self.build_static is True:\n ENV_CFLAGS_NEW += ' --static'\n os.putenv('CFLAGS', ENV_CFLAGS_NEW)\n os.putenv('CPPFLAGS', ENV_CFLAGS_NEW)\n ENV_LDFLAGS_NEW = self.ENV_LDFLAGS\n ENV_LDFLAGS_NEW += ' -fopenmp' # openmp is needed by soxr\n #ENV_LDFLAGS_NEW += ' -lstdc++' # stdc++ is needed by snappy\n os.putenv('LDFLAGS', ENV_LDFLAGS_NEW)\n\n confcmd = ''\n confcmd += './configure --prefix=%s' % self.TARGET_DIR\n confcmd += ' --extra-version=static'\n if self.build_static is True:\n confcmd += ' --pkg-config-flags=\"--static\"'\n confcmd += ' --enable-gpl'\n confcmd += ' --enable-version3'\n if self.nonfree:\n confcmd += ' --enable-nonfree'\n if self.build_static is True:\n confcmd += ' --enable-static'\n confcmd += ' --disable-shared'\n else:\n confcmd += ' --disable-static'\n confcmd += ' --enable-static'\n confcmd += ' --disable-debug'\n confcmd += ' --enable-runtime-cpudetect'\n confcmd += ' --disable-doc'\n confcmd += ' --disable-ffplay'\n confcmd += ' --disable-ffserver'\n confcmd += ' --enable-bzlib'\n confcmd += ' --enable-zlib'\n confcmd += ' --enable-lzma'\n confcmd += ' --enable-libmp3lame'\n confcmd += ' --enable-libopenjpeg'\n confcmd += ' --enable-libopus'\n confcmd += ' --enable-libvorbis'\n confcmd += ' --enable-libtheora'\n #confcmd += ' --enable-libvpx'\n confcmd += ' --enable-libspeex'\n confcmd += ' --enable-libx264'\n confcmd += ' --enable-libx265'\n confcmd += ' --enable-libsoxr'\n confcmd += ' --enable-libtwolame'\n confcmd += ' --enable-libwavpack'\n confcmd += ' --enable-libilbc'\n confcmd += ' --enable-libwebp'\n confcmd += ' --enable-libfreetype'\n confcmd += ' --enable-libfontconfig'\n #confcmd += ' --enable-libebur128'\n #confcmd += ' --enable-libkvazaar'\n # confcmd += ' --enable-librtmp'\n # confcmd += ' --enable-libsnappy'\n # confcmd += ' --enable-libgsm' # TODO fix headers /inc\n # confcmd += ' --enable-zimg'\n # confcmd += ' --enable-libbluray'\n # confcfg += ' --enable-libschrodeinger'\n # confcmd += ' --disable-devices'\n # confcmd += ' --enable-lto'\n if self.nonfree:\n confcmd += ' --enable-libfdk-aac'\n confcmd += ' --enable-nvenc'\n confcmd += ' --enable-openssl'\n\n os.system('make distclean')\n os.system(confcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n os.system('make tools/qt-faststart')\n os.system('cp tools/qt-faststart %s' % os.path.join(self.TARGET_DIR, 'bin'))\n\n # restore env\n os.putenv('CFLAGS', self.ENV_CFLAGS)\n os.putenv('CPPFLAGS', self.ENV_CFLAGS)\n os.putenv('LDFLAGS', self.ENV_LDFLAGS)\n\n def b_ffmbc(self):\n print('\\n*** Building ffmbc ***\\n')\n os.chdir(os.path.join(self.BUILD_DIR, 'ffmbc'))\n\n # modify env\n\n ENV_CFLAGS_NEW = '%s' % self.ENV_CFLAGS\n if self.build_static is True:\n ENV_CFLAGS_NEW += ' --static'\n os.putenv('CFLAGS', ENV_CFLAGS_NEW)\n os.putenv('CPPFLAGS', ENV_CFLAGS_NEW)\n ENV_LDFLAGS_NEW = self.ENV_LDFLAGS\n ENV_LDFLAGS_NEW += ' -fopenmp' # openmp is needed by soxr\n # ENV_LDFLAGS_NEW += ' -lstdc++' # stdc++ is needed by snappy\n os.putenv('LDFLAGS', ENV_LDFLAGS_NEW)\n\n confcmd = ''\n confcmd += './configure --prefix=%s' % self.TARGET_DIR\n confcmd += ' --extra-version=static'\n #if self.build_static is True:\n # confcmd += ' --pkg-config-flags=\"--static\"'\n confcmd += ' --enable-gpl'\n if self.nonfree:\n confcmd += ' --enable-nonfree'\n if self.build_static is True:\n confcmd += ' --enable-static'\n confcmd += ' --disable-shared'\n else:\n confcmd += ' --disable-static'\n confcmd += ' --enable-static'\n confcmd += ' --disable-debug'\n confcmd += ' --disable-doc'\n confcmd += ' --enable-bzlib'\n confcmd += ' --enable-zlib'\n confcmd += ' --enable-libmp3lame'\n confcmd += ' --enable-libopenjpeg'\n confcmd += ' --enable-libvorbis'\n confcmd += ' --enable-libtheora'\n confcmd += ' --enable-libvpx'\n confcmd += ' --enable-libspeex'\n confcmd += ' --enable-libx264'\n confcmd += ' --enable-libfaac'\n confcmd += ' --enable-libfreetype'\n\n os.system('make distclean')\n os.system(confcmd)\n os.system('make -j %s && make install' % self.cpuCount)\n os.system('make tools/qt-faststart')\n os.system('cp tools/qt-faststart %s' % os.path.join(self.TARGET_DIR, 'bin'))\n\n # restore env\n os.putenv('CFLAGS', self.ENV_CFLAGS)\n os.putenv('CPPFLAGS', self.ENV_CFLAGS)\n os.putenv('LDFLAGS', self.ENV_LDFLAGS)\n\n def out_pack(self):\n os.chdir(self.OUT_DIR)\n for item in ['ffmpeg', 'ffprobe', 'tiffcp', 'tiffinfo', 'qt-faststart']:\n os.system('cp -f {0} ./'.format(os.path.join(self.TARGET_DIR, 'bin', item)))\n if self.build_static is False:\n for item in ['libx265.so.85', 'libvpx.so.4', 'libvorbisenc.so.2', 'libvorbis.so.0', 'libtwolame.so.0', 'libtheoraenc.so.1', 'libtheoradec.so.1', 'libspeex.so.1', 'libopenjpeg.so.1', 'libmp3lame.so.0', 'liblzma.so.5', 'libz.so.1', 'libssl.so.1.0.0', 'libcrypto.so.1.0.0', 'libwebp.so.6', 'libsoxr.so.0', 'libilbc.so.2', 'libfdk-aac.so.1', 'libebur128.so.1',]:\n os.system('cp -f {0} ./'.format(os.path.join(self.TARGET_DIR, 'lib', item)))\n os.system('strip *')\n os.chdir(self.ENV_ROOT)\n os.system('tar -cvf ./{0}.tar ./{0}'.format(self.OUT_FOLDER))\n os.system('xz -ve9 ./{0}.tar'.format(self.OUT_FOLDER))\n\n def u_striplibs(self):\n os.system('strip %s/*' % os.path.join(self.TARGET_DIR, 'bin'))\n os.system('strip %s/*' % os.path.join(self.TARGET_DIR, 'lib'))\n\n def go_setup(self):\n self.prewarn()\n self.cleanOUT_DIR_FILES()\n self.cleanOUT_DIR()\n self.cleanTARGET_DIR()\n self.cleanBUILD_DIR()\n\n self.setupDIR()\n self.f_getfiles()\n self.f_decompressfiles_gz()\n self.f_extractfiles(gzipMode=True)\n self.b_yasm()\n self.b_xz()\n self.f_decompressfiles_xz()\n self.f_extractfiles()\n self.f_repo_clone()\n self.f_repo_deploy()\n\n def go_main(self):\n self.b_openssl()\n self.b_cmake()\n self.b_zlib()\n self.b_bzip2()\n self.b_ncurses()\n #self.b_snappy()\n self.b_libtiff()\n self.b_libpng()\n self.b_openjpeg()\n self.b_libogg()\n self.b_libvorbis()\n self.b_libtheora()\n self.b_libvpx()\n self.b_speex()\n self.b_lame()\n self.b_twolame()\n self.b_soxr()\n self.b_wavpack()\n self.b_x264()\n self.b_x265()\n self.b_xvid()\n self.b_libgsm()\n self.b_libilbc()\n self.b_webp()\n self.b_opus()\n self.b_kvazaar()\n self.b_expat()\n self.b_freetype()\n self.b_fontconfig()\n self.b_libebur128()\n self.b_blackmagic()\n if self.nonfree:\n self.b_fdkaac()\n self.b_nvenc()\n self.b_openssl()\n\n def run(self):\n try:\n self.go_setup()\n self.go_main()\n self.b_ffmpeg()\n self.out_pack()\n except KeyboardInterrupt:\n print('\\nBye\\n')\n sys.exit(0)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-n', '--nonfree', dest='nonfree', help='build non-free/non-redist', action='store_true', default=False)\n parser.add_argument('--cflags', dest='cflags', help='add extra CFLAGS, like -march=native')\n parser.add_argument('-s', '--shared', dest='build_static', help='build shared', action='store_false', default=True)\n parser.add_argument('--setup', dest='do_setup', help='do setup and exit', action='store_true', default=False)\n parser.add_argument('--main', dest='do_main', help='do main and exit', action='store_true', default=False)\n parser.add_argument('--ff', dest='do_ffmpeg', help='do ffmpeg and exit', action='store_true', default=False)\n parser.add_argument('--fb', dest='do_ffmbc', help='do ffmbc and exit', action='store_true', default=False)\n parser.add_argument('--out', dest='do_out', help='do out pack and exit', action='store_true', default=False)\n args = parser.parse_args()\n\n ffmpegb = ffmpeg_build(nonfree=args.nonfree, cflags=args.cflags, build_static=args.build_static)\n\n if args.do_setup is True:\n ffmpegb.go_setup()\n elif args.do_main is True:\n ffmpegb.go_main()\n elif args.do_ffmpeg is True:\n ffmpegb.b_ffmpeg()\n elif args.do_ffmbc is True:\n ffmpegb.b_faac()\n ffmpegb.b_ffmbc()\n elif args.do_out is True:\n ffmpegb.out_pack()\n else:\n ffmpegb.run()\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":36547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"67816055","text":"import pygame\nfrom pygame.locals import *\nimport sys\nimport random\n\nclass FlyingNick:\n def __init__(self):\n self.screen = pygame.display.set_mode((400, 708))\n self.nick = pygame.Rect(65, 50, 50, 50)\n self.background = pygame.image.load(\"assets/background.jpg\").convert()\n self.nickSprite = [pygame.image.load(\"assets/22.png\").convert_alpha(),\n pygame.image.load(\"assets/02.png\").convert_alpha(),\n pygame.image.load(\"assets/dead.png\")] \n self.blockUp = pygame.image.load(\"assets/bottom.png\").convert_alpha()\n self.blockDown = pygame.image.load(\"assets/top.png\").convert_alpha()\n self.gap = 170\n self.blockX = 400\n self.nickY = 350\n self.jump = 0\n self.jumpSpeed = 10\n self.gravity = 5\n self.dead = False\n self.sprite = 0\n self.counter = 0\n self.offset = random.randint(-110, 110)\n \n def updateBlocks(self):\n self.blockX -= 2\n if self.blockX < -80:\n self.blockX = 400\n self.counter += 1\n self.offset = random.randint(-110, 110)\n \n def personageUpdate(self):\n if self.jump:\n self.jumpSpeed -= 1\n self.nickY -= self.jumpSpeed\n self.jump -= 1\n else:\n self.nickY += self.gravity\n self.gravity += 0.2 \n self.nick[1] = self.nickY \n up = pygame.Rect(self.blockX, \n 360 + self.gap - self.offset + 10, \n self.blockUp.get_width() - 10, \n self.blockUp.get_height())\n down = pygame.Rect(self.blockX, \n 0 - self.gap - self.offset - 10, \n self.blockUp.get_width() - 10, \n self.blockUp.get_height())\n if up.colliderect(self.nick):\n self.dead = True\n if down.colliderect(self.nick):\n self.dead = True\n if not 0 < self.nick[1] < 720:\n self.nick[1] = 50\n self.nickY = 50\n self.dead = False\n self.counter = 0\n self.blockX = 400\n self.offset = random.randint(-110, 110)\n self.gravity = 5\n \n def run(self):\n clock = pygame.time.Clock()\n pygame.font.init()\n font = pygame.font.SysFont(\"Times New Roman\", 50)\n while True:\n clock.tick(60)\n for event in pygame.event.get():\n \n if event.type == pygame.QUIT:\n sys.exit()\n if (event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN) and not self.dead:\n self.jump = 17\n self.gravity = 5\n self.jumpSpeed = 10\n \n self.screen.fill((255,255,255))\n self.screen.blit(self.background, (0, 0))\n self.screen.blit(self.blockUp, (self.blockX ,360 + self.gap - self.offset ))\n self.screen.blit(self.blockDown, (self.blockX , 0 - self.gap - self.offset))\n self.screen.blit(font.render(str(self.counter), -1, (255, 255, 255)), (200, 50))\n \n if self.dead:\n self.sprite = 2\n elif self.jump:\n self.sprite = 1\n \n self.screen.blit(self.nickSprite[self.sprite], (70 ,self.nickY))\n if not self.dead:\n self.sprite = 0\n self.updateBlocks()\n self.personageUpdate()\n pygame.display.update()\n \nif __name__ == \"__main__\":\n FlyingNick().run()\n ","sub_path":"flyingNick.py","file_name":"flyingNick.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"524901725","text":"class KeyVal:\n key = \"\"\n val = []\n\n def __init__(self, key, val):\n self.key = key\n self.val = val\n\n def get_key(self):\n return self.key\n\n def get_val(self):\n return self.val\n\n\ndef hash_string(string, table_size):\n next_map_value = 0\n # for each character in the string\n for char in string:\n # add that characters value to the total\n next_map_value += ord(char)\n # mod that value by the table size\n next_map_value %= table_size\n # return the generated hash value\n return next_map_value\n\n\ndef main():\n strings = [KeyVal(\"Calc 1\", [0]),\n KeyVal(\"Calc 2\", [1]),\n KeyVal(\"Calc 3\", [2]),\n KeyVal(\"Calc 4\", [7]),\n KeyVal(\"Tech Comm 1\", [3]),\n KeyVal(\"CSC 215\", [4]),\n KeyVal(\"CSC 150\", [5]),\n KeyVal(\"CSC 215\", [8]),\n KeyVal(\"CSC 215\", [9]),\n KeyVal(\"CSC 251\", [10]),\n KeyVal(\"CSC 251\", [6])]\n\n table_size = len(strings)\n # fill the hash_map with empty arrays so index errors do not occur\n hash_map = [[] for _ in range(table_size)]\n\n next_map_value = 0\n\n # for each string in list\n for key_val in strings:\n\n # get the hash value for the next key\n next_map_value = hash_string(key_val.key, table_size)\n\n # if the hash value index is available, fill it with the data\n if len(hash_map[next_map_value]) is 0:\n hash_map[next_map_value].append([key_val.key, key_val.val])\n # else check if they valid key is in that spot, and append the value to that spot\n elif hash_map[next_map_value][0][0] is key_val.key:\n hash_map[next_map_value][0][1].append(key_val.val[0])\n # else an open fill is needed\n else:\n # add one to the index\n i = next_map_value + 1\n # while i is in the table range\n while i <= table_size:\n # if reaching end of table range, reset to start of hash table\n if i >= table_size:\n i = 0\n # if the next spot is open, fill it with the data\n if len(hash_map[i]) is 0:\n hash_map[i].append([key_val.key, key_val.val])\n break\n # else check if the next spots key is the current key, and append the value to that spot\n elif hash_map[i][0][0] is key_val.key:\n hash_map[i][0][1].append(key_val.val[0])\n break\n # add one to index to check for the next spot\n i += 1\n\n print(hash_map)\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"StringHashTable.py","file_name":"StringHashTable.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"130243436","text":"\"\"\"\r\nSurvival Prediction Main Code - Multi-GPU Support\r\n\r\nWritten by Connor Squires for Survival Prediction in MRIs of Brain Tumours\r\nusing Deep Learning Final Year Project 2018\r\n\r\nSupervisor : Kamlesh Pawar\r\nLast Edited: October 2018\r\n\r\nExecuted on Tensorflow Version 1.4 - Keras 2.0.8\r\n\r\nDefines all image generators needed to exectute the model as defined in \r\npredictmodel_combined. The modelrun() function compiles the model and runs\r\nthrough each epoch with a given step size and batch size. \r\n\"\"\"\r\nimport pandas as pd\r\nimport glob\r\nimport nibabel as nib\r\nimport numpy as np\r\nimport predictmodel_combined as cnn3d\r\nimport keras\r\nfrom keras.utils import multi_gpu_model\r\nfrom keras import optimizers\r\nimport matplotlib.pyplot as plt\r\nimport collections as clt\r\n\r\nplt.switch_backend('agg')\r\n\r\n# Returns the spreadsheet in the form of a DataFrame with the minimum and\r\n# maximum survival days to reverse the normalisation\r\ndef load_csv(csvpath):\r\n csvpandas = pd.read_csv(csvpath, sep=\",\", header=0)\r\n csvpandas['BraTS18ID'] = csvpandas['BraTS18ID'].astype(str)\r\n maxpandas = csvpandas['Survival'].max()\r\n minpandas = csvpandas['Survival'].min()\r\n csvpandas['Survival'] = (csvpandas['Survival']-csvpandas['Survival'].min())/(csvpandas['Survival'].max()-csvpandas['Survival'].min())\r\n csvpandas['Age'] = csvpandas['Age']/90\r\n return csvpandas, maxpandas, minpandas\r\n\r\n# Augments the images based on a randomly generated index, 8 Augmentations\r\ndef augument_data(f_img, index):\r\n if index == 1:\r\n f_img = np.rot90(f_img, 1, (0, 1))\r\n elif index == 2:\r\n f_img = np.rot90(f_img, 2, (0, 1))\r\n elif index == 3:\r\n f_img = np.rot90(f_img, 3, (0, 1))\r\n elif index == 4:\r\n f_img = np.fliplr(f_img)\r\n elif index == 5:\r\n f_img = np.flipud(f_img)\r\n elif index == 6:\r\n f_img = np.rot90(np.flipud(f_img), 1, (0, 1))\r\n elif index == 7:\r\n f_img = np.rot90(np.flipud(f_img), 3, (0, 1))\r\n else:\r\n f_img = f_img\r\n return f_img\r\n\r\n# Uses the Nibabel function to read .nii image and return numpy array\r\ndef read_nii(f_name, index):\r\n f_img_obj = nib.load(f_name)\r\n f_img = np.single(f_img_obj.get_data())\r\n f_img = f_img/(np.max(f_img))\r\n f_img = augument_data(f_img, index)\r\n return f_img\r\n\r\n# Calculates the handcrafted features of the tumour\r\ndef lesion_generate(img_seg, img_flair):\r\n img_seg_flat = img_seg.flatten()\r\n img_seg_counter = clt.Counter(img_seg_flat)\r\n img_seg_counter = list(img_seg_counter.items())\r\n img_seg_counter = np.array(img_seg_counter)\r\n img_seg_counter = img_seg_counter[img_seg_counter[:, 0].argsort()]\r\n\r\n img_flair_flat = img_flair.flatten()\r\n img_flair_counter = clt.Counter(img_flair_flat)\r\n img_flair_counter = list(img_flair_counter.items())\r\n img_flair_counter = np.array(img_flair_counter)\r\n img_flair_counter = img_flair_counter[img_flair_counter[:, 0].argsort()]\r\n\r\n num0 = img_flair_counter[0, 1]\r\n not0 = (240*240*155)-num0\r\n NCRNET = (img_seg_counter[1, 1])\r\n ED = (img_seg_counter[2, 1])\r\n ET = (img_seg_counter[3, 1])\r\n lesion = NCRNET+ED+ET\r\n\r\n lesionperc = lesion/not0\r\n NCRNETperc = NCRNET/lesion\r\n EDperc = ED/lesion\r\n ETperc = ET/lesion\r\n\r\n lesiondata = np.array([lesionperc, NCRNETperc, EDperc, ETperc])\r\n return lesiondata\r\n\r\n# Training Data Generator, yielding a stack of the 5 inputs images, the\r\n# handcrafted inputs and the output in days\r\ndef generate_data(path, csvpath, batches, gpu_number):\r\n img_dir = glob.glob(path)\r\n numfiles = len(img_dir)\r\n numaugs = 8\r\n samples = np.zeros((batches, 240, 240, 155, 5))\r\n days = np.zeros((batches, 1))\r\n handcraft = np.zeros((batches, 5))\r\n\r\n# Creates an randomised array of length Number of Files* Augmentation\r\n# 1st Column references what image set to use, 2nd is what augmentation\r\n sequence = np.column_stack((np.tile(np.arange(numfiles), numaugs), np.repeat(np.arange(numaugs), numfiles)))\r\n trainoutput, maxpandas, minpandas = load_csv(csvpath)\r\n while 1:\r\n shuffle = np.random.permutation((numaugs * numfiles))\r\n randsequence = sequence[shuffle, :]\r\n for j in range(0, ((numfiles * numaugs)-gpu_number), gpu_number):\r\n for batch in range(batches):\r\n f_name_flair = img_dir[randsequence[j+batch, 0]][:-10] + 'flair.nii.gz'\r\n f_name_t1 = img_dir[randsequence[j+batch, 0]][:-10] + 't1.nii.gz'\r\n f_name_t1ce = img_dir[randsequence[j+batch, 0]][:-10] + 't1ce.nii.gz'\r\n f_name_t2 = img_dir[randsequence[j+batch, 0]][:-10] + 't2.nii.gz'\r\n f_name_seg = img_dir[randsequence[j+batch, 0]][:-10] + 'seg.nii.gz'\r\n img_flair = read_nii(f_name_flair, randsequence[j+batch, 1])\r\n img_t1 = read_nii(f_name_t1, randsequence[j+batch, 1])\r\n img_t1ce = read_nii(f_name_t1ce, randsequence[j+batch, 1])\r\n img_t2 = read_nii(f_name_t2, randsequence[j+batch, 1])\r\n img_seg = read_nii(f_name_seg, randsequence[j+batch, 1])\r\n x = np.stack((img_flair, img_t1, img_t1ce, img_t2, img_seg), -1)\r\n samples[batch, :, :, :, :] = x\r\n name = img_dir[randsequence[j+batch, 0]][:-11]\r\n name = name.split('/')[6]\r\n location = trainoutput.loc[trainoutput['BraTS18ID'] == name].index[0]\r\n age = trainoutput.iat[location, 1]\r\n day = trainoutput.iat[location, 2]\r\n lesiondata = lesion_generate(img_seg, img_flair)\r\n handcrafted = np.append(lesiondata, age)\r\n handcrafted = np.reshape(handcrafted, (1, 5))\r\n days[batch, 0] = day\r\n handcraft[batch, :] = handcrafted\r\n yield [samples, handcraft], days\r\n\r\n# Validation Set Generator, no shuffling or augmentation used\r\ndef generate_data_val(path, csvpath, batches, gpu_number):\r\n img_dir = glob.glob(path)\r\n numfiles = len(img_dir)\r\n\r\n samples = np.zeros((batches, 240, 240, 155, 5))\r\n days = np.zeros((batches, 1))\r\n handcraft = np.zeros((batches, 5))\r\n\r\n trainoutput, maxpandas, minpandas = load_csv(csvpath)\r\n while 1:\r\n for j in range(0, (numfiles-gpu_number), gpu_number):\r\n for batch in range(batches):\r\n f_name_flair = img_dir[j+batch][:-10] + 'flair.nii.gz'\r\n f_name_t1 = img_dir[j+batch][:-10] + 't1.nii.gz'\r\n f_name_t1ce = img_dir[j+batch][:-10] + 't1ce.nii.gz'\r\n f_name_t2 = img_dir[j+batch][:-10] + 't2.nii.gz'\r\n f_name_seg = img_dir[j+batch][:-10] + 'seg.nii.gz'\r\n img_flair = read_nii(f_name_flair, 0)\r\n img_t1 = read_nii(f_name_t1, 0)\r\n img_t1ce = read_nii(f_name_t1ce, 0)\r\n img_t2 = read_nii(f_name_t2, 0)\r\n img_seg = read_nii(f_name_seg, 0)\r\n x = np.stack((img_flair, img_t1, img_t1ce, img_t2, img_seg), -1)\r\n samples[batch, :, :, :, :] = x\r\n name = img_dir[j+batch][:-11]\r\n name = name.split('/')[6]\r\n location = trainoutput.loc[trainoutput['BraTS18ID'] == name].index[0]\r\n age = trainoutput.iat[location, 1]\r\n day = trainoutput.iat[location, 2]\r\n lesiondata = lesion_generate(img_seg, img_flair)\r\n handcrafted = np.append(lesiondata, age)\r\n handcrafted = np.reshape(handcrafted, (1, 5))\r\n days[batch, 0] = day\r\n handcraft[batch, :] = handcrafted\r\n yield [samples, handcraft], days\r\n\r\n# Prediction dataset, Image inputs 1 at a time\r\ndef generate_data_predict(path, csvpath, batches):\r\n img_dir = sorted(glob.glob(path))\r\n numfiles = len(img_dir)\r\n samples = np.zeros((batches, 240, 240, 155, 5))\r\n days = np.zeros((batches, 1))\r\n handcraft = np.zeros((batches, 5))\r\n\r\n trainoutput, maxpandas, minpandas = load_csv(csvpath)\r\n\r\n while 1:\r\n for j in range(numfiles):\r\n f_name_flair = img_dir[j][:-10] + 'flair.nii.gz'\r\n f_name_t1 = img_dir[j][:-10] + 't1.nii.gz'\r\n f_name_t1ce = img_dir[j][:-10] + 't1ce.nii.gz'\r\n f_name_t2 = img_dir[j][:-10] + 't2.nii.gz'\r\n f_name_seg = img_dir[j][:-10] + 'seg.nii.gz'\r\n img_flair = read_nii(f_name_flair, 0)\r\n img_t1 = read_nii(f_name_t1, 0)\r\n img_t1ce = read_nii(f_name_t1ce, 0)\r\n img_t2 = read_nii(f_name_t2, 0)\r\n img_seg = read_nii(f_name_seg, 0)\r\n x = np.stack((img_flair, img_t1, img_t1ce, img_t2, img_seg), -1)\r\n samples[0, :, :, :, :] = x\r\n name = img_dir[j][:-11]\r\n name = name.split('/')[6]\r\n location = trainoutput.loc[trainoutput['BraTS18ID'] == name].index[0]\r\n age = trainoutput.iat[location, 1]\r\n day = trainoutput.iat[location, 2]\r\n lesiondata = lesion_generate(img_seg, img_flair)\r\n handcrafted = np.append(lesiondata, age)\r\n handcrafted = np.reshape(handcrafted, (1, 5))\r\n days[0, 0] = day\r\n handcraft[0, :] = handcrafted\r\n yield [samples, handcraft]\r\n\r\n# Compiles the individual models and combined model. Trains the model using\r\n# fit generator. Returns the numpy array of prediction. Saves the loss\r\n# history for both training and validation.\r\ndef modelrun():\r\n csvtrain = '/projects/ab57/connor/survival_data.csv'\r\n csvtest = '/projects/ab57/connor/survival_data_test.csv'\r\n\r\n trainpath = '/scratch/ab57/connor/Brats18Survival/Train/*/*seg.nii.gz'\r\n testpath = '/scratch/ab57/connor/Brats18Survival/Validate/*/*seg.nii.gz'\r\n\r\n adm = optimizers.Adam(lr=0.00005)\r\n model = cnn3d.prediction3d()\r\n model.compile(optimizer=adm, loss='mean_squared_error')\r\n\r\n modelhand = cnn3d.predictionhand()\r\n modelhand.compile(optimizer=adm, loss='mean_squared_error')\r\n\r\n merging = cnn3d.merging(model.output, modelhand.output, model.input, modelhand.input)\r\n merging.compile(optimizer=adm, loss='mean_squared_error')\r\n\r\n gpu_number = 3\r\n merging_parrallel = multi_gpu_model(merging, gpus=gpu_number)\r\n merging_parrallel.compile(optimizer=adm, loss='mean_squared_error')\r\n\r\n batchsize_train = gpu_number\r\n batchsize_test = gpu_number\r\n batchsize_predict = 1\r\n steps_train = gpu_number*64\r\n steps_test = gpu_number*4\r\n steps_predict = 36\r\n epochs = 50\r\n generator_train = generate_data(trainpath, csvtrain, batchsize_train, gpu_number)\r\n generator_test = generate_data_val(testpath, csvtrain, batchsize_test, gpu_number)\r\n generator_predict = generate_data_predict(testpath, csvtest, batchsize_predict)\r\n\r\n# Callback class to allow callbacks when multi-gpu is used. Is called on the\r\n# single gpu model and weights are saved\r\n class MyCbk(keras.callbacks.Callback):\r\n\r\n def __init__(self, model):\r\n self.model_to_save = model\r\n self.epoch = 1\r\n\r\n def on_epoch_end(self, epoch, logs=None):\r\n self.model_to_save.save_weights('/scratch/ab57/connor/modelsaves/modelsigmoid/modeladmmweights-{epoch:%03d}.h5' % self.epoch)\r\n self.epoch += 1\r\n\r\n modelsave = MyCbk(merging)\r\n callback_group = [modelsave]\r\n\r\n print('Model Is Go')\r\n merging_parrallel.fit_generator(generator_train, steps_per_epoch=steps_train,\r\n epochs=epochs, initial_epoch=0, verbose=1,\r\n validation_data=generator_test,\r\n validation_steps=steps_test, use_multiprocessing=True,\r\n callbacks=callback_group)\r\n print('Training is a Done Done')\r\n\r\n history_train = merging_parrallel.history.history['loss']\r\n nphistory_train = np.array(history_train)\r\n\r\n np.savetxt(\"/scratch/ab57/connor/modelsaves/modelsigmoid/loss_history_adam4layer.txt\", nphistory_train, delimiter=\", \")\r\n\r\n history_val = merging_parrallel.history.history['val_loss']\r\n nphistory_val = np.array(history_val)\r\n\r\n np.savetxt(\"/scratch/ab57/connor/modelsaves/modelsigmoid/val_loss_history_adam4layer.txt\", nphistory_val, delimiter=\", \")\r\n\r\n merging.save_weights('/scratch/ab57/connor/modelsaves/modelsigmoid/my_modelextended_weights.h5')\r\n plt.figure(1)\r\n plt.plot(history_train)\r\n plt.plot(history_val)\r\n plt.title('model loss')\r\n plt.ylabel('loss')\r\n plt.xlabel('epoch')\r\n plt.legend(['train', 'test'], loc='upper left')\r\n plt.yscale('log')\r\n\r\n predictions = merging.predict_generator(generator_predict, use_multiprocessing=True, verbose=1, steps=steps_predict)\r\n return predictions\r\n\r\n# Analyses the prediction data and saves metrics to txt folders\r\ndef outputdata(predictions, foldername):\r\n csvtest = '/projects/ab57/connor/survival_data_test.csv'\r\n\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/scaledpredictions.txt\", predictions, delimiter=\", \")\r\n outputcsv, maxpandas, minpandas = load_csv(csvtest)\r\n outputscaled = outputcsv['Survival']\r\n outputscaled = outputscaled.to_frame()\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/scaledoutputs.txt\", outputscaled, delimiter=\", \")\r\n realoutput = outputscaled*((maxpandas-minpandas))+minpandas\r\n realpredict = predictions*((maxpandas-minpandas))+minpandas\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/realpredict.txt\", realpredict, delimiter=\", \")\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/realoutput.txt\", realoutput, delimiter=\", \")\r\n plt.figure(2)\r\n plt.plot(realoutput)\r\n plt.plot(realpredict)\r\n plt.title('predictions')\r\n plt.ylabel('survival days')\r\n plt.xlabel('test subject')\r\n plt.legend(['truthoutput', 'predictions'], loc='upper left')\r\n plt.savefig('/projects/ab57/connor/'+foldername+'/predictions.png')\r\n\r\n errorchecking = realoutput - realpredict\r\n absoluteerror = abs(errorchecking)\r\n MEA = absoluteerror.mean()\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/errorpredict.txt\", errorchecking, delimiter=\", \")\r\n plt.figure(3)\r\n plt.plot(errorchecking)\r\n plt.title('Error')\r\n plt.ylabel('Survival in Days Error')\r\n plt.xlabel('test subject')\r\n plt.legend(['Error'], loc='upper left')\r\n plt.savefig('/projects/ab57/connor/'+foldername+'/errors.png')\r\n return MEA, errorchecking, realoutput, realpredict\r\n\r\n\r\ndef outputdatatrain(predictions, foldername):\r\n csvtest = '/projects/ab57/connor/survival_data_train.csv'\r\n\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/scaledpredictions.txt\", predictions, delimiter=\", \")\r\n outputcsv, maxpandas, minpandas = load_csv(csvtest)\r\n outputscaled = outputcsv['Survival']\r\n outputscaled = outputscaled.to_frame()\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/scaledoutputs.txt\", outputscaled, delimiter=\", \")\r\n realoutput = outputscaled*((maxpandas-minpandas))+minpandas\r\n realpredict = predictions*((maxpandas-minpandas))+minpandas\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/realpredict.txt\", realpredict, delimiter=\", \")\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/realoutput.txt\", realoutput, delimiter=\", \")\r\n plt.figure(2)\r\n plt.plot(realoutput)\r\n plt.plot(realpredict)\r\n plt.title('predictions')\r\n plt.ylabel('survival days')\r\n plt.xlabel('test subject')\r\n plt.legend(['truthoutput', 'predictions'], loc='upper left')\r\n plt.savefig('/projects/ab57/connor/'+foldername+'/predictions.png')\r\n\r\n errorchecking = realoutput - realpredict\r\n absoluteerror = abs(errorchecking)\r\n MEA = absoluteerror.mean()\r\n np.savetxt(\"/projects/ab57/connor/\"+foldername+\"/errorpredict.txt\", errorchecking, delimiter=\", \")\r\n plt.figure(3)\r\n plt.plot(errorchecking)\r\n plt.title('Error')\r\n plt.ylabel('Survival in Days Error')\r\n plt.xlabel('test subject')\r\n plt.legend(['Error'], loc='upper left')\r\n plt.savefig('/projects/ab57/connor/'+foldername+'/errors.png')\r\n return MEA, errorchecking, realoutput, realpredict\r\n","sub_path":"imageprediction_multigpu.py","file_name":"imageprediction_multigpu.py","file_ext":"py","file_size_in_byte":16275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485008408","text":"import dropbox\nfrom secrets import DROPBOX_APP\n\n\nclass TransferData:\n def __init__(self, access_token):\n self.access_token = access_token\n\n def upload_file(self, file_from, file_to):\n dbx = dropbox.Dropbox(self.access_token)\n\n with open(file_from, 'rb') as f:\n dbx.files_upload(f.read(), file_to)\n\n\ndef upload_file_to_dropbox(file_path, upload_path):\n access_token = DROPBOX_APP\n transfer_data = TransferData(access_token)\n\n file_from = file_path\n file_to = upload_path # The full path to upload the file to, including the file name\n\n transfer_data.upload_file(file_from, file_to)","sub_path":"src/server/api/API_ingest/dropbox_handler.py","file_name":"dropbox_handler.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"636561582","text":"import itertools\r\n\r\ndef main():\r\n class Morph:\r\n def __init__(self, surface, base, pos, pos1):\r\n self.surface = surface\r\n self.base = base\r\n self.pos = pos\r\n self.pos1 = pos1\r\n\r\n def show(self):\r\n print(self.surface, self.base, self.pos, self.pos1)\r\n\r\n\r\n class Chunk:\r\n def __init__(self, sentence_id, chunk_id, dst, srcs):\r\n self.sentence_id = sentence_id\r\n self.chunk_id = chunk_id\r\n self.morphs = []\r\n self.dst = dst\r\n self.srcs = srcs\r\n self.has_noun = False\r\n self.has_verb = False\r\n self.has_particle = False\r\n self.surfaces = ''\r\n self.first_verb = None\r\n self.particle = []\r\n\r\n def show_morphs(self):\r\n morphs = ''\r\n for morph in self.morphs:\r\n morphs += morph.surface\r\n print(\"morphs:\", morphs)\r\n\r\n def show_chunk_id(self):\r\n print(\"==========\")\r\n print(\"chunk_id:\", self.chunk_id)\r\n\r\n def show_sentence_id(self):\r\n if (self.chunk_id == 0):\r\n print(\"====================\")\r\n print(\"sentence_id:\", self.sentence_id)\r\n\r\n def show_dst(self):\r\n print(\"dst:\", self.dst)\r\n\r\n def show_srcs(self):\r\n print(\"srcs:\", self.srcs[self.chunk_id])\r\n\r\n\r\n path = 'ai.ja.txt.parsed'\r\n with open(path, encoding=\"utf-8\") as f:\r\n text = f.read().split('\\n')\r\n result = []\r\n morphs = []\r\n chunks = []\r\n srcs = [[]]\r\n chunk = None\r\n sentence_id = 0\r\n chunk_id = 0\r\n\r\n for line in text[:-1]:\r\n if line == 'EOS':\r\n result.append(morphs)\r\n morphs = []\r\n sentence_id += 1\r\n chunk_id = 0\r\n srcs = [[]]\r\n\r\n elif line[0] == '*':\r\n if chunk:\r\n chunks.append(chunk)\r\n dst = int(line.split()[2][:-1])\r\n diff = dst + 1 - len(srcs)\r\n ex = [[] for _ in range(diff)]\r\n srcs.extend(ex)\r\n if dst != -1:\r\n srcs[dst].append(chunk_id)\r\n chunk = Chunk(sentence_id, chunk_id, dst, srcs)\r\n chunk_id += 1\r\n\r\n else:\r\n ls = line.split('\\t')\r\n d = {}\r\n tmp = ls[1].split(',')\r\n morph = Morph(ls[0], tmp[6], tmp[0], tmp[1])\r\n morphs.append(morph)\r\n chunk.morphs.append(morph)\r\n\r\n else:\r\n chunks.append(chunk)\r\n\r\n sentences = [[] for _ in range(len(chunks))]\r\n for chunk in chunks:\r\n for morph in chunk.morphs:\r\n chunk.surfaces += morph.surface\r\n if morph.pos == '動詞':\r\n if chunk.has_verb == False:\r\n chunk.first_verb = morph.base\r\n chunk.has_verb = True\r\n elif morph.pos == '名詞':\r\n chunk.has_noun = True\r\n elif morph.pos == '助詞':\r\n chunk.has_particle = True\r\n chunk.particle.append(morph.surface)\r\n\r\n sentences[chunk.sentence_id].append(chunk)\r\n\r\n dsts = [[] for _ in range(len(chunks))]\r\n for chunk in chunks:\r\n dst = sentences[chunk.sentence_id][chunk.dst]\r\n dsts[chunk.sentence_id].append(dst)\r\n\r\n with open('knock46.txt', mode='w', encoding=\"utf-8\") as f:\r\n for i, (sentence, dst) in enumerate(zip(sentences, dsts)):\r\n dic = {}\r\n\r\n for s, d in zip(sentence, dst):\r\n if s.particle and d.first_verb:\r\n old = dic.get(d.first_verb, [])\r\n surfaces = s.surfaces.replace(\" \", \"\").replace(\"。\", \"\").replace(\"、\", \"\")\r\n for p in s.particle:\r\n dic[d.first_verb] = old + [[p, surfaces]]\r\n for k, v in dic.items():\r\n ls = sorted(v)\r\n ls = list(zip(*ls))\r\n output = k + '\\t' + \" \".join(ls[0]) + '\\t' + \" \".join(ls[1]) + '\\n'\r\n f.write(output)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"yamaguchi/chapter05/knock46.py","file_name":"knock46.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"224183012","text":"from django.conf.urls import url\nfrom rest_framework.urlpatterns import format_suffix_patterns\nfrom sights import views\n\nurlpatterns = [\n url(r'^$', views.ApiRoot.as_view(), name='api-root'),\n\n url(r'^users/$', views.UserList.as_view(), name='user-list'),\n url(r'^users/(?P[0-9]+)/$', views.UserDetail.as_view(), name='user-detail'),\n url(r'^register/$', views.RegisterUser.as_view(), name='register'),\n url(r'^login/$', views.LoginUser.as_view(), name='login'),\n\n url(r'^locations/$', views.LocationList.as_view(), name='location-list'),\n url(r'^locations/(?P[0-9]+)/$', views.LocationDetail.as_view(), name='location-detail'),\n\n url(r'^visits/$', views.VisitList.as_view(), name='visit-list'),\n url(r'^visits/(?P[0-9]+)/$', views.VisitDetail.as_view(), name='visit-detail'),\n\n url(r'^locations/(?P[0-9]+)/visit$', views.LocationVisit.as_view(), name='location-visit'),\n\n url(r'^users/(?P[0-9]+)/ratio$', views.UserRatio.as_view(), name='user-ratio'),\n url(r'^locations/(?P[0-9]+)/ratio$', views.LocationRatio.as_view(), name='location-ratio'),\n\n url(r'^git$', views.Git.as_view(), name='git'),\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)\n","sub_path":"sights/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"477575198","text":"#! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3\n# 水水砂砂濃ビ\n# 1 2 10 20 15 200\nA, B, C, D, E, F = map(int, input().split())\nA *= 100\nB *= 100\nws = set([])\nss = set([])\nans = [A, 0]\nfor i in range(F // A + 1):\n for j in range((F - A * i) // B + 1):\n if 0 < A * i + B * j <= F:\n ws.add(A * i + B * j)\nfor i in range(F // C + 1):\n for j in range((F - C * i) // D + 1):\n if 0 < C * i + D * j <= F:\n ss.add(C * i + D * j)\nfor i in ws:\n for j in ss:\n if i + j <= F and j / i <= E / 100:\n if ans[1] / ans[0] < j / (i + j):\n ans = [i+j, j]\nprint(str(ans[0])+' '+str(ans[1]))\n","sub_path":"過去問/arc083_a/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"23218617","text":"\"\"\"\nJust to test database functions,\noutside of Flask.\n\nWe want to open our MongoDB database,\ninsert some memos, and read them back\n\"\"\"\nimport arrow\n\n# Mongo database\nfrom pymongo import MongoClient\nimport CONFIG\ntry: \n dbclient = MongoClient(CONFIG.MONGO_URL)\n db = dbclient.busytimes\n collection = db.dated\n\nexcept:\n print(\"Failure opening database. Is Mongo running? Correct password?\")\n sys.exit(1)\n\n#\n# Insertions: I commented these out after the first\n# run successfuly inserted them\n# \n\nrecord = { \"type\": \"dated_memo\",\n \"startTime\": '234',\n \"endTime\": '456',\n \"dates\": [{ \"date\":'123',\n \"data\":[['123','123'],\n ['123','1123']]\n },\n { \"date\":'123',\n \"data\":[['123','123'],\n ['123','1123']]\n }\n ]\n }\ncollection.insert(record)\nrecord = { \"type\": \"dated_memo\",\n \"startTime\": '244444',\n \"endTime\": '456',\n \"dates\": [{ \"date\":'123',\n \"data\":[['123','123'],\n ['123','1123']]\n },\n { \"date\":'123',\n \"data\":[['123','123'],\n ['123','1123']]\n }\n ]\n }\ncollection.insert(record)\ncollection.remove({})\n#\n# Read database --- May be useful to see what is in there,\n# even after you have a working 'insert' operation in the flask app,\n# but they aren't very readable. If you have more than a couple records,\n# you'll want a loop for printing them in a nicer format. \n#\n\nrecords = [ ] \nfor record in collection.find( { \"type\": \"dated_memo\" }):\n records.append(\n { \"startTime\": record['startTime'],\n \"endTime\": record['endTime'],\n \"dates\": [{ \"date\":'123',\n \"data\":[['123','123'],\n ['123','1123']]\n },\n { \"date\":'123',\n \"data\":[['123','123'],\n ['123','1123']]\n }\n ]\n })\nrecordss = [ ] \nfor record in collection.find( {}):\n print(record)\n","sub_path":"db_trial.py","file_name":"db_trial.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"365442928","text":"\"\"\"lampotilat URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.index, name='index'),\n path('tempchart', views.tempchart, name='tempchart'),\n path('movechart', views.movechart, name='movechart'),\n path('rainchart', views.rainchart, name='rainchart'),\n path('windchart', views.windchart, name='windchart'),\n path('means', views.means, name='means'),\n path('setup', views.setup, name='setup'),\n]","sub_path":"lampotilat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"587483445","text":"# -*- coding: utf-8 -*-\nfrom django.core.management import call_command\nfrom six import StringIO\n\n\ndef test_show_urls_format_dense():\n out = StringIO()\n call_command('show_urls', stdout=out)\n\n output = out.getvalue()\n assert \"/admin/\\tdjango.contrib.admin.sites.index\\tadmin:index\\n\" in output\n assert \"/admin//\\tdjango.contrib.admin.sites.app_index\\tadmin:app_list\\n\" in output\n\n\ndef test_show_urls_format_verbose():\n out = StringIO()\n call_command('show_urls', format=\"verbose\", stdout=out)\n\n output = out.getvalue()\n assert \"\"\"/login/\n\\tController: django.contrib.auth.views.LoginView\n\\tURL Name: login\"\"\" in output\n","sub_path":"tests/management/commands/test_show_urls.py","file_name":"test_show_urls.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"615193371","text":"def test(file1, file2):\n firstfile = open(file1, 'r')\n secondfile = open(file2, 'r')\n lines1 = []\n lines2 = []\n for line in firstfile:\n lines1.append(line)\n for line in secondfile:\n lines2.append(line)\n\n if len(lines1) != len(lines2):\n return False\n\n for i in range(0, len(lines1)):\n if (\"generated on\" not in lines1[i] and \"code class\" not in lines1[i]):\n if (lines1[i] != lines2[i]):\n return False\n\n return True \n","sub_path":"example/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"126511426","text":"from PyQt4 import QtCore, QtGui\n\nfrom Revolver.common import Tester\nfrom Revolver.classes import devices\nfrom Revolver.runnables import getPool, DoorRunner\nfrom Revolver.pytango import getMotorPosition\n\nfrom Revolver.UI.layout_dialog_calibration import Ui_Dialog\n\n\n\nclass CalibrationDialog(QtGui.QDialog, Tester, Ui_Dialog):\n # key for motors\n MOTORX = \"RAMANX\"\n MOTORY = \"RAMANY\"\n MOTORZ = \"RAMANZ\"\n\n # door\n DOOR = \"haspllabcl1.desy.de:10000/llab/door/haspllabcl1.01\"\n\n def __init__(self, parent=None):\n Tester.__init__(self)\n super(CalibrationDialog, self).__init__(parent=parent)\n\n self.setupUi(self)\n\n self.debug(\"Initialization of the calibration dialog\")\n\n self._thread_pool = getPool(parent=self)\n\n # get motor positions and set the corresponding spin boxes\n key = self.MOTORX\n spinbox = self.dsb_rbx\n value = getMotorPosition(devices.DEVICE_PATHS[key])\n if self.testFloat(value):\n spinbox.setValue(value)\n\n key = self.MOTORY\n spinbox = self.dsb_rby\n value = getMotorPosition(devices.DEVICE_PATHS[key])\n if self.testFloat(value):\n spinbox.setValue(value)\n\n key = self.MOTORZ\n spinbox = self.dsb_rbz\n value = getMotorPosition(devices.DEVICE_PATHS[key])\n if self.testFloat(value):\n spinbox.setValue(value)\n\n def calibrate(self, motor, value):\n \"\"\"\n Calibrates a motor via Sardana\n @return:\n \"\"\"\n self.debug(\"Calibrating a motor ({}) to the value ({})\".format(motor, value))\n cmdline = \"{} calibrate {} {}\".format(self.DOOR, motor, value)\n self.parent().jsRunMacro(cmdline)\n\n def actionSetMotorX(self):\n \"\"\"\n Calibrates rbx motor\n @return:\n \"\"\"\n motor = self.MOTORX.lower()\n value = self.dsb_rbx.value()\n self.calibrate(motor, value)\n\n def actionSetMotorY(self):\n \"\"\"\n Calibrates rby motor\n @return:\n \"\"\"\n motor = self.MOTORY.lower()\n value = self.dsb_rby.value()\n self.calibrate(motor, value)\n\n def actionSetMotorZ(self):\n \"\"\"\n Calibrates rbz motor\n @return:\n \"\"\"\n motor = self.MOTORZ.lower()\n value = self.dsb_rbz.value()\n self.calibrate(motor, value)\n \n def actionMotorXzero(self):\n \"\"\"\n Calibrates rbx motor to zero\n @return:\n \"\"\"\n motor = self.MOTORX.lower()\n self.calibrate(motor, 0.)\n\n def actionMotorYzero(self):\n \"\"\"\n Calibrates rby motor to zero\n @return:\n \"\"\"\n motor = self.MOTORY.lower()\n self.calibrate(motor, 0.)\n\n def actionMotorZzero(self):\n \"\"\"\n Calibrates rbz motor to zero\n @return:\n \"\"\"\n motor = self.MOTORZ.lower()\n self.calibrate(motor, 0.)","sub_path":"Revolver/gui_dialog_calibration.py","file_name":"gui_dialog_calibration.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"480955179","text":"#!/usr/bin/python3\nimport os\nimport pickle\nimport tkinter as tk\nimport tkinter.messagebox as tkMB\nfrom tkinter import ttk\n\nfrom tkinter.filedialog import askopenfilename as tkAOF\nfrom tkinter.filedialog import asksaveasfilename as tkASF\n\n\nclass mainApp():\n\n def __init__(self, masterloop):\n\n self.master = masterloop\n\n #inti main frame\n self.mainFrame = ttk.Frame(self.master)\n self.mainFrame.pack()\n #variables\n #color codes\n self.color_hardcode = {}\n self.init_hardcore_code()\n\n #suit data\n self.suit_data = {}\n self.init_def_suit_data()\n\n #default color theme gui\n self.default_color = {\"menu_bg\":\"#7c7f93\", \"menu_active\":\"#a6a8b6\", \"frame_bg\":\"#454754\", \n \"frame_sel\":\"\", \"but_clas_normal\":\"#35a3b2\", \"btn_clas_sel\":\"#35b283\"}\n\n self.style = ttk.Style()\n self.style.theme_use('vista')\n self.style.configure(\".\", bg=\"#454754\")\n \n # self.config_theme_style()\n\n #bits \n self.bits_light = list(\"00000000\")\n self.bits_color = list(\"00000000\")\n\n #internal comand history lists\n self.internal_history_light = []\n self.internal_history_color = []\n\n ###MAIN FILEs \n ## FOR EDITABLE FILE MUST BE IN BITS strings\n #contains only delay and command ( no first bayt, no xor, no end byte)\n # DICT[commandNUM] = {delay : floatSecond, commands=[] }\n self.bool_data_saved = False\n self.position_work_dict = 0\n self.working_dict_bits_string = {}\n\n self.position_history_wrok_dict = -1\n\n #call frames and pack them in\n #comand history\n self.history_comands_frame = ttk.Frame(self.mainFrame)\n self.history_comands_frame.pack(side=tk.LEFT, fill=\"y\")\n\n #bits menu\n self.bits_option_frame = ttk.Frame(self.mainFrame)\n self.bits_option_frame.pack(side=tk.LEFT, fill=\"y\")\n\n #suits asigne \n self.suits_frame = ttk.Frame(self.mainFrame)\n self.suits_frame.pack(side=tk.LEFT, fill=\"y\")\n\n #bottom status bar\n # self.status_bar_bot = ttk.Frame(self.mainFrame)\n # self.status_bar_bot.pack(anchor=tk.S, fill=\"x\")\n ##TOP MENU\n self.master.wm_title(\"Led Motion - Suffle 0.3v - DEMO\")\n self.menubar = tk.Menu(self.master)\n self.filemenu = tk.Menu(self.menubar, tearoff=0)\n self.filemenu.add_command(label='New File', command=self.new_file)\n self.filemenu.add_separator()\n self.filemenu.add_command(label='Open File', command=self.load_file)\n self.filemenu.add_command(label='Save File', command=self.save_file)\n self.filemenu.add_separator()\n self.filemenu.add_command(label='Exit', command=self.exit_program)\n self.menubar.add_cascade(label='File', menu=self.filemenu)\n\n self.editmenu = tk.Menu(self.master, tearoff=0)\n self.editmenu.add_command(label=\"Rename Suits\", command=self.rename_suit_window)\n self.menubar.add_cascade(label=\"Edit\", menu=self.editmenu)\n\n self.export_options = tk.Menu(self.master, tearoff=0)\n self.export_options.add_command(label=\"Led Motion V2\", command=self.led_motion_v2_export)\n self.export_options.add_separator()\n self.export_options.add_command(label=\"Suffle Sender\", command=self.suffle_sender_export)\n self.export_options.add_command(label=\"Export timer\", command=self.export_timer)\n self.export_options.add_command(label=\"Import Timer\", command=self.import_timer)\n self.menubar.add_cascade(label=\"Export\", menu=self.export_options)\n\n self.help_menu = tk.Menu(self.master, tearoff=0)\n self.help_menu.add_command(label=\"Dev TEST\", command=self.test_window)\n self.menubar.add_cascade(label=\"Help\", menu=self.help_menu)\n\n self.master.config(menu=self.menubar)\n#\n\n ### CALL FRAMES FOR MAIN PROGRAM\n self.init_fill_frames()\n ##END INIT CLASS\n\n #populate frames with functions\n def init_fill_frames(self):\n self.callFrame_history()\n self.callFrame_bits_options()\n self.callFrame_suits_gui()\n\n #set\n self.reset_suit_data()\n\n\n##BITS OPTIONS\n def callFrame_bits_options(self):\n self.color_light_top_lable = ttk.LabelFrame(\n self.bits_option_frame, text=\"Color / Light\")\n self.color_light_top_lable.pack(fill=\"y\", expand=\"yes\")\n # Color options\n self.color_cont_top_label = ttk.LabelFrame(self.color_light_top_lable, text=\"Color\")\n self.color_cont_top_label.pack(fill=\"both\", expand=\"yes\")\n # color listbox to select\n self.color_list_user_pick = tk.Listbox(self.color_cont_top_label, height=7, exportselection=False)\n self.color_list_user_pick.bind('<>', self.color_user_selected)\n self.color_list_user_pick.pack()\n for color in self.color_hardcode.keys():\n self.color_list_user_pick.insert(tk.END, color)\n # color label of userpick (control display)\n self.color_control_display = tk.Label(self.color_cont_top_label)\n self.color_control_display.pack(fill=\"both\", expand=\"yes\", padx=3, pady=5)\n # End of color\n # light options\n # light radiobuttons and checkboc values\n self.var_light_radion_master = tk.IntVar()\n self.var_light_head = tk.IntVar()\n self.var_light_armor = tk.IntVar()\n self.var_light_arm_left = tk.IntVar()\n self.var_light_arm_right = tk.IntVar()\n self.var_light_leg_left = tk.IntVar()\n self.var_light_leg_right = tk.IntVar()\n # main light label container\n self.light_cont_top_label = ttk.LabelFrame(self.color_light_top_lable, text=\"Lights\")\n # self.light_cont_top_label.configure(background=\"#a2a3a9\")\n self.light_cont_top_label.pack(fill=\"both\", expand=\"yes\")\n # light radio buttons\n self.radio_light_OFF = ttk.Radiobutton(self.light_cont_top_label, text=\"OFF\",\n variable=self.var_light_radion_master, value=1, command=self.radio_light)\n self.radio_light_ON = ttk.Radiobutton(self.light_cont_top_label, text=\"ON\",\n variable=self.var_light_radion_master, value=0, command=self.radio_light)\n self.radio_light_CUS = ttk.Radiobutton(self.light_cont_top_label, text=\"Custom\",\n variable=self.var_light_radion_master, value=2, command=self.radio_light)\n\n # pack light radio buttons\n self.radio_light_OFF.pack(anchor=tk.W)\n self.radio_light_ON.pack(anchor=tk.W)\n self.radio_light_CUS.pack(anchor=tk.W)\n #coustom labelframe\n self.light_custom_labelframe = ttk.Frame(self.light_cont_top_label)\n self.light_custom_labelframe.pack()\n # custom checkboxes\n self.cbox_light_head = tk.Checkbutton(self.light_custom_labelframe, text=\"Head\", variable=self.var_light_head,\n onvalue=1, offvalue=0, height=1, state='disabled', width=15, anchor=\"w\", padx=10)\n self.cbox_light_armor = tk.Checkbutton(self.light_custom_labelframe, text=\"Armor\", variable=self.var_light_armor,\n onvalue=1, offvalue=0, height=1, state='disabled', width=15, anchor=\"w\", padx=10)\n self.cbox_light_arm_left = tk.Checkbutton(self.light_custom_labelframe, text=\"Arm Left\", variable=self.var_light_arm_left,\n onvalue=1, offvalue=0, height=1, state='disabled', width=15, anchor=\"w\", padx=10)\n self.cbox_light_arm_right = tk.Checkbutton(self.light_custom_labelframe, text=\"Arm Right\", variable=self.var_light_arm_right,\n onvalue=1, offvalue=0, height=1, state='disabled', width=15, anchor=\"w\", padx=10)\n self.cbox_light_leg_left = tk.Checkbutton(self.light_custom_labelframe, text=\"Leg Left\", variable=self.var_light_leg_left,\n onvalue=1, offvalue=0, height=1, state='disabled', width=15, anchor=\"w\", padx=10)\n self.cbox_light_leg_right = tk.Checkbutton(self.light_custom_labelframe, text=\"Leg Right\", variable=self.var_light_leg_right,\n onvalue=1, offvalue=0, height=1, state='disabled', width=15, anchor=\"w\", padx=10)\n #checkbox pack\n self.cbox_light_head.pack()\n self.cbox_light_armor.pack()\n self.cbox_light_arm_left.pack()\n self.cbox_light_arm_right.pack()\n self.cbox_light_leg_left.pack()\n self.cbox_light_leg_right.pack()\n # #test button for output\n # self.btn_test_output_bits = tk.Button(self.bits_option_frame, text=\"Test output\", command=self.test_output)\n # self.btn_test_output_bits.pack()\n \n # #set value to radiobuttons\n # self.var_light_radion_master.set(1)\n self.radio_light()\n\n def init_hardcore_code(self):\n self.color_hardcode[\"Red\"] = {\"display\": \"#ff0000\", \"value\": \"0001\"}\n self.color_hardcode[\"Green\"] = {\"display\": \"#008000\", \"value\": \"0010\"}\n self.color_hardcode[\"Blue\"] = {\"display\": \"#0000ff\", \"value\": \"0100\"}\n self.color_hardcode[\"Cyan\"] = {\"display\": \"#00ffff\", \"value\": \"0110\"}\n self.color_hardcode[\"Magenta\"] = {\"display\": \"#ff00ff\", \"value\": \"0101\"}\n self.color_hardcode[\"Yellow\"] = {\"display\": \"#ffff00\", \"value\": \"0011\"}\n self.color_hardcode[\"White\"] = {\"display\": \"#ffffff\", \"value\": \"0111\"}\n def color_user_selected(self, event):\n # get color from user picked out of list\n # set bits light\n color = self.color_list_user_pick.get(self.color_list_user_pick.curselection())\n # print(color)\n self.color_control_display.configure(\n bg=self.color_hardcode[color][\"display\"], text=color)\n self.set_bits_color(self.color_hardcode[color][\"value\"])\n def set_bits_color(self, color_bits_hc):\n # change bits acording to user select from list\n self.bits_color = list(\"1111\" + color_bits_hc)\n # print(self.bits_color)\n def set_bits_light_on_save_to_suit(self):\n # change bits akording to checkboxes when asigned to suit\n self.bits_light = list(\"00000000\")\n if self.var_light_head.get() == 1:\n self.bits_light[7] = \"1\"\n if self.var_light_armor.get() == 1:\n self.bits_light[6] = \"1\"\n if self.var_light_arm_left.get() == 1:\n self.bits_light[5] = \"1\"\n if self.var_light_arm_right.get() == 1:\n self.bits_light[4] = \"1\"\n if self.var_light_leg_left.get() == 1:\n self.bits_light[3] = \"1\"\n if self.var_light_leg_right.get() == 1:\n self.bits_light[2] = \"1\"\n def radio_light(self):\n # check selected value of light radiobuttons\n if self.var_light_radion_master.get() == 1:\n print(\"Selected ALL PARTS = OFF\")\n self.light_checkbox_disable(False)\n self.light_checkbox_sel(False)\n elif self.var_light_radion_master.get() == 0:\n print(\"Selected ALL PARTS = ON\")\n self.light_checkbox_disable(False)\n self.light_checkbox_sel(True)\n elif self.var_light_radion_master.get() == 2:\n print(\"Selected CUSTOM PARTS\")\n self.light_checkbox_disable(True)\n self.light_checkbox_sel(False)\n def light_checkbox_sel(self, pick):\n #select or deselect value of light parts, called from radio_lights\n if pick:\n self.cbox_light_head.select()\n self.cbox_light_armor.select()\n self.cbox_light_arm_left.select()\n self.cbox_light_arm_right.select()\n self.cbox_light_leg_left.select()\n self.cbox_light_leg_right.select()\n else:\n self.cbox_light_head.deselect()\n self.cbox_light_armor.deselect()\n self.cbox_light_arm_left.deselect()\n self.cbox_light_arm_right.deselect()\n self.cbox_light_leg_left.deselect()\n self.cbox_light_leg_right.deselect()\n def light_checkbox_disable(self, enabled):\n #enable of disable checkbox clicability, called from radio_lights\n if enabled:\n self.cbox_light_head.configure(state='active')\n self.cbox_light_armor.configure(state='active')\n self.cbox_light_arm_left.configure(state='active')\n self.cbox_light_arm_right.configure(state='active')\n self.cbox_light_leg_left.configure(state='active')\n self.cbox_light_leg_right.configure(state='active')\n else:\n self.cbox_light_head.configure(state='disabled')\n self.cbox_light_armor.configure(state='disabled')\n self.cbox_light_arm_left.configure(state='disabled')\n self.cbox_light_arm_right.configure(state='disabled')\n self.cbox_light_leg_left.configure(state='disabled')\n self.cbox_light_leg_right.configure(state='disabled')\n\n##SUIT GUI PACK AND FUNCTIONS\n\n ##SUIT GUI PACK\n def callFrame_suits_gui(self):\n \n self.suits_frame_label = ttk.LabelFrame(self.suits_frame, text=\"Led Suits\")\n self.suits_frame_label.pack(anchor=tk.N, fill=\"both\", expand=\"yes\")\n\n # self.suit_bottom_frame = ttk.LabelFrame(self.suit)\n ##\n suit_frame_01 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 1\")\n suit_frame_02 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 2\")\n suit_frame_03 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 3\")\n suit_frame_04 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 4\")\n suit_frame_05 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 5\")\n suit_frame_06 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 6\")\n suit_frame_07 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 7\")\n suit_frame_08 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 8\")\n suit_frame_09 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 9\")\n suit_frame_10 = ttk.LabelFrame(self.suits_frame_label, text=\"Suit 10\")\n\n suit_frame_01.grid(row=0, column=0, columnspan=2, rowspan=2)\n suit_frame_02.grid(row=0, column=2, columnspan=2, rowspan=2)\n suit_frame_03.grid(row=0, column=4, columnspan=2, rowspan=2)\n suit_frame_04.grid(row=0, column=6, columnspan=2, rowspan=2)\n suit_frame_05.grid(row=0, column=8, columnspan=2, rowspan=2)\n suit_frame_06.grid(row=2, column=0, columnspan=2, rowspan=2)\n suit_frame_07.grid(row=2, column=2, columnspan=2, rowspan=2)\n suit_frame_08.grid(row=2, column=4, columnspan=2, rowspan=2)\n suit_frame_09.grid(row=2, column=6, columnspan=2, rowspan=2)\n suit_frame_10.grid(row=2, column=8, columnspan=2, rowspan=2)\n\n self.suit_name_01 = ttk.Label(suit_frame_01, text=\" \")\n self.suit_name_02 = ttk.Label(suit_frame_02, text=\" \")\n self.suit_name_03 = ttk.Label(suit_frame_03, text=\" \")\n self.suit_name_04 = ttk.Label(suit_frame_04, text=\" \")\n self.suit_name_05 = ttk.Label(suit_frame_05, text=\" \")\n self.suit_name_06 = ttk.Label(suit_frame_06, text=\" \")\n self.suit_name_07 = ttk.Label(suit_frame_07, text=\" \")\n self.suit_name_08 = ttk.Label(suit_frame_08, text=\" \")\n self.suit_name_09 = ttk.Label(suit_frame_09, text=\" \")\n self.suit_name_10 = ttk.Label(suit_frame_10, text=\" \")\n\n self.suit_name_01.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_02.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_03.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_04.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_05.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_06.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_07.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_08.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_09.pack(fill=\"both\", expand=\"yes\")\n self.suit_name_10.pack(fill=\"both\", expand=\"yes\")\n \n minisuit01 = tk.LabelFrame(suit_frame_01, bg=self.default_color[\"frame_bg\"])\n minisuit02 = tk.LabelFrame(suit_frame_02, bg=self.default_color[\"frame_bg\"])\n minisuit03 = tk.LabelFrame(suit_frame_03, bg=self.default_color[\"frame_bg\"])\n minisuit04 = tk.LabelFrame(suit_frame_04, bg=self.default_color[\"frame_bg\"])\n minisuit05 = tk.LabelFrame(suit_frame_05, bg=self.default_color[\"frame_bg\"])\n minisuit06 = tk.LabelFrame(suit_frame_06, bg=self.default_color[\"frame_bg\"])\n minisuit07 = tk.LabelFrame(suit_frame_07, bg=self.default_color[\"frame_bg\"])\n minisuit08 = tk.LabelFrame(suit_frame_08, bg=self.default_color[\"frame_bg\"])\n minisuit09 = tk.LabelFrame(suit_frame_09, bg=self.default_color[\"frame_bg\"])\n minisuit10 = tk.LabelFrame(suit_frame_10, bg=self.default_color[\"frame_bg\"])\n\n minisuit01.pack()\n minisuit02.pack()\n minisuit03.pack()\n minisuit04.pack()\n minisuit05.pack()\n minisuit06.pack()\n minisuit07.pack()\n minisuit08.pack()\n minisuit09.pack()\n minisuit10.pack()\n\n #labels light part colored\n self.head_01 = tk.Label(minisuit01, text=\"HEAD\")\n self.armor_01 = tk.Label(minisuit01, text=\"ARMOR\")\n self.armL_01 = tk.Label(minisuit01, text=\"LEFT ARM\")\n self.armR_01 = tk.Label(minisuit01, text=\"RIGHT ARM\")\n self.legL_01 = tk.Label(minisuit01, text=\"LEFT LEG\")\n self.legR_01 = tk.Label(minisuit01, text=\"RIGHT LEG\")\n\n self.head_01.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_01.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_01.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_01.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_01.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_01.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_02 = tk.Label(minisuit02, text=\"HEAD\")\n self.armor_02 = tk.Label(minisuit02, text=\"ARMOR\")\n self.armL_02 = tk.Label(minisuit02, text=\"LEFT ARM\")\n self.armR_02 = tk.Label(minisuit02, text=\"RIGHT ARM\")\n self.legL_02 = tk.Label(minisuit02, text=\"LEFT LEG\")\n self.legR_02 = tk.Label(minisuit02, text=\"RIGHT LEG\")\n\n self.head_02.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_02.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_02.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_02.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_02.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_02.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_03 = tk.Label(minisuit03, text=\"HEAD\")\n self.armor_03 = tk.Label(minisuit03, text=\"ARMOR\")\n self.armL_03 = tk.Label(minisuit03, text=\"LEFT ARM\")\n self.armR_03 = tk.Label(minisuit03, text=\"RIGHT ARM\")\n self.legL_03 = tk.Label(minisuit03, text=\"LEFT LEG\")\n self.legR_03 = tk.Label(minisuit03, text=\"RIGHT LEG\")\n\n self.head_03.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_03.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_03.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_03.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_03.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_03.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_04 = tk.Label(minisuit04, text=\"HEAD\")\n self.armor_04 = tk.Label(minisuit04, text=\"ARMOR\")\n self.armL_04 = tk.Label(minisuit04, text=\"LEFT ARM\")\n self.armR_04 = tk.Label(minisuit04, text=\"RIGHT ARM\")\n self.legL_04 = tk.Label(minisuit04, text=\"LEFT LEG\")\n self.legR_04 = tk.Label(minisuit04, text=\"RIGHT LEG\")\n\n self.head_04.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_04.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_04.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_04.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_04.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_04.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_05 = tk.Label(minisuit05, text=\"HEAD\")\n self.armor_05 = tk.Label(minisuit05, text=\"ARMOR\")\n self.armL_05 = tk.Label(minisuit05, text=\"LEFT ARM\")\n self.armR_05 = tk.Label(minisuit05, text=\"RIGHT ARM\")\n self.legL_05 = tk.Label(minisuit05, text=\"LEFT LEG\")\n self.legR_05 = tk.Label(minisuit05, text=\"RIGHT LEG\")\n\n self.head_05.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_05.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_05.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_05.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_05.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_05.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_06 = tk.Label(minisuit06, text=\"HEAD\")\n self.armor_06 = tk.Label(minisuit06, text=\"ARMOR\")\n self.armL_06 = tk.Label(minisuit06, text=\"LEFT ARM\")\n self.armR_06 = tk.Label(minisuit06, text=\"RIGHT ARM\")\n self.legL_06 = tk.Label(minisuit06, text=\"LEFT LEG\")\n self.legR_06 = tk.Label(minisuit06, text=\"RIGHT LEG\")\n\n self.head_06.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_06.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_06.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_06.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_06.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_06.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_07 = tk.Label(minisuit07, text=\"HEAD\")\n self.armor_07 = tk.Label(minisuit07, text=\"ARMOR\")\n self.armL_07 = tk.Label(minisuit07, text=\"LEFT ARM\")\n self.armR_07 = tk.Label(minisuit07, text=\"RIGHT ARM\")\n self.legL_07 = tk.Label(minisuit07, text=\"LEFT LEG\")\n self.legR_07 = tk.Label(minisuit07, text=\"RIGHT LEG\")\n\n self.head_07.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_07.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_07.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_07.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_07.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_07.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_08 = tk.Label(minisuit08, text=\"HEAD\")\n self.armor_08 = tk.Label(minisuit08, text=\"ARMOR\")\n self.armL_08 = tk.Label(minisuit08, text=\"LEFT ARM\")\n self.armR_08 = tk.Label(minisuit08, text=\"RIGHT ARM\")\n self.legL_08 = tk.Label(minisuit08, text=\"LEFT LEG\")\n self.legR_08 = tk.Label(minisuit08, text=\"RIGHT LEG\")\n\n self.head_08.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_08.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_08.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_08.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_08.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_08.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_09 = tk.Label(minisuit09, text=\"HEAD\")\n self.armor_09 = tk.Label(minisuit09, text=\"ARMOR\")\n self.armL_09 = tk.Label(minisuit09, text=\"LEFT ARM\")\n self.armR_09 = tk.Label(minisuit09, text=\"RIGHT ARM\")\n self.legL_09 = tk.Label(minisuit09, text=\"LEFT LEG\")\n self.legR_09 = tk.Label(minisuit09, text=\"RIGHT LEG\")\n\n self.head_09.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_09.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_09.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_09.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_09.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_09.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n self.head_10 = tk.Label(minisuit10, text=\"HEAD\")\n self.armor_10 = tk.Label(minisuit10, text=\"ARMOR\")\n self.armL_10 = tk.Label(minisuit10, text=\"LEFT ARM\")\n self.armR_10 = tk.Label(minisuit10, text=\"RIGHT ARM\")\n self.legL_10 = tk.Label(minisuit10, text=\"LEFT LEG\")\n self.legR_10 = tk.Label(minisuit10, text=\"RIGHT LEG\")\n\n self.head_10.grid(row=0, column=0, columnspan=4, rowspan=2)\n self.armor_10.grid(row=2, column=0, columnspan=4, rowspan=2)\n self.armL_10.grid(row=4, column=0, columnspan=2, rowspan=2)\n self.armR_10.grid(row=4, column=2, columnspan=2, rowspan=2)\n self.legL_10.grid(row=6, column=0, columnspan=2, rowspan=2)\n self.legR_10.grid(row=6, column=2, columnspan=2, rowspan=2)\n\n\n suit_btn_apply01 = ttk.Button(suit_frame_01, text=\"Apply\", command=lambda:self.call_data_on_suit(1))\n suit_btn_apply02 = ttk.Button(suit_frame_02, text=\"Apply\", command=lambda:self.call_data_on_suit(2))\n suit_btn_apply03 = ttk.Button(suit_frame_03, text=\"Apply\", command=lambda:self.call_data_on_suit(3))\n suit_btn_apply04 = ttk.Button(suit_frame_04, text=\"Apply\", command=lambda:self.call_data_on_suit(4))\n suit_btn_apply05 = ttk.Button(suit_frame_05, text=\"Apply\", command=lambda:self.call_data_on_suit(5))\n suit_btn_apply06 = ttk.Button(suit_frame_06, text=\"Apply\", command=lambda:self.call_data_on_suit(6))\n suit_btn_apply07 = ttk.Button(suit_frame_07, text=\"Apply\", command=lambda:self.call_data_on_suit(7))\n suit_btn_apply08 = ttk.Button(suit_frame_08, text=\"Apply\", command=lambda:self.call_data_on_suit(8))\n suit_btn_apply09 = ttk.Button(suit_frame_09, text=\"Apply\", command=lambda:self.call_data_on_suit(9))\n suit_btn_apply10 = ttk.Button(suit_frame_10, text=\"Apply\", command=lambda:self.call_data_on_suit(10))\n\n suit_btn_apply01.pack(fill='x')\n suit_btn_apply02.pack(fill='x')\n suit_btn_apply03.pack(fill='x')\n suit_btn_apply04.pack(fill='x')\n suit_btn_apply05.pack(fill='x')\n suit_btn_apply06.pack(fill='x')\n suit_btn_apply07.pack(fill='x')\n suit_btn_apply08.pack(fill='x')\n suit_btn_apply09.pack(fill='x')\n suit_btn_apply10.pack(fill='x')\n\n\n suit_btn_app_color_only01 = ttk.Button(suit_frame_01, text=\"Color Only\", command=lambda:self.call_data_on_suit(1, True))\n suit_btn_app_color_only02 = ttk.Button(suit_frame_02, text=\"Color Only\", command=lambda:self.call_data_on_suit(2, True))\n suit_btn_app_color_only03 = ttk.Button(suit_frame_03, text=\"Color Only\", command=lambda:self.call_data_on_suit(3, True))\n suit_btn_app_color_only04 = ttk.Button(suit_frame_04, text=\"Color Only\", command=lambda:self.call_data_on_suit(4, True))\n suit_btn_app_color_only05 = ttk.Button(suit_frame_05, text=\"Color Only\", command=lambda:self.call_data_on_suit(5, True))\n suit_btn_app_color_only06 = ttk.Button(suit_frame_06, text=\"Color Only\", command=lambda:self.call_data_on_suit(6, True))\n suit_btn_app_color_only07 = ttk.Button(suit_frame_07, text=\"Color Only\", command=lambda:self.call_data_on_suit(7, True))\n suit_btn_app_color_only08 = ttk.Button(suit_frame_08, text=\"Color Only\", command=lambda:self.call_data_on_suit(8, True))\n suit_btn_app_color_only09 = ttk.Button(suit_frame_09, text=\"Color Only\", command=lambda:self.call_data_on_suit(9, True))\n suit_btn_app_color_only10 = ttk.Button(suit_frame_10, text=\"Color Only\", command=lambda:self.call_data_on_suit(10, True))\n\n suit_btn_app_color_only01.pack(fill='x')\n suit_btn_app_color_only02.pack(fill='x')\n suit_btn_app_color_only03.pack(fill='x')\n suit_btn_app_color_only04.pack(fill='x')\n suit_btn_app_color_only05.pack(fill='x')\n suit_btn_app_color_only06.pack(fill='x')\n suit_btn_app_color_only07.pack(fill='x')\n suit_btn_app_color_only08.pack(fill='x')\n suit_btn_app_color_only09.pack(fill='x')\n suit_btn_app_color_only10.pack(fill='x')\n\n ##\n ##delay options\n delay_frame_label = ttk.LabelFrame(self.suits_frame, text=\"Time options\")\n delay_frame_label.pack(side=tk.LEFT)\n self.delay_sc = tk.DoubleVar()\n self.delay_man = tk.StringVar()\n\n self.delay_scale = tk.Scale(delay_frame_label, orient=tk.HORIZONTAL, variable=self.delay_sc, from_=0.01, to=10.0, length=600, digits=4, resolution=0.01, bg=\"#a2a3a9\", command=lambda x:self.check_delay(False))\n self.delay_scale.pack(side=tk.TOP)\n\n delay_label = ttk.Label(delay_frame_label, text=\"Time on in second\")\n delay_label.pack(side=tk.LEFT)\n\n self.delay_manual_entry = ttk.Entry(delay_frame_label, textvariable=self.delay_man)\n self.delay_manual_entry.pack(side=tk.LEFT)\n\n delay_man_button = ttk.Button(delay_frame_label, text=\"Set\", command=lambda:self.check_delay(True))\n delay_man_button.pack(side=tk.LEFT)\n\n ##buttom buttons\n btn_save_position = ttk.Button(self.suits_frame, text=\"Save as NEW Line\", command=self.save_current_position)\n btn_reset_suits = ttk.Button(self.suits_frame, text=\"Reset\", command=self.reset_suit_data)\n self.btn_save_to_history_EDIT = ttk.Button(self.suits_frame, text=\"Edite selected from history\", command=lambda:self.save_current_position(True))\n self.btn_insrt_into_history = ttk.Button(self.suits_frame, text=\"Insert into history selected\", command=self.insert_history_row)\n # btn_reset_suits.pack(side=tk.RIGHT)\n # btn_save_position.pack(side=tk.RIGHT)\n btn_save_position.pack(anchor=tk.SE, fill='both', pady=7)\n # btn_reset_suits.pack(anchor=tk.SE)\n btn_reset_suits.pack()\n # self.btn_save_to_history_EDIT.config(state=tk.DISABLED)\n self.btn_save_to_history_EDIT.pack(anchor=tk.SE, fill='both', pady=4)\n self.btn_insrt_into_history.pack(anchor=tk.SE, fill='both')\n self.dis_edite_button(False)\n ##\n ##SUIT FUNCTIONS\n def init_def_suit_data(self):\n #default frame, hold tmp data asigned to suit/ resets to 0\n self.suit_data[1] = {\"name\":\"Suit 1\", \"color\":[], \"light\":[]}\n self.suit_data[2] = {\"name\":\"Suit 2\", \"color\":[], \"light\":[]}\n self.suit_data[3] = {\"name\":\"Suit 3\", \"color\":[], \"light\":[]}\n self.suit_data[4] = {\"name\":\"Suit 4\", \"color\":[], \"light\":[]}\n self.suit_data[5] = {\"name\":\"Suit 5\", \"color\":[], \"light\":[]}\n self.suit_data[6] = {\"name\":\"Suit 6\", \"color\":[], \"light\":[]}\n self.suit_data[7] = {\"name\":\"Suit 7\", \"color\":[], \"light\":[]}\n self.suit_data[8] = {\"name\":\"Suit 8\", \"color\":[], \"light\":[]}\n self.suit_data[9] = {\"name\":\"Suit 9\", \"color\":[], \"light\":[]}\n self.suit_data[10] = {\"name\":\"Suit 10\", \"color\":[], \"light\":[]}\n\n def reset_suit_data(self):\n self.init_def_suit_data()\n for x in range(1,11):\n self.change_lable_colors_parts(x, \"demo\", [\"stupid\", \"empty\", \"list\"])\n\n def check_delay(self, from_entry):\n if from_entry:\n try:\n tmp_delay = float(self.delay_manual_entry.get())\n self.delay_scale.set(tmp_delay)\n print(tmp_delay)\n except ValueError:\n print(\"error input\")\n else:\n try:\n tmp_delay = self.delay_scale.get()\n self.delay_manual_entry.delete(0, tk.END)\n self.delay_manual_entry.insert(0, str(tmp_delay))\n except ValueError:\n print(\"Scale error\")\n\n def call_data_on_suit(self, suit, coloronly=False):\n if coloronly:\n tmp_light = self.suit_data[suit][\"light\"]\n self.change_data_suit(suit, tmp_light, self.bits_color)\n else:\n self.set_bits_light_on_save_to_suit()\n self.change_data_suit(suit, self.bits_light, self.bits_color)\n\n def change_data_suit(self, suit, light, color):\n ##gets internal called from data on suit check data and calls new config\n self.suit_data[suit][\"color\"] = color\n self.suit_data[suit][\"light\"] = light\n strcolor = ''.join(color)\n\n self.suit_tmp_color = None\n for col in self.color_hardcode.keys():\n if self.color_hardcode[col][\"value\"] == strcolor[-4:]:\n # chane_suit_gui(suit, 1, color_hardcode[col][\"display\"])\n self.suit_tmp_color = self.color_hardcode[col][\"display\"]\n\n part_to_turn_on = []\n tmp_light_list = list(light)\n if tmp_light_list[7] == '1':\n part_to_turn_on.append(\"head\")\n if tmp_light_list[6] == '1':\n part_to_turn_on.append(\"armor\")\n if tmp_light_list[5] == '1':\n part_to_turn_on.append(\"leftarm\")\n if tmp_light_list[4] == '1':\n part_to_turn_on.append(\"rightarm\")\n if tmp_light_list[3] == '1':\n part_to_turn_on.append(\"leftleg\")\n if tmp_light_list[2] == '1':\n part_to_turn_on.append(\"rightleg\")\n\n # print(\"color: \", self.suit_tmp_color)\n # print(\"parts: \", str(part_to_turn_on))\n self.change_lable_colors_parts(suit, self.suit_tmp_color, part_to_turn_on)\n ##\n def dis_edite_button(self, enable, leave_menu=False):\n if enable:\n self.btn_insrt_into_history.config(state=tk.NORMAL)\n self.btn_save_to_history_EDIT.config(state=tk.NORMAL)\n self.btn_DeleteHistory.config(state=tk.NORMAL)\n self.history_next_select.config(state=tk.NORMAL)\n self.history_back_select.config(state=tk.NORMAL)\n else:\n self.btn_save_to_history_EDIT.config(state=tk.DISABLED)\n self.btn_DeleteHistory.config(state=tk.DISABLED)\n self.btn_insrt_into_history.config(state=tk.DISABLED)\n if leave_menu:\n pass\n else:\n self.history_next_select.config(state=tk.DISABLED)\n self.history_back_select.config(state=tk.DISABLED)\n \n\n def change_lable_colors_parts(self, suit, color, part_list):\n ## with suit numb, define lable color on part activeted\n if suit == 1:\n if \"head\" in part_list:\n self.head_01.configure(bg=color)\n else:\n self.head_01.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_01.configure(bg=color)\n else:\n self.armor_01.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_01.configure(bg=color)\n else:\n self.armL_01.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_01.configure(bg=color)\n else:\n self.armR_01.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_01.configure(bg=color)\n else:\n self.legL_01.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_01.configure(bg=color)\n else:\n self.legR_01.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 2:\n if \"head\" in part_list:\n self.head_02.configure(bg=color)\n else:\n self.head_02.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_02.configure(bg=color)\n else:\n self.armor_02.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_02.configure(bg=color)\n else:\n self.armL_02.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_02.configure(bg=color)\n else:\n self.armR_02.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_02.configure(bg=color)\n else:\n self.legL_02.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_02.configure(bg=color)\n else:\n self.legR_02.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 3:\n if \"head\" in part_list:\n self.head_03.configure(bg=color)\n else:\n self.head_03.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_03.configure(bg=color)\n else:\n self.armor_03.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_03.configure(bg=color)\n else:\n self.armL_03.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_03.configure(bg=color)\n else:\n self.armR_03.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_03.configure(bg=color)\n else:\n self.legL_03.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_03.configure(bg=color)\n else:\n self.legR_03.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 4:\n if \"head\" in part_list:\n self.head_04.configure(bg=color)\n else:\n self.head_04.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_04.configure(bg=color)\n else:\n self.armor_04.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_04.configure(bg=color)\n else:\n self.armL_04.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_04.configure(bg=color)\n else:\n self.armR_04.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_04.configure(bg=color)\n else:\n self.legL_04.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_04.configure(bg=color)\n else:\n self.legR_04.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 5:\n if \"head\" in part_list:\n self.head_05.configure(bg=color)\n else:\n self.head_05.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_05.configure(bg=color)\n else:\n self.armor_05.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_05.configure(bg=color)\n else:\n self.armL_05.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_05.configure(bg=color)\n else:\n self.armR_05.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_05.configure(bg=color)\n else:\n self.legL_05.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_05.configure(bg=color)\n else:\n self.legR_05.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 6:\n if \"head\" in part_list:\n self.head_06.configure(bg=color)\n else:\n self.head_06.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_06.configure(bg=color)\n else:\n self.armor_06.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_06.configure(bg=color)\n else:\n self.armL_06.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_06.configure(bg=color)\n else:\n self.armR_06.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_06.configure(bg=color)\n else:\n self.legL_06.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_06.configure(bg=color)\n else:\n self.legR_06.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 7:\n if \"head\" in part_list:\n self.head_07.configure(bg=color)\n else:\n self.head_07.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_07.configure(bg=color)\n else:\n self.armor_07.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_07.configure(bg=color)\n else:\n self.armL_07.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_07.configure(bg=color)\n else:\n self.armR_07.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_07.configure(bg=color)\n else:\n self.legL_07.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_07.configure(bg=color)\n else:\n self.legR_07.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 8:\n if \"head\" in part_list:\n self.head_08.configure(bg=color)\n else:\n self.head_08.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_08.configure(bg=color)\n else:\n self.armor_08.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_08.configure(bg=color)\n else:\n self.armL_08.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_08.configure(bg=color)\n else:\n self.armR_08.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_08.configure(bg=color)\n else:\n self.legL_08.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_08.configure(bg=color)\n else:\n self.legR_08.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 9:\n if \"head\" in part_list:\n self.head_09.configure(bg=color)\n else:\n self.head_09.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_09.configure(bg=color)\n else:\n self.armor_09.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_09.configure(bg=color)\n else:\n self.armL_09.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_09.configure(bg=color)\n else:\n self.armR_09.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_09.configure(bg=color)\n else:\n self.legL_09.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_09.configure(bg=color)\n else:\n self.legR_09.configure(bg=self.default_color[\"frame_bg\"])\n elif suit == 10:\n if \"head\" in part_list:\n self.head_10.configure(bg=color)\n else:\n self.head_10.configure(bg=self.default_color[\"frame_bg\"])\n if \"armor\" in part_list:\n self.armor_10.configure(bg=color)\n else:\n self.armor_10.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftarm\" in part_list:\n self.armL_10.configure(bg=color)\n else:\n self.armL_10.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightarm\" in part_list:\n self.armR_10.configure(bg=color)\n else:\n self.armR_10.configure(bg=self.default_color[\"frame_bg\"])\n if \"leftleg\" in part_list:\n self.legL_10.configure(bg=color)\n else:\n self.legL_10.configure(bg=self.default_color[\"frame_bg\"])\n if \"rightleg\" in part_list:\n self.legR_10.configure(bg=color)\n else:\n self.legR_10.configure(bg=self.default_color[\"frame_bg\"])\n ##\n def save_current_position(self, edit=False):\n # self.btn_save_to_history_EDIT.config(state=tk.DISABLED)\n self.dis_edite_button(False)\n self.bool_data_saved = False\n\n command_list = []\n for key in range(1, 11):\n if self.suit_data[key][\"light\"] == []:\n command_list.append(\"00000000\")\n else:\n command_list.append( ''.join(self.suit_data[key][\"light\"]))\n if self.suit_data[key][\"color\"] == []:\n command_list.append(\"00000000\")\n else:\n command_list.append( ''.join(self.suit_data[key][\"color\"]))\n ###this is output for further calc == HEXA\n print(str(command_list))\n print(\"delay = \", str(self.delay_scale.get()))\n if edit:\n self.save_EDITE_history(self.delay_scale.get(), command_list)\n else:\n self.save_to_working_dict(self.delay_scale.get(), command_list)\n\n ##MASTER SAVE\n def save_to_working_dict(self, delay, comands):\n self.working_dict_bits_string[self.position_work_dict] = {\"delay\":delay, \"command\":comands}\n self.position_work_dict += 1\n self.update_history_box()\n\n def save_EDITE_history(self, delay, comands):\n # ind = self.history_list_box.get(self.history_list_box.curselection())\n # if self.position_history_wrok_dict > -1:\n ind = self.history_list_box.curselection()\n print(\"history index:\" + str(ind))\n self.working_dict_bits_string[ind[0]] = {\"delay\":delay, \"command\":comands}\n self.update_history_box()\n\n ##Rename logic and windown\n def rename_suit(self, suit, name):\n print(suit)\n print(name)\n # if what == 0:\n if suit == 1:\n self.suit_name_01.configure(text=name)\n elif suit == 2:\n self.suit_name_02.configure(text=name)\n elif suit == 3:\n self.suit_name_03.configure(text=name)\n elif suit == 4:\n self.suit_name_04.configure(text=name)\n elif suit == 5:\n self.suit_name_05.configure(text=name)\n elif suit == 6:\n self.suit_name_06.configure(text=name)\n elif suit == 7:\n self.suit_name_07.configure(text=name)\n elif suit == 8:\n self.suit_name_08.configure(text=name)\n elif suit == 9:\n self.suit_name_09.configure(text=name)\n elif suit == 10:\n self.suit_name_10.configure(text=name)\n #rename window\n def rename_suit_window(self):\n rename_win = tk.Toplevel(self.mainFrame)\n rename_win.wm_title(\"Led Motion - Rename Suits\")\n rename_text = tk.Label(rename_win, text=\"Select suit number, enter new name, press Rename\")\n rename_text.pack()\n suit_num = tk.Spinbox(rename_win, from_=1, to=10)\n suit_num.pack()\n new_name = tk.Entry(rename_win)\n new_name.pack()\n btn_rename = tk.Button(rename_win, text=\"Rename\", command=lambda:self.rename_suit(int(suit_num.get()), new_name.get()))\n btn_rename.pack()\n ##\n\n ###History frame far left\n\n def callFrame_history(self):\n \n history_label = ttk.LabelFrame(self.history_comands_frame, text=\"Command list\")\n history_label.pack(fill=\"y\", expand=\"yes\", padx=10)\n\n history_dis_label = ttk.Label(history_label, text=\"Command num - Time\")\n history_dis_label.pack()\n\n btnFrame = ttk.LabelFrame(history_label)\n btnFrame.pack(fill='x')\n\n self.history_back_select = ttk.Button(btnFrame, text=\"Back\", command=self.history_select_back)\n self.history_next_select = ttk.Button(btnFrame, text=\"Next\", command=self.history_select_next)\n\n self.history_back_select.pack(side=tk.LEFT)\n self.history_next_select.pack(side=tk.LEFT)\n \n listboxFrame = ttk.Frame(history_label)\n listboxFrame.pack(fill=\"y\", expand=\"yes\")\n\n self.history_list_box = tk.Listbox(listboxFrame, exportselection=False)\n self.history_list_box.pack(side=tk.LEFT, fill=\"y\", expand=\"yes\")\n\n scrollbar = ttk.Scrollbar(listboxFrame, orient=\"vertical\")\n scrollbar.config(command=self.history_list_box.yview)\n scrollbar.pack(side=tk.RIGHT, anchor=tk.NE, fill='y')\n \n self.history_list_box.config(yscrollcommand=scrollbar.set)\n\n self.btn_DeleteHistory = ttk.Button(history_label, text=\"Delete row\", command=self.delete_history_row)\n self.btn_DeleteHistory.pack(side=tk.BOTTOM, anchor=tk.S, fill=\"x\")\n\n\n self.tot_time_label = ttk.Label(history_label, text=\"Total time: \")\n self.tot_time_label.pack(side=tk.BOTTOM, padx=5)\n\n # Lb1.bind('<>', immediately)\n self.history_list_box.bind('<>', self.select_from_history)\n self.history_list_box.bind('', self.update_gpu_from_history)\n # self.history_list_box.bind('<>', self.dis_edite_button)\n\n def update_history_box(self):\n #read working dict\n tot_time = 0.0\n\n self.history_list_box.delete(0, last=tk.END)\n\n for x in self.working_dict_bits_string.keys():\n self.history_list_box.insert(x, str(x+1)+\" - \"+ str(self.working_dict_bits_string[x][\"delay\"]))\n tot_time += float(self.working_dict_bits_string[x][\"delay\"])\n\n self.history_list_box.see(tk.END)\n self.tot_time_label.configure(text=\"Total time: \"+str(round(tot_time, 2))+\" seconds.\")\n\n def select_from_history(self, event):\n # self.btn_save_to_history_EDIT.config(state=tk.NORMAL)\n self.dis_edite_button(True)\n \n tmp = self.history_list_box.curselection()[0]\n self.position_history_wrok_dict = tmp\n print(tmp)\n\n def update_gpu_from_history(self, event):\n self.dis_edite_button(False, True)\n tmp_comands = self.working_dict_bits_string[self.position_history_wrok_dict][\"command\"]\n tmp_time = self.working_dict_bits_string[self.position_history_wrok_dict][\"delay\"]\n posit = 0\n print(tmp_comands)\n if tmp_comands == []:\n pass\n self.reset_suit_data()\n else:\n for x in range(10):\n self.change_data_suit(x+1, tmp_comands[posit], tmp_comands[posit+1])\n posit += 2\n #change time delay\n self.delay_scale.set(tmp_time)\n\n def history_select_back(self):\n if self.position_history_wrok_dict > 0:\n self.history_list_box.select_clear(self.position_history_wrok_dict)\n self.position_history_wrok_dict -= 1\n self.history_list_box.select_set(self.position_history_wrok_dict)\n self.update_gpu_from_history(\"priv\")\n\n def history_select_next(self):\n if self.position_history_wrok_dict < self.history_list_box.size()-1:\n self.history_list_box.select_clear(self.position_history_wrok_dict)\n self.position_history_wrok_dict += 1\n self.history_list_box.select_set(self.position_history_wrok_dict)\n self.update_gpu_from_history(\"next\")\n\n def delete_history_row(self):\n\n self.history_list_box.delete(self.position_history_wrok_dict)\n\n for x in range(self.position_history_wrok_dict, len(self.working_dict_bits_string.keys())):\n # else:\n print(x)\n if x+1 == len(self.working_dict_bits_string.keys()):\n print(\"LAST\")\n del self.working_dict_bits_string[x]\n self.position_work_dict -= 1\n else:\n self.working_dict_bits_string[x] = self.working_dict_bits_string[x+1]\n\n self.update_history_box()\n\n def insert_history_row(self):\n print(\"insert\")\n\n ##END OF FUNCTIONS\n# ##test functions\n def test_window(self):\n testW = tk.Toplevel(self.master)\n\n print_work_dict = ttk.Button(testW, text=\"Print Working Dict\", command=self.test_print_working_dict)\n print_work_dict.pack()\n\n print_bits_light_color = ttk.Button(testW, text=\"Print Light Color\", command=self.test_output)\n print_bits_light_color.pack()\n\n btn_player = ttk.Button(testW, text=\"Player\", command=self.callFrame_Music)\n btn_player.pack()\n\n def test_output(self):\n self.set_bits_light_on_save_to_suit()\n print(\"Test output:\\nColor\")\n print(self.bits_color)\n print(\"Light\")\n print(self.bits_light)\n\n def test_print_working_dict(self):\n print(\"\\n\\n WORKING DICT \\n\")\n # print(str(self.working_dict_bits_string))\n for x in self.working_dict_bits_string.keys():\n print (str(x) + \" - \\n\" + str(self.working_dict_bits_string[x]))\n print(\"\\n POSITION\")\n print(self.position_work_dict)\n print(\"END \\n\\n\")\n\n ##topmenu functions\n def check_data_if_saved(self):\n if self.bool_data_saved:\n return 1\n else:\n if self.working_dict_bits_string == {}:\n return 1\n else:\n # self.ask_want_save()\n if tkMB.askyesno('Unsaved File', 'You are about to destroy unsaved file. Do you want to save it?'):\n self.save_file()\n else:\n pass\n\n def new_file(self):\n self.check_data_if_saved()\n self.working_dict_bits_string = {}\n self.reset_suit_data()\n self.history_list_box.delete(0, last=tk.END)\n\n def load_file(self):\n self.check_data_if_saved()\n self.working_dict_bits_string = {}\n self.reset_suit_data()\n self.history_list_box.delete(0, last=tk.END)\n \n filename = tkAOF(filetype=[(\"Led Command File\", \"*.suffle\")])\n print(filename)\n try:\n with open(filename, \"rb\") as f:\n self.working_dict_bits_string = pickle.load(f)\n self.position_work_dict = len(self.working_dict_bits_string)\n except FileNotFoundError:\n print(\"error loading file\")\n self.update_history_box()\n\n\n def save_file(self):\n filename = tkASF(filetype=[(\"Led Command File\", \"*.suffle\")])\n \n try:\n if filename[-7:] == \".suffle\":\n with open(filename, \"wb\") as f:\n pickle.dump(self.working_dict_bits_string, f)\n else:\n with open(filename + \".suffle\", \"wb\") as f:\n pickle.dump(self.working_dict_bits_string, f)\n except EnvironmentError:\n print(\"cant save file\")\n\n self.bool_data_saved = True\n\n def exit_program(self):\n self.check_data_if_saved()\n exit()\n\n def led_motion_v2_export(self):\n pass\n def suffle_sender_export(self):\n # self.check_data_if_saved()\n export_tmp_data = {}\n export_tmp_data = self.working_dict_bits_string\n\n ##testprint\n print(\"WORKING DICT BITS STRING\")\n print(str(self.working_dict_bits_string))\n print(str(export_tmp_data))\n\n export_position = 0\n export_command_string_hexa = {}\n\n for line in export_tmp_data.keys():\n tmp_commands = []\n hexa_cmd = []\n xor_sum = '0X05'\n # hexa_cmd.append(xor_sum, )\n\n for cmd in tmp_commands:\n hexa_cmd.append(hex(int(cmd, 2)).upper())\n\n for hexcmd in hexa_cmd:\n xor_sum = hex(int(xor_sum, 16) ^ int(hexcmd, 16))\n\n tmp_commands.append(\"0X05\")\n for hexcmd in hexa_cmd:\n tmp_commands.append(hexa_cmd)\n tmp_commands.append('0x0D')\n tmp_commands.append('0x0A')\n tmp_delay = export_tmp_data[line][\"delay\"]\n\n export_command_string_hexa[line] = {\"delay\":tmp_delay, \"command\":tmp_commands}\n\n self.save_export_suffle_sender(export_command_string_hexa)\n\n def save_export_suffle_sender(self, dict_to_save):\n filename = tkASF(filetype=[(\"Led Command File\", \"*.led\")])\n \n try:\n if filename[-4:] == \".led\": \n with open(filename, \"wb\") as f:\n pickle.dump(dict_to_save, f)\n else:\n with open(filename + \".led\", \"wb\") as f:\n pickle.dump(dict_to_save, f)\n except:\n print(\"cant save file\")\n\n def export_timer(self, filename=\"timer.mss\"):\n timer = []\n for x in self.working_dict_bits_string.keys():\n timer.append(self.working_dict_bits_string[x][\"delay\"])\n try: \n with open(filename, \"wb\") as f:\n pickle.dump(timer, f)\n except:\n print(\"cant save file\")\n\n def import_timer(self, filename=\"timer.mss\"):\n self.check_data_if_saved()\n timer = []\n try:\n with open(filename, \"rb\") as f:\n timer = pickle.load(f)\n except:\n print(\"cant import file\")\n pos = 0\n self.working_dict_bits_string = {}\n for x in timer:\n self.working_dict_bits_string[pos] = {\"delay\": x, \"command\":[]}\n pos += 1\n self.position_work_dict = len(self.working_dict_bits_string)\n self.update_history_box()\n #end topmenu functions\n\n####OPTIONAL GET BITS FROM MUSIC TO SET TIMER\n def callFrame_Music(self, timer=\"timer.mss\"):\n import pyaudio \n import wave \n\n self.chunk = 1024 \n\n p = pyaudio.PyAudio() \n fname = tkAOF\n f = wave.open(fname, \"rb\")\n\n #open stream \n stream = p.open(format = p.get_format_from_width(f.getsampwidth()), \n channels = f.getnchannels(), \n rate = f.getframerate(), \n output = True) \n #read data \n self.data = f.readframes(chunk) \n\n\n\n top_self_frame = tk.Toplevel(self.master)\n\n MusicMainFrame = ttk.LabelFrame(top_self_frame)\n MusicMainFrame.pack()\n #top frame load music\n btn_open_music_file = ttk.Button(MusicMainFrame, text=\"Load Music\", command=self.load_music_file)\n btn_calculate = ttk.Button(MusicMainFrame, text=\"Calculate Bits TIMER\", command=self.calculate_music_bits)\n btn_load_timer_to_builder = ttk.Button(MusicMainFrame, text=\"SEND TIMER TO BUILDER\", command=self.load_to_builder)\n\n btn_open_music_file.pack()\n btn_calculate.pack()\n btn_load_timer_to_builder.pack()\n\n # def load_music_file(self):\n \n###style\n\n##main call\nif __name__==\"__main__\":\n root = tk.Tk()\n app = mainApp(root)\n root.mainloop()\n","sub_path":"Gui_Light_Builder.py","file_name":"Gui_Light_Builder.py","file_ext":"py","file_size_in_byte":59857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"202266589","text":"### to see the different performance between multiple thread, multiple process and sequence processing\n### if the ~size~ is far too smaller, such as 1 or 10, then multiple threads will be out-performance than\n### multiple-process\n### if the ~size~ grows bigger, such as 1000 or 10000, then multiple process will be faster than multiple\n### thread\n\nimport threading\nimport multiprocessing\nimport random\nimport time\n\n\nsize = 100000\ncores = 4\nmy_list = [[] for _ in range(cores)]\nTIMES = 10\n\nDEBUG = False\n\n\ndef func(core, size, name='serial'):\n for i in range(size):\n my_list[core].append(random.random())\n if DEBUG:\n print(\"{} has {} elements in my_list[{}]\".format(name, len(my_list[core]), core))\n\n\ndef multithreaded(cores, size):\n threads = []\n for core in range(cores):\n threads.append(threading.Thread(target=func, args=(core, size, \"thread-{}\".format(core))))\n\n for i in range(cores):\n threads[i].start()\n for i in range(cores):\n threads[i].join()\n\n\ndef serial(cores, size):\n for core in range(cores):\n func(core, size)\n\n\ndef multiprocessed(cores, size):\n processes = []\n for core in range(cores):\n processes.append(multiprocessing.Process(target=func, args=(core, size, \"process-{}\".format(core))))\n for i in range(cores):\n processes[i].start()\n\n for i in range(cores):\n processes[i].join()\n\n\ndef timeit(mode, TIMES=100):\n if mode == \"thread\":\n costs = []\n for _ in range(TIMES):\n start = time.time()\n multithreaded(cores, size)\n end = time.time()\n costs.append(end-start)\n print(\"Evaluate threads mode {} times and the average cost is {}s\".format(TIMES, sum(costs)/TIMES))\n elif mode == \"serial\":\n costs = []\n for _ in range(TIMES):\n start = time.time()\n serial(cores, size)\n end = time.time()\n costs.append(end-start)\n print(\"Evaluate serial mode {} times and the average cost is {}s\".format(TIMES, sum(costs)/TIMES))\n elif mode == \"process\":\n costs = []\n for _ in range(TIMES):\n start = time.time()\n multiprocessed(cores, size)\n end = time.time()\n costs.append(end-start)\n print(\"Evaluate serial mode {} times and the average cost is {}s\".format(TIMES, sum(costs)/TIMES))\n\n\n\nif __name__ == \"__main__\":\n # multithreaded(cores, size)\n # serial(cores, size)\n # multiprocessed(cores, size)\n\n # timeit(\"serial\")\n timeit(\"thread\")\n timeit(\"process\")\n # global inteperter lock\n","sub_path":"benchmark.py","file_name":"benchmark.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"177808027","text":"import datetime\nimport json\nimport logging\nimport os\nimport time\nfrom collections import defaultdict\nfrom contextlib import contextmanager\n\nimport torch\nfrom fvcore.common.file_io import PathManager\nfrom fvcore.common.history_buffer import HistoryBuffer\n\n_CURRENT_STORAGE_STACK = []\n\n\ndef get_event_storage():\n assert len(_CURRENT_STORAGE_STACK), \\\n \"get_event_storage() has to be called inside a 'with EventStorage(...)' context!\"\n return _CURRENT_STORAGE_STACK[-1]\n\n\nclass EventWriter(object):\n def write(self):\n raise NotImplementedError\n\n def close(self):\n pass\n\n\nclass JSONWriter(EventWriter):\n def __init__(self, json_file, window_size=20):\n self._file_handle = PathManager.open(json_file, \"a\")\n self._window_size = window_size\n\n def write(self):\n storage = get_event_storage()\n to_save = {\"iteration\": storage.iter}\n to_save.update(storage.latest_with_smoothing_hint(self._window_size))\n self._file_handle.write(json.dumps(to_save, sort_keys=True) + \"\\n\")\n self._file_handle.flush()\n try:\n os.fsync(self._file_handle.fileno())\n except AttributeError:\n pass\n\n def close(self):\n self._file_handle.close()\n\n\nclass TensorboardXWriter(EventWriter):\n def __init__(self, log_dir: str, window_size: int = 20, **kwargs):\n self._window_size = window_size\n from torch.utils.tensorboard import SummaryWriter\n\n self._writer = SummaryWriter(log_dir, **kwargs)\n\n def write(self):\n storage = get_event_storage()\n for k, v in storage.latest_with_smoothing_hint(self._window_size).items():\n self._writer.add_scalar(k, v, storage.iter)\n\n if len(storage._vis_data) >= 1:\n for img_name, img, step_num in storage._vis_data:\n self._writer.add_image(img_name, img, step_num)\n storage.clear_images()\n\n if len(storage._histograms) >= 1:\n for params in storage._histograms:\n self._writer.add_histogram_raw(**params)\n storage.clear_histograms()\n\n def close(self):\n if hasattr(self, \"_writer\"):\n self._writer.close()\n\n\nclass CommonMetricPrinter(EventWriter):\n def __init__(self, max_iter):\n self.logger = logging.getLogger(__name__)\n self._max_iter = max_iter\n self._last_write = None\n\n def write(self):\n storage = get_event_storage()\n iteration = storage.iter\n\n try:\n data_time = storage.history(\"data_time\").avg(20)\n except KeyError:\n data_time = None\n\n eta_string = \"N/A\"\n try:\n iter_time = storage.history(\"time\").global_avg()\n eta_seconds = storage.history(\"time\").median(1000) * (self._max_iter - iteration)\n storage.put_scalar(\"eta_seconds\", eta_seconds, smoothing_hint=False)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n except KeyError:\n iter_time = None\n if self._last_write is not None:\n estimate_iter_time = (\n (time.perf_counter() - self._last_write[1]) / (iteration - self._last_write[0])\n )\n eta_seconds = estimate_iter_time * (self._max_iter - iteration)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n self._last_write = (iteration, time.perf_counter())\n\n try:\n lr = \"{:.6f}\".format(storage.history(\"lr\").latest())\n except KeyError:\n lr = \"N/A\"\n\n if torch.cuda.is_available():\n max_mem_mb = torch.cuda.max_memory_allocated() / 1024.0 / 1024.0\n else:\n max_mem_mb = None\n\n self.logger.info(\n \" eta: {eta} iter: {iter} {losses} {time}{data_time}lr: {lr} {memory}\".format(\n eta=eta_string,\n iter=iteration,\n losses=\" \".join(\n [\n \"{}: {:.3f}\".format(k, v.median(20))\n for k, v in storage.histories().items()\n if \"loss\" in k\n ]\n ),\n time=\"time: {:.4f} \".format(iter_time) if iter_time is not None else \"\",\n data_time=\"data_time: {:.4f} \".format(data_time) if data_time is not None else \"\",\n lr=lr,\n memory=\"max_mem: {:.0f}M\".format(max_mem_mb) if max_mem_mb is not None else \"\",\n )\n )\n\n\nclass EventStorage(object):\n def __init__(self, start_iter=0):\n self._history = defaultdict(HistoryBuffer)\n self._smoothing_hints = {}\n self._latest_scalars = {}\n self._iter = start_iter\n self._current_prefix = \"\"\n self._vis_data = []\n self._histograms = []\n\n def put_image(self, img_name, img_tensor):\n self._vis_data.append((img_name, img_tensor, self._iter))\n\n def put_scalar(self, name, value, smoothing_hint=True):\n name = self._current_prefix + name\n history = self._history[name]\n value = float(value)\n history.update(value, self._iter)\n self._latest_scalars[name] = value\n\n existing_hint = self._smoothing_hints.get(name)\n if existing_hint is not None:\n assert existing_hint == smoothing_hint, \\\n f\"Scalar {name} was put with a different smoothing_hint!\"\n else:\n self._smoothing_hints[name] = smoothing_hint\n\n def put_scalars(self, *, smoothing_hint=True, **kwargs):\n for k, v in kwargs.items():\n self.put_scalar(k, v, smoothing_hint=smoothing_hint)\n\n def put_histogram(self, hist_name, hist_tensor, bins=1000):\n ht_min, ht_max = hist_tensor.min().item(), hist_tensor.max().item()\n\n hist_counts = torch.histc(hist_tensor, bins=bins)\n hist_edges = torch.linspace(start=ht_min, end=ht_max, steps=bins + 1, dtype=torch.float32)\n\n hist_params = dict(\n tag=hist_name,\n min=ht_min,\n max=ht_max,\n num=len(hist_tensor),\n sum=float(hist_tensor.sum()),\n sum_squares=float(torch.sum(hist_tensor ** 2)),\n bucket_limits=hist_edges[1:].tolist(),\n bucket_counts=hist_counts.tolist(),\n global_step=self._iter,\n )\n self._histograms.append(hist_params)\n\n def history(self, name):\n ret = self._history.get(name, None)\n if ret is None:\n raise KeyError(f\"No history metric available for {name}!\")\n return ret\n\n def histories(self):\n return self._history\n\n def latest(self):\n return self._latest_scalars\n\n def latest_with_smoothing_hint(self, window_size=20):\n result = {}\n for k, v in self._latest_scalars.items():\n result[k] = self._history[k].median(window_size) if self._smoothing_hints[k] else v\n return result\n\n def smoothing_hints(self):\n return self._smoothing_hints\n\n def step(self):\n self._iter += 1\n self._latest_scalars = {}\n\n @property\n def iter(self):\n return self._iter\n\n @property\n def iteration(self):\n return self._iter\n\n def __enter__(self):\n _CURRENT_STORAGE_STACK.append(self)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n assert _CURRENT_STORAGE_STACK[-1] == self\n _CURRENT_STORAGE_STACK.pop()\n\n @contextmanager\n def name_scope(self, name):\n old_prefix = self._current_prefix\n self._current_prefix = name.rstrip(\"/\") + \"/\"\n yield\n self._current_prefix = old_prefix\n\n def clear_images(self):\n self._vis_data = []\n\n def clear_histograms(self):\n self._histograms = []\n","sub_path":"tkdet/utils/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":7748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"327534481","text":"import logging.config\nimport os\nfrom pathlib import Path\n\n# Build paths inside the project like this: BASE_DIR / 'subdir'.\nBASE_DIR = Path(__file__).resolve().parent.parent\n\nSTATIC_URL = '/api/static/'\nMEDIA_ROOT = '/'\nMEDIA_URL = '/'\n\nDATA_ROOT = Path('/data') # Files that are included in backups\nASSETS_ROOT = Path('/assets') # Files that can be regenerated, and don't need to be backed up\n\nARCHIVES_ROOT = DATA_ROOT / 'archives'\nBACKUPS_ROOT = DATA_ROOT / 'backups'\nMOUNTS_ROOT = DATA_ROOT / 'mounts'\nPREVIEWS_ROOT = ASSETS_ROOT / 'previews'\nSTATIC_ROOT = ASSETS_ROOT / 'static'\nENTRIES_DUMP_PATH = DATA_ROOT / 'all-entries.json'\n\nSSH_DIR = Path('/root/.ssh')\nTIMELINE_INCLUDE_FILE = '.timelineinclude'\n\n\n# Ensure that the absolute URLs in API responses are correct, even behind the reverse proxy\nUSE_X_FORWARDED_HOST = True\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = os.environ.get('BACKEND_SECRET_KEY', False)\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = os.environ.get('BACKEND_DEBUG', False) == '1'\nALLOWED_HOSTS = ['*']\n\n# Application definition\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django_filters',\n 'rest_framework',\n 'generic_relations',\n 'timeline.apps.TimelineConfig',\n 'archive.apps.ArchiveConfig',\n 'backup.apps.BackupConfig',\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'backend.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'backend.wsgi.application'\n\n\n# Database\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': 'timeline',\n 'USER': 'postgres',\n 'PASSWORD': 'postgres',\n 'HOST': 'timeline-db',\n 'PORT': 5432,\n }\n}\n\n# Logging\nLOGGING_CONFIG = None\nlogging.config.dictConfig({\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'console': {\n \"()\": \"coloredlogs.ColoredFormatter\",\n 'format': '%(asctime)s %(levelname)s [%(name)s:%(lineno)s] %(message)s',\n },\n },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'console',\n },\n },\n 'loggers': {\n '': {\n 'level': 'INFO',\n 'handlers': ['console'],\n },\n 'gunicorn.access': {\n 'level': 'ERROR',\n 'handlers': ['console'],\n 'propagate': True,\n 'qualname': 'gunicorn.access',\n }\n },\n})\n\n\n# Password validation\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nIMAGE_PREVIEW_SIZES = {\n 'thumbnail': {\n 'width': 1200,\n 'height': 200,\n },\n 'thumbnail2x': {\n 'width': 2400,\n 'height': 400,\n },\n 'preview': {\n 'width': 1800,\n 'height': 1200,\n },\n 'preview2x': {\n 'width': 3600,\n 'height': 2400,\n },\n}\n\nDOCUMENT_PREVIEW_SIZES = {\n 'thumbnail': {\n 'width': 1200,\n 'height': 200,\n },\n 'thumbnail2x': {\n 'width': 2400,\n 'height': 400,\n },\n 'preview': {\n 'width': 1800,\n 'height': 1800,\n },\n 'preview2x': {\n 'width': 3600,\n 'height': 3600,\n },\n}\n\nVIDEO_PREVIEW_SIZES = {\n 'thumbnail': {\n 'width': 400,\n 'height': 200,\n },\n 'preview': {\n 'width': 1280,\n 'height': 720,\n },\n}\n\nREST_FRAMEWORK = {\n 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination'\n}\n\n# In bytes\nMAX_PLAINTEXT_PREVIEW_SIZE = 10000 # 2KB = 1 page of text\n\n\n# Internationalization\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = False\nUSE_L10N = False\nUSE_TZ = True\n","sub_path":"backend/source/backend/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"604933460","text":"#!/usr/bin/python\n\nimport boto3\nimport json\nfrom boto3.s3.transfer import S3Transfer\nimport gzip\n\n\ndef poll_queue():\n print('Polling queue...')\n sqs = boto3.client('sqs')\n url = sqs.get_queue_url(QueueName='Cloudtrail-queue')['QueueUrl']\n messages = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10)\n if 'Messages' in messages:\n body = messages['Messages'][0]['Body']\n receipthandle = messages['Messages'][0]['ReceiptHandle']\n bucket = json.loads(body)['s3Bucket']\n object_key = json.loads(body)['s3ObjectKey'][0]\n\n parse_log(bucket, object_key)\n sqs.delete_message(QueueUrl=url, ReceiptHandle=receipthandle)\n else:\n print(\"There are no messages in the queue\")\n\n\ndef parse_log(bucket, logfile):\n s3 = boto3.client('s3')\n transfer = S3Transfer(s3)\n local_file = '/tmp/cloudtrail'\n\n transfer.download_file(bucket, logfile, local_file)\n\n file = gzip.open(local_file, \"r\")\n file_content = json.loads(file.read().decode(\"utf-8\"))['Records']\n for content in file_content:\n #print(content)\n if 'errorMessage' in content:\n if content['errorMessage'] == 'Failed authentication':\n print(\"Authentication failed username \", content['userIdentity']['userName'], \"from the ip address \", content['sourceIPAddress'],)\n file.close()\n\n\nif __name__ == \"__main__\":\n try:\n poll_queue()\n\n except:\n raise","sub_path":"cloudtrail_logger.py","file_name":"cloudtrail_logger.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"436171517","text":"\"\"\"Displays the original users message in regional letter indicators.\nInspired by an incident between *NIX and eggplantpatrol.\nWritten by Caleb-Shepard and kobeeraveendran.\nSome data structure revision by Khalil Wehmeyer\n\nFor the curious outsider, \"eggplantpatrol\" is the name of a user in \nthe UCF Computer Science Discord. We use \"eggplant\" interchangeably\nwith letters in their block emoji representation.\n\"\"\"\n\n#TODO add exception handling for words that span more than one message\n# e.g. a 1000 character single word will break this as it is inseparable\n# when it is expanded into eggplant format\n\nimport re\nimport nltk\n\nCOMMAND = \"eggplant\"\nCOMMAND_FORMAT = r\"^!{0} (?P.*)$\".format(COMMAND)\nMAX_MESSAGE_LENGTH = 1000\n\neggplant_dictionary = {\n '1': ':one:', \n '2': ':two:',\n '3': ':three:',\n '4': ':four:',\n '5': ':five:',\n '6': ':six:',\n '7': ':seven:',\n '8': ':eight:',\n '9': ':nine:',\n '0': ':zero:',\n '!': ':exclamation:'\n}\n\n# I'm trolling\n# you won't read this\ndef is_ascii(text):\n \"\"\"Confirm that the given text is all ASCII characters.\"\"\"\n return len(text) == len(text.encode())\n\n\nasync def command_eggplant(client, message):\n \"\"\"Eggplant a message.\"\"\"\n\n # If the message doesn't fit the command syntax or the message is not\n # all ASCII characters, then show the help message.\n command_match = re.match(COMMAND_FORMAT, message.content, re.DOTALL)\n if command_match is None or not is_ascii(command_match.group(\"rest\")):\n # TODO make this a variable that all modules can access and call? \n # The Lion should be authoritative over its plugins, not the other\n # way around @tgsachse \n syntax_error_response = \"Incorrect syntax. Try `!help`.\"\n await client.send_message(message.channel, syntax_error_response)\n return\n\n # Figure out who sent the command\n message_author_display_name = message.author.display_name\n message_body = command_match.group(\"rest\")\n\n \"\"\"Begin generating our response to the sender; this will be a list of words\n rather than a string to simplify, beautify, and optimize message splits\n when the character limit is surpassed. Messages will be split by word\n and never mid-word unless if absolutely neccessary\n \"\"\"\n full_response = []\n response = \"\"\n tokenized_message = nltk.word_tokenize(message_body)\n\n # Dictionary remapping of individual chatacters to their eggplant representation\n for word in tokenized_message:\n\n # convert a word into its eggplant representation\n eggplant_word = \"\"\n for char in word:\n if not is_ascii(char):\n pass\n elif char.isalpha():\n eggplant_word += \":regional_indicator_\" + char.lower() + \": \"\n elif char in eggplant_dictionary:\n eggplant_word += eggplant_dictionary[char] + ' '\n else:\n pass # ;)\n\n if len(eggplant_word) + len(response) < MAX_MESSAGE_LENGTH:\n response += eggplant_word\n else:\n # save one (1000 character or less) section of the message\n # so that the message may be split into different parts\n full_response.append(response)\n # reset the value of \"response\" and continue\n response = \"\"\n\n response += \" \"\n\n \"\"\"If the sender signature fits in the resulting message without overflowing\n to a new message, then add it to the end. Otherwise just send it separately\n \"\"\"\n if len(response + \" - \" + message_author_display_name) < MAX_MESSAGE_LENGTH:\n response += \" - \" + message_author_display_name\n full_response.append(response)\n else:\n full_response.append(\" - \" + message_author_display_name)\n\n\n \"\"\"There may be more than one message to send, so loop through the full response\n and send each message sequentially\n \"\"\"\n for response in full_response:\n await client.send_message(message.channel, response)\n","sub_path":"source/plugins/eggplant.py","file_name":"eggplant.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490171463","text":"import numpy as np\nimport scipy\nimport csv\nfrom scipy import linalg\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\n\n\n\nwith open('hw1-data/X_train.csv') as csvfile:\n\treadCSV = csv.reader(csvfile, delimiter=',')\n\trows = [row for row in readCSV]\nx_train = np.array(rows)\nx_train = x_train.astype(np.float)\nprint(x_train)\n\nwith open('hw1-data/y_train.csv') as csvfile:\n\treadCSV = csv.reader(csvfile, delimiter=',')\n\tp = []\n\tfor row in readCSV:\n\t\tp.append(row)\ny_train = np.array(p)\ny_train = y_train.astype(np.float)\nprint(y_train)\n\nprint(x_train.shape)\n\n\n#################\n#######(a)#######\n#################\n\nU, s, V = linalg.svd(x_train, full_matrices=False)\nS = linalg.diagsvd(s,7,7)\nprint(U.shape,S.shape,V.shape)\nprint(V.shape, inv(S).shape,U.T.shape, y_train.shape)\n\nw_ls = V.dot(inv(S)).dot(U.T).dot(y_train)\nprint(w_ls.shape)\n\n\n## Although I calculated SVD, I realized that using trace will be more convenient\n\nw_rr = np.zeros((7, 5001))\ndf = np.zeros(5001)\nfor i in range(5001):\n\tw_rr[:,i] = inv(i*np.identity(7) + x_train.T.dot(x_train)).dot(x_train.T).dot(y_train).flatten()\n\tdf[i] = np.trace(x_train.dot(inv(x_train.T.dot(x_train)+i*np.identity(7))).dot(x_train.T))\n\nprint(df)\nprint(w_rr)\n\n\nplt.plot(df[:],w_rr[0,:], 'r',label='d1')\nplt.plot(df[:],w_rr[1,:], 'b',label='d2')\nplt.plot(df[:],w_rr[2,:], 'g',label='d3')\nplt.plot(df[:],w_rr[3,:], 'y',label='d4')\nplt.plot(df[:],w_rr[4,:], 'k',label='d5')\nplt.plot(df[:],w_rr[5,:], 'c',label='d6')\nplt.plot(df[:],w_rr[6,:], 'm',label='d7')\nplt.ylabel('w_rr')\nplt.xlabel('df(lambda)')\nplt.legend(loc='lower left')\nplt.show()\n\n#################\n#######(c)#######\n#################\n\nwith open('hw1-data/X_test.csv') as csvfile:\n\treadCSV = csv.reader(csvfile, delimiter=',')\n\trows = [row for row in readCSV]\nx_test = np.array(rows)\nx_test = x_test.astype(np.float)\nprint(x_test.shape)\n\nwith open('hw1-data/y_test.csv') as csvfile:\n\treadCSV = csv.reader(csvfile, delimiter=',')\n\trows = [row for row in readCSV]\ny_test = np.array(rows)\ny_test = y_test.astype(np.float)\nprint(y_test.shape)\n\n\nrmse = np.zeros(51)\n\n\n\n\n\n\nfor i in range(51):\n\trmse[i] = np.sqrt((y_test - x_test.dot(w_rr[:,i]).reshape(42,1)).T.dot(y_test - x_test.dot(w_rr[:,i]).reshape(42,1))/42)\n\nlamb = np.linspace(0,50,51)\nprint(lamb)\n\nplt.plot(lamb[:],rmse[:], 'r.')\nplt.ylabel('RMSE')\nplt.xlabel('lambda')\nplt.show()\n\n#################\n#######(d)#######\n#################\n\ntmp2 = np.concatenate((np.square(x_train[:,0:6]),x_train[:,0:6]),axis=1)\nx2_train = np.concatenate((tmp2,np.ones((350,1))),axis=1)\ntmp3 = np.concatenate((tmp2,np.power(x_train[:,0:6],3)),axis=1)\nx3_train = np.concatenate((tmp3,np.ones((350,1))),axis=1)\n\ntmp_test2 = np.concatenate((np.square(x_test[:,0:6]),x_test[:,0:6]),axis=1)\nx2_test = np.concatenate((tmp_test2,np.ones((42,1))),axis=1)\ntmp_test3 = np.concatenate((tmp_test2,np.power(x_test[:,0:6],3)),axis=1)\nx3_test = np.concatenate((tmp_test3,np.ones((42,1))),axis=1)\n\nprint(x2_train.shape)\nprint(x3_train.shape)\n\nw_rr2 = np.zeros((13,501))\nfor i in range(501):\n\tw_rr2[:,i] = inv(i*np.identity(13) + x2_train.T.dot(x2_train)).dot(x2_train.T).dot(y_train).flatten()\nprint(w_rr2)\n\nw_rr3 = np.zeros((19,501))\nfor i in range(501):\n\tw_rr3[:,i] = inv(i*np.identity(19) + x3_train.T.dot(x3_train)).dot(x3_train.T).dot(y_train).flatten()\nprint(w_rr3)\n'''\nrmse1 = np.zeros(501)\n\nfor i in range(501):\n\trmse1[i] = np.sqrt((y_test - x_test.dot(w_rr[:,i]).reshape(42,1)).T.dot(y_test - x_test.dot(w_rr[:,i]).reshape(42,1))/42)\n\nrmse2 = np.zeros(501)\nfor i in range(501):\n\trmse2[i] = np.sqrt((y_test - x2_test.dot(w_rr2[:,i]).reshape(42,1)).T.dot(y_test - x2_test.dot(w_rr2[:,i]).reshape(42,1))/42)\n\nrmse3 = np.zeros(501)\nfor i in range(501):\n\trmse3[i] = np.sqrt((y_test - x3_test.dot(w_rr3[:,i]).reshape(42,1)).T.dot(y_test - x3_test.dot(w_rr3[:,i]).reshape(42,1))/42)\n\n\nlamb_poly = np.linspace(0,500,501)\n\nplt.plot(lamb_poly[:],rmse1[:],'r.',label='p=1')\nplt.plot(lamb_poly[:],rmse2[:],'b.',label='p=2')\nplt.plot(lamb_poly[:],rmse3[:],'g.',label='p=3')\nplt.ylabel('RMSE')\nplt.xlabel('lambda')\nplt.legend(loc='lower right')\nplt.show()\n'''\n","sub_path":"hw1/hw1-xx2241.py","file_name":"hw1-xx2241.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"509067443","text":"#\n# Bug: 82687\n# Title: EMI WMS problems with ISB tar file handling\n# Link: https://savannah.cern.ch/bugs/?82687\n#\n#\n\nimport logging\n\nfrom libutils.Exceptions import *\n\n\ndef run(utils):\n\n bug='82687'\n\n logging.info(\"Start regression test for bug %s\"%(bug))\n\n logging.info(\"Prepare jdl file for submission\")\n\n #Neccessary to avoid overwrite of the external jdls\n utils.use_external_jdl(\"%s.jdl\"%(bug)) \n utils.add_jdl_attribute(utils.get_jdl_file(),'VirtualOrganisation',\"\\\"%s\\\"\"%utils.VO)\n\n logging.info(\"Submit the job\")\n\n JOBID=utils.run_command_continue_on_error(\"glite-wms-job-submit %s --config %s --nomsg %s \"%(utils.get_delegation_options(),utils.get_config_file(),utils.get_jdl_file()))\n\n logging.info(\"Wait until job finishes\")\n\n utils.wait_until_job_finishes(JOBID)\n\n logging.info(\"Check job stauts\")\n\n utils.job_status(JOBID)\n\n if utils.get_job_status().find(\"Done (Success)\")!=-1:\n\n logging.info(\"Retrieve the output\")\n\n utils.run_command_continue_on_error (\"glite-wms-job-output --nosubdir --noint --dir %s %s \"%(utils.get_job_output_dir(),JOBID))\n\n logging.info(\"Check if the output files are correctly retrieved\")\n\n FILE=open(\"%s/ls.out\"%(utils.get_job_output_dir()))\n lines=FILE.readlines()\n FILE.close()\n\n ok=0\n\n for line in lines:\n if line.find(\"82687.jdl\")!=-1:\n ok=ok+1\n if line.find(\"supercalifragilistichespiralidose.txt\")!=-1:\n ok=ok+1\n\n\n if ok==2:\n logging.info(\"Output files are collectly retrieved\")\n else:\n logging.error(\"Test failed. Output files are not correctly retrieved\")\n raise GeneralError(\"Check output files\",\"Test failed. Output files are not correctly retrieved\")\n \n\n else:\n logging.error(\"Job status is not 'Done (Success)', job failed to terminated successfully. Status reason %s\"%(utils.get_StatusReason(JOBID)))\n raise GeneralError(\"Check job status\",\"Job status is not 'Done (Success)' but %s. Status reason %s\"%(utils.get_job_status(),utils.get_StatusReason(JOBID)))\n\n\n logging.info(\"End of regression test for bug %s\"%(bug))\n","sub_path":"regression_tests/bugs/82687.py","file_name":"82687.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"484494315","text":"import csv\n\n# Read in the CSV file using csv.reader\nwith open(\"./City_of_Seattle_Wage_Data.csv\", \"r\") as read_fh:\n\n # Store the header line in a variable using next (Links to an external site.)\n header = next(read_fh)\n input_list = list(csv.reader(read_fh))\n\n# Create a dictionary to store the list of 'Hourly Rate' by job title (hint: this is a dictionary where the value is a list - seattle[job] = [rates]. You'll need to use key in dictionary or dictionary.get to see if the key exists in each dictionary and create it if it does not, similar to counting with dictionaries.)\nhourly_rate_dict = {}\nfor line in enumerate(input_list):\n if line[1][-2] in hourly_rate_dict:\n # append the list with the rates\n hourly_rate_dict[line[1][-2]].append(line[1][-1])\n else:\n # create a new entry\n hourly_rate_dict[line[1][-2]] = [line[1][-1]]\n\n# After your data structure is created, use a for loop to go over each job and calculate the average pay\nfor job_title, salaries in hourly_rate_dict.items():\n temp_salary = 0\n for salary in salaries:\n temp_salary = temp_salary + float(salary)\n else:\n # Print a sentence for each job saying how many people work that job and what the average pay is. (hint: if there's one person, you just need to print the first value of the rates list)\n print (\"There are {} employees with the title \\\"{}\\\", and the average salary for that position is ${:.2f}.\".format(len(salaries), job_title, temp_salary / len(salaries)))\n\n# Calculate the highest paying job\n# find the highest paying salary in the original list\ntemp_salary = [0]\nfor line in input_list:\n temp_salary.append(float(line[-1]))\n\nmax_salary = (max(temp_salary))\n# iterate through the salaries and find the job title with the highest salary\ncurrent_max = 0\nfor job_title, salaries in hourly_rate_dict.items():\n for salary in salaries:\n if float(max(salaries)) > float(current_max):\n current_max = max(salaries)\nelse:\n print (\"The highest paying job is \\\"{}\\\", with a salary of ${}.\".format(job_title, current_max))\n\n# Print the seattle dictionary to a file\nwith open(\"output.txt\", \"w\") as write_fh:\n write_fh.write(str(hourly_rate_dict))\n","sub_path":"mod5_extra.py","file_name":"mod5_extra.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"158383358","text":"from __future__ import annotations \nimport collections \nimport random \nimport heapq \nimport math\nimport bisect\n\n\nclass Solution:\n def alphabetBoardPath(self, target: str) -> str:\n i = 0\n j = 0\n board = dict()\n for c in 'abcdefghijklmnopqrstuvwxyz':\n board[c] = (j, i)\n i += 1\n if i == 5:\n i = 0\n j += 1\n\n res = ''\n loc = (0, 0)\n i = 0\n while i < len(target) and target[i] == 'a':\n res += '!'\n i += 1\n while i < len(target):\n new_x, new_y = board[target[i]]\n\n if i > 0 and target[i-1] == 'z':\n # z case \n if new_x > loc[0]:\n res += 'D' * (new_x - loc[0])\n elif new_x < loc[0]:\n res += 'U' * abs(new_x - loc[0])\n if new_y > loc[1]:\n res += 'R' * (new_y - loc[1])\n elif new_y < loc[1]:\n res += 'L' * abs(new_y - loc[1])\n else:\n # normal \n if new_y > loc[1]:\n res += 'R' * (new_y - loc[1])\n elif new_y < loc[1]:\n res += 'L' * abs(new_y - loc[1])\n\n if new_x > loc[0]:\n res += 'D' * (new_x - loc[0])\n elif new_x < loc[0]:\n res += 'U' * abs(new_x - loc[0])\n\n res += '!'\n loc = (new_x, new_y)\n i += 1\n\n return res\n\n\ns = Solution()\n\ntarget = \"leet\"\nprint(s.alphabetBoardPath(target))\n\ntarget = \"code\"\nprint(s.alphabetBoardPath(target))\n\ntarget = \"a\"\nprint(s.alphabetBoardPath(target))\n\n\ntarget = \"\"\nprint(s.alphabetBoardPath(target))\n\ntarget = \"zb\"\nprint(s.alphabetBoardPath(target))\n\ntarget = \"zdz\"\nprint(s.alphabetBoardPath(target))\n","sub_path":"M_1138_alphabetBoardPath.py","file_name":"M_1138_alphabetBoardPath.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"583470337","text":"import numpy as np\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords\nfrom gensim import models\nimport scipy.spatial.distance as scp\n\nSTOPWORDS = stopwords.words('german')\n\nclass TextIterator:\n def __init__(self,corpus):\n self.text_list = self.init_text_list(corpus)\n\n def init_text_list(self, corpus):\n text_list = []\n if type(corpus) == type({}):\n for id in list(corpus):\n text_list.append(corpus[id].lower())\n elif type(corpus) == type([]):\n for id, text in corpus:\n text_list.append(text.lower())\n return text_list\n\n def __iter__(self): #iterator über die wörter im text\n for full_text in self.text_list:\n yield word_tokenize(full_text)\n\nclass Document:\n def __init__(self, id, text, embeddings, dim = 200):\n self.id = id\n self.text = text\n self.embedding, words_not_found = embed_document(self.text, embeddings, dim = dim)\n\n def get_id(self):\n return self.id\n\n def get_text(self):\n return self.text\n\n def get_embedding(self):\n return self.embedding\n\nclass Corpus:\n def __init__(self, corpus, embedding_path, dim = 200):\n #input corpus ist entweder liste [(id, doc_text),...] oder dict {id:doc_text}\n self.embeddings = self.train_word_embeddings(embedding_path, TextIterator(corpus), dim = dim)\n self.corpus_dict = self.import_corpus(corpus)\n self.embedding_matrix = [] #todo implement fast similarity computation via matrix\n self.dim = dim\n\n def import_corpus(self, corpus):\n dict = {}\n if type(corpus) == type({}):\n for id in list(corpus):\n dict[id] = Document(id, corpus[id], dim = self.dim)\n elif type(corpus) == type([]):\n for id, text in corpus:\n dict[id] = Document(id, text)\n return dict\n\n def train_word_embeddings(self, path, text_iterator, dim = 200, min_word_count = 5):\n model = models.Word2Vec(text_iterator, size=dim, min_count=min_word_count, workers=2)\n model.save(path + \"/embeddings.txt\")\n return model\n\n def fast_similarity(self, new_document, add_new_doc = False, top_n = 10):\n id, text = new_document #todo: in welchem Format kommen neue Dokumente allgemein an?\n if add_new_doc:\n self.embeddings.train([word.lower() for word in word_tokenize(text)])\n self.corpus_dict[id] = text\n\n document_similarities = [] #[(id,similarity),...]\n embedded_document = embed_document(text, self.embeddings, self.dim)\n\n #TODO: implement fast cosine similarity computation\n for id in list(self.corpus_dict):\n document_similarities.append((id, cosine_similarity(embedded_document, self.corpus_dict[id].get_embedding())))\n\n document_similarities = sorted(document_similarities, key = lambda x : x[1], reversed = True)\n if top_n == -1:\n return document_similarities\n else:\n return document_similarities[:top_n]\n\n\n\n\ndef cosine_similarity(vec1,vec2):\n return 1 - scp.cosine(vec1,vec2)\n\ndef embed_document(text, embeddings, dim = 200):\n result = np.zeros((dim,))\n words_not_found = []\n words = [word.lower() for word in word_tokenize(text) if word.lower() not in stopwords]\n for word in words:\n try:\n result += embeddings[word]\n except KeyError:\n words_not_found.append(word)\n return result, words_not_found\n\n\n","sub_path":"embeddingSimilarityPipeline/embedding_util.py","file_name":"embedding_util.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"236505480","text":"from scrapy.conf import settings\nimport pymongo\nimport gridfs\n\n\nclass MongoPipeline(object):\n \"\"\"\n Pipeline were we store the item in the database\n \"\"\"\n\n def __init__(self):\n connection = pymongo.MongoClient(\n settings['MONGODB_SERVER'],\n settings['MONGODB_PORT']\n )\n self.db = connection[settings['MONGODB_DB']]\n self.collection = self.db[settings['MONGODB_COLLECTION']]\n\n def process_item(self, item, spider):\n title = item['title'] or \"\"\n comic = item['comic']\n image = item['image']\n thumbnail = item['thumbnail']\n subtext = item['subtext']\n url = item['url']\n order = item['order']\n datetime = item['createdAt'] if 'createdAt' in item else None\n\n mongodb_item = self.collection.find_one({\n 'comic': comic,\n 'url': url\n })\n\n if not mongodb_item:\n fs = gridfs.GridFSBucket(self.db)\n file_id = fs.upload_from_stream(image, open(image))\n thumbnail_file_id = fs.upload_from_stream(image, open(thumbnail))\n\n self.collection.insert({\n 'comic': comic,\n 'title': title,\n 'image': image,\n 'file_id': file_id,\n 'text': subtext,\n 'url': url,\n 'order': order,\n 'createdAt': datetime,\n 'thumbnail': thumbnail_file_id\n })\n\n return item\n","sub_path":"scrape/existentialcomics/pipeline/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"145484340","text":"from django.conf.urls import patterns, include, url\nimport safeinside.views\n\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'safeinside.views.home', name='home'),\n # url(r'^safeinside/', include('safeinside.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n url(r'^$', safeinside.views.hello),\n url(r'^hello/$', safeinside.views.hello),\n url(r'^objects_list/(all)/$', safeinside.views.objectsList),\n url(r'^objects_list/(normal)/$', safeinside.views.objectsList),\n url(r'^objects_list/(test)/$', safeinside.views.objectsList),\n url(r'^objects_list/(disabled)/$', safeinside.views.objectsList),\n url(r'^objects_list/(enabled)/$', safeinside.views.objectsList),\n url(r'^objects_online_offline/(normal_standalone)/$', safeinside.views.objectsOnlineOffline),\n url(r'^objects_online_offline/(normal)/$', safeinside.views.objectsOnlineOffline),\n url(r'^object_info/(?P\\d+)/$', safeinside.views.objectInfo),\n url(r'^object_info/(?P\\d+)/(?P.+)/$', safeinside.views.objectInfo),\n url(r'^object_create/$', safeinside.views.objectCreate),\n url(r'^object_create/(?P\\d+)/$', safeinside.views.objectCreate),\n url(r'^object_rename/$', safeinside.views.objectRename),\n url(r'^object_change_state/(?P\\d+)/(?P.+)/$', safeinside.views.objectChangeState),\n url(r'^object_reload_firmware/$', safeinside.views.objectReloadFirmware),\n \n url(r'^objects_notregistered/$', safeinside.views.getUnregisteredObjects),\n url(r'^objects_count_events_by_type/(normal_standalone)/$', safeinside.views.objectsCountEventsByType),\n url(r'^objects_count_events_by_type/(normal)/$', safeinside.views.objectsCountEventsByType),\n\n url(r'^object_count_events_by_type/(normal)/(\\d*)/$', safeinside.views.objectCountEventsByType),\n url(r'^object_count_events_by_type/(normal_standalone)/(\\d*)/$', safeinside.views.objectCountEventsByType),\n url(r'^one_object_login/$', safeinside.views.oneObjectLogin),\n url(r'^one_object/$', safeinside.views.oneObject),\n)\n","sub_path":"web/safeinside/safeinside/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"257947347","text":"import os\nimport bitmarket_api\nimport pprint\nimport logging\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\ncredentials = bitmarket_api.JsonBitmarketCredentialsProvider(os.path.join(dir_path, \"config.json\"))\n\nlogger = logging.getLogger('bitmarket')\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(logging.FileHandler(\"log.txt\"))\nbitmarket = bitmarket_api.BitmarketAPI(credentials_provider=credentials, logger=logger)\n\npp = pprint.PrettyPrinter(depth=6)\n\nresponse_json = bitmarket.info()\npp.pprint(response_json)\n#response_json = bitmarket.trades('LTCPLN')\n#response_json = bitmarket.history('LTC')\n#response_json = bitmarket.public_trades(bitmarket.MARKET_LTCPLN)\nresponse_json = bitmarket.public_ticker(bitmarket.MARKET_LTCPLN)\n\npp.pprint(response_json)","sub_path":"trading/brokers/bitmarket/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420022301","text":"from pymongo import MongoClient\r\nimport json\r\n#Import the necessary methods from tweepy library\r\nfrom tweepy.streaming import StreamListener\r\nfrom tweepy import OAuthHandler\r\nfrom tweepy import Stream\r\n\r\n#Variables that contains the user credentials to access Twitter API \r\naccess_token = \"993861826910785536-SRwlwm6u1QnlMB8efcPYWURlniZi3o6\"\r\naccess_token_secret = \"YaxmO5FV7cVaLtb5xxxBMGtRr3HECFQSE7rAPrSwY3DSO\"\r\nconsumer_key = \"YGxg6Pv3b5DNIB4O9vIxhO8it\"\r\nconsumer_secret = \"dzqEyOncIN3TQ2ViOooPpEdKMxUz90Ub368RJw15vUXiIQamdi\"\r\n\r\n\r\n#This is a basic listener that just prints received tweets to stdout.\r\nclass StdOutListener(StreamListener):\r\n\r\n def on_data(self, data):\r\n client = MongoClient('localhost', 27017)\r\n db = client['twitter_db']\r\n collection = db['twitter_collection']\r\n tweet = json.loads(data)\r\n \r\n collection.insert(tweet)\r\n \r\n print(data)\r\n return True\r\n\r\n def on_error(self, status):\r\n print(status)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n #This handles Twitter authetification and the connection to Twitter Streaming API\r\n l = StdOutListener()\r\n auth = OAuthHandler(consumer_key, consumer_secret)\r\n auth.set_access_token(access_token, access_token_secret)\r\n stream = Stream(auth, l)\r\n\r\n #This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'\r\n stream.filter(track=['trump', 'modi', 'putin'])\r\n \r\n","sub_path":"TweetRead.py","file_name":"TweetRead.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"156710371","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2016 matsumoto \n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\n\n\"\"\"\nimport cv2\n\n\nclass DataAugmentation():\n\n def __init__(self, frame, in_size):\n self.frame = frame\n self.height, self.width = frame.shape[:2]\n self.frames = []\n self.in_size = in_size\n # print(frame.shape)\n # cv2.imwrite('result.jpg', frame)\n\n def slideWindows(self, frame):\n in_size = self.in_size\n # left up\n x = 0\n y = 0\n self.frames.append(frame[y:y + in_size, x:x + in_size])\n\n # left down\n x = 0\n y = self.height\n self.frames.append(frame[y - in_size:y, x:x + in_size])\n\n # right up\n x = self.width\n y = 0\n self.frames.append(frame[y:y + in_size, x - in_size:x])\n\n # right down\n x = self.width\n y = self.height\n self.frames.append(frame[y - in_size:y, x - in_size:x])\n\n # center\n x = (self.width // 2) - (in_size // 2)\n y = (self.height // 2) - (in_size // 2)\n self.frames.append(frame[y:y + in_size, x:x + in_size])\n\n def getFrames(self):\n self.slideWindows(self.frame)\n self.slideWindows(cv2.flip(self.frame, 1))\n return self.frames\n\n# if __name__ == '__main__':\n# in_size = 227\n#\n# cap = cv2.VideoCapture('test.mp4')\n# cap.set(cv2.CAP_PROP_POS_FRAMES, 30)\n# ret, frame = cap.read()\n# data_au = DataAugmentation(frame)\n# frames = data_au.getFrames()\n# i = 0\n# for f in frames:\n# i += 1\n# cv2.imwrite('f' + str(i) + '.jpg', f)\n# cap.release()\n","sub_path":"net_feat/dataaugmentation.py","file_name":"dataaugmentation.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"368306517","text":"import cv2\nimport os\nfrom time import sleep\n\n\ncam = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n\nwhile True:\n ret, img = cam.read()\n # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # faces = face_detector.detectMultiScale(gray, 1.3, 5)\n # for (x, y, w, h) in faces:\n # cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)\n # count += 1\n # Сохраняем лицо\n # cv2.imwrite('face/user.' + str(face_id) + '.' + str(count) + '.jpg', gray[y:y + h, x:x + w])\n cv2.imshow('image', img)\n k = cv2.waitKey(100) & 0xff # 'ESC'\n if k == 27:\n break\n # elif count >= 30: # Если сохранили 30 изображений выход.\n # break\nprint(\"\\n [INFO] Exiting Program and cleanup stuff\")\ncam.release()\ncv2.destroyAllWindows()\n","sub_path":"test_cam.py","file_name":"test_cam.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"581429564","text":"from sqlalchemy import String, Integer, ForeignKey, Column, Table\nfrom data.db_session import SqlAlchemyBase\nfrom sqlalchemy_serializer import SerializerMixin\n\nassociation_table = Table('association', SqlAlchemyBase.metadata, # промежуточная таблица категорий работ\n Column('jobs', Integer,\n ForeignKey('jobs.id')),\n Column('category', Integer,\n ForeignKey('category.id'))\n )\n\n\nclass Category(SqlAlchemyBase, SerializerMixin):\n __tablename__ = 'category'\n id = Column(Integer, primary_key=True, # id\n autoincrement=True)\n name = Column(String, nullable=False) # наименование категории\n","sub_path":"models/categories.py","file_name":"categories.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"323864985","text":"_WRITE_TO_DIR = 'machineFiles/'\n\n_MACHINES = (1, 2, 4, 8)\n_XeS_HOST = False\n\n_NODE_SUFFIX = 'soctf-pdc-'\n_XeS_NODES = tuple('{:03d}'.format(i) for i in range(1, 9))\n_i7_NODES = tuple('{:03d}'.format(i) for i in range(9, 17))\n_XeS_MAX_PROC = 20\n_i7_MAX_PROC = 8\n\nfor m in _MACHINES:\n\tif _XeS_HOST:\n\t\twith open(_WRITE_TO_DIR + '{}.mf'.format(m*_XeS_MAX_PROC), 'w') as XeSPure:\n\t\t\tXeSPure.write('\\n'.join((_NODE_SUFFIX + n) for n in _XeS_NODES[:m]))\n\t\t\tXeSPure.write('\\n')\n\telse:\n\t\twith open(_WRITE_TO_DIR + '{}.mf'.format(m*_i7_MAX_PROC), 'w') as i7Pure:\n\t\t\ti7Pure.write('\\n'.join((_NODE_SUFFIX + n) for n in _i7_NODES[:m]))\n\t\t\ti7Pure.write('\\n')\n\twith open(_WRITE_TO_DIR + '{}.mf'.format(m*(_i7_MAX_PROC + _XeS_MAX_PROC)), 'w') as mixed:\n\t\tmixed.write('\\n'.join((_NODE_SUFFIX + n) for pair in (zip(_XeS_NODES, _i7_NODES) if _XeS_HOST else zip(_i7_NODES, _XeS_NODES)) for n in pair))\n\t\tmixed.write('\\n')\n","sub_path":"sendTests/mpiTestI7/generateMachineFile.py","file_name":"generateMachineFile.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"466791064","text":"import os\nimport tempfile\nimport unittest\n\nfrom tensorflow import keras\n\nfrom calamari_ocr.ocr import DataSetType\nfrom calamari_ocr.ocr.dataset.imageprocessors.data_range_normalizer import DataRangeNormalizer\nfrom calamari_ocr.ocr.dataset.imageprocessors.default_image_processors import default_image_processors\nfrom calamari_ocr.ocr.dataset.imageprocessors.final_preparation import FinalPreparation\nfrom calamari_ocr.ocr.dataset.imageprocessors.scale_to_height_processor import ScaleToHeightProcessor\nfrom calamari_ocr.scripts.train import run\nfrom calamari_ocr.utils import glob_all\n\nthis_dir = os.path.dirname(os.path.realpath(__file__))\n\n\nclass Attrs():\n def __init__(self):\n self.dataset = DataSetType.FILE\n self.gt_extension = DataSetType.gt_extension(self.dataset)\n self.files = glob_all([os.path.join(this_dir, \"data\", \"uw3_50lines\", \"train\", \"*.png\")])\n self.seed = 24\n self.backend = \"tensorflow\"\n self.network = \"cnn=40:3x3,pool=2x2,cnn=60:3x3,pool=2x2,lstm=200,dropout=0.5\"\n self.line_height = 48\n self.pad = 16\n self.num_threads = 1\n self.display = 1\n self.batch_size = 1\n self.checkpoint_frequency = 1000\n self.epochs = 1\n self.samples_per_epoch = 8\n self.stats_size = 100\n self.no_skip_invalid_gt = False\n self.no_progress_bars = True\n self.output_dir = None\n self.output_model_prefix = \"uw3_50lines\"\n self.bidi_dir = None\n self.weights = None\n self.ema_weights = False\n self.whitelist_files = []\n self.whitelist = []\n self.gradient_clipping_norm = 5\n self.validation = None\n self.validation_dataset = DataSetType.FILE\n self.validation_extension = None\n self.validation_split_ratio = None\n self.early_stopping_frequency = -1\n self.early_stopping_nbest = 10\n self.early_stopping_at_accuracy = 0.99\n self.early_stopping_best_model_prefix = \"uw3_50lines_best\"\n self.early_stopping_best_model_output_dir = self.output_dir\n self.n_augmentations = 0\n self.num_inter_threads = 0\n self.num_intra_threads = 0\n self.text_regularization = [\"extended\"]\n self.text_normalization = \"NFC\"\n self.text_generator_params = None\n self.line_generator_params = None\n self.pagexml_text_index = 0\n self.text_files = None\n self.only_train_on_augmented = False\n self.data_preprocessing = [p.name for p in default_image_processors()]\n self.shuffle_buffer_size = 1000\n self.keep_loaded_codec = False\n self.train_data_on_the_fly = False\n self.validation_data_on_the_fly = False\n self.no_auto_compute_codec = False\n self.dataset_pad = 0\n self.debug = False\n self.train_verbose = True\n self.use_train_as_val = False\n self.ensemble = -1\n self.masking_mode = 1\n\n\nclass TestSimpleTrain(unittest.TestCase):\n def tearDown(self) -> None:\n keras.backend.clear_session()\n\n def test_simple_train(self):\n args = Attrs()\n args.use_train_as_val = True\n with tempfile.TemporaryDirectory() as d:\n args.output_dir = d\n run(args)\n\n def test_train_without_center_normalizer(self):\n args = Attrs()\n args.use_train_as_val = True\n args.data_preprocessing = [\n DataRangeNormalizer.__name__,\n ScaleToHeightProcessor.__name__,\n FinalPreparation.__name__,\n ]\n with tempfile.TemporaryDirectory() as d:\n args.output_dir = d\n run(args)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"calamari_ocr/test/test_simple_train.py","file_name":"test_simple_train.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"373682460","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/gianluca/Pubblici/GIThub/MASTER/Videomass/videomass3/vdms_panels/youtubedl_ui.py\n# Compiled at: 2020-05-11 07:27:34\n# Size of source mod 2**32: 33259 bytes\nfrom videomass3.vdms_io import IO_tools\nfrom videomass3.vdms_utils.utils import format_bytes\nfrom videomass3.vdms_utils.utils import time_human\nfrom videomass3.vdms_frames.ydl_mediainfo import YDL_Mediainfo\nimport wx\nRED = '#ea312d'\nVQUALITY = {'Best quality video':[\n 'best', 'best'], \n 'Worst quality video':[\n 'worst', 'worst']}\nAFORMATS = {'Default audio format':('best', '--extract-audio'), \n 'wav':('wav', '--extract-audio --audio-format wav'), \n 'mp3':('mp3', '--extract-audio --audio-format mp3'), \n 'aac':('aac', '--extract-audio --audio-format aac'), \n 'm4a':('m4a', '--extract-audio --audio-format m4a'), \n 'vorbis':('vorbis', '--extract-audio --audio-format vorbis'), \n 'opus':('opus', '--extract-audio --audio-format opus'), \n 'flac':('flac', '--extract-audio --audio-format flac')}\nAQUALITY = {'Best quality audio':[\n 'best', 'best'], \n 'Worst quality audio':[\n 'worst', 'worst']}\nopt = {'NO_PLAYLIST':[\n True, '--no-playlist'], \n 'THUMB':[\n False, ''], \n 'METADATA':[\n False, ''], \n 'V_QUALITY':[\n 'best', 'best'], \n 'A_FORMAT':[\n 'best', '--extract-audio'], \n 'A_QUALITY':[\n 'best', 'best'], \n 'SUBTITLES':[\n False, '']}\nget = wx.GetApp()\nPYLIB_YDL = get.pylibYdl\n\nclass Downloader(wx.Panel):\n __doc__ = '\\n This panel gives a graphic layout to some features of youtube-dl\\n '\n\n def __init__(self, parent, OS):\n \"\"\"\n The first item of the self.info is a complete list of all\n informations getting by extract_info method from youtube_dl\n module.\n \"\"\"\n self.parent = parent\n self.oS = OS\n self.info = []\n wx.Panel.__init__(self, parent, -1)\n sizer_base = wx.BoxSizer(wx.VERTICAL)\n frame = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, ''), wx.VERTICAL)\n sizer_base.Add(frame, 1, wx.ALL | wx.EXPAND, 5)\n sizer = wx.BoxSizer(wx.VERTICAL)\n frame.Add(sizer, 1, wx.ALL | wx.EXPAND, 5)\n self.choice = wx.Choice(self, (wx.ID_ANY), choices=[\n _('Default'),\n _('Download audio and video splitted'),\n _('Download Audio only'),\n _('Download by format code')],\n size=(-1, -1))\n self.choice.SetSelection(0)\n sizer.Add(self.choice, 0, wx.EXPAND | wx.ALL, 15)\n grid_v = wx.FlexGridSizer(1, 3, 0, 0)\n sizer.Add(grid_v, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)\n f = [x for x in VQUALITY.keys()]\n self.cmbx_vq = wx.ComboBox(self, (wx.ID_ANY), choices=f, size=(200, -1),\n style=(wx.CB_DROPDOWN | wx.CB_READONLY))\n self.cmbx_vq.SetSelection(0)\n grid_v.Add(self.cmbx_vq, 0, wx.ALL, 5)\n self.cmbx_aq = wx.ComboBox(self, (wx.ID_ANY), choices=[x for x in AQUALITY.keys()],\n size=(200, -1),\n style=(wx.CB_DROPDOWN | wx.CB_READONLY))\n self.cmbx_aq.SetSelection(0)\n self.cmbx_aq.Disable()\n grid_v.Add(self.cmbx_aq, 0, wx.ALL, 5)\n self.cmbx_af = wx.ComboBox(self, (wx.ID_ANY), choices=[x for x in AFORMATS.keys()],\n size=(200, -1),\n style=(wx.CB_DROPDOWN | wx.CB_READONLY))\n self.cmbx_af.Disable()\n self.cmbx_af.SetSelection(0)\n grid_v.Add(self.cmbx_af, 0, wx.ALL, 5)\n grid_cod = wx.FlexGridSizer(1, 4, 0, 0)\n sizer.Add(grid_cod, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)\n self.txt_maincode = wx.TextCtrl(self, (wx.ID_ANY), '', style=(wx.TE_MULTILINE | wx.HSCROLL | wx.TE_RICH2),\n size=(180, 40))\n self.txt_maincode.Disable()\n self.stext1 = wx.StaticText(self, wx.ID_ANY, _('Enter Format Code:'))\n self.stext1.Disable()\n grid_cod.Add(self.stext1, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)\n grid_cod.Add(self.txt_maincode, 0, wx.ALL, 5)\n self.txt_mergecode = wx.TextCtrl(self, (wx.ID_ANY), '', style=(wx.TE_MULTILINE | wx.HSCROLL | wx.TE_RICH2),\n size=(180, 40))\n self.txt_mergecode.Disable()\n self.stext2 = wx.StaticText(self, wx.ID_ANY, _('Merge with:'))\n self.stext2.Disable()\n grid_cod.Add(self.stext2, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)\n grid_cod.Add(self.txt_mergecode, 0, wx.ALL, 5)\n grid_opt = wx.FlexGridSizer(1, 4, 0, 0)\n sizer.Add(grid_opt, 0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 5)\n self.ckbx_pl = wx.CheckBox(self, wx.ID_ANY, _('Download all playlist'))\n grid_opt.Add(self.ckbx_pl, 0, wx.ALL, 5)\n self.ckbx_thumb = wx.CheckBox(self, wx.ID_ANY, _('Embed thumbnail in audio file'))\n grid_opt.Add(self.ckbx_thumb, 0, wx.ALL, 5)\n self.ckbx_meta = wx.CheckBox(self, wx.ID_ANY, _('Add metadata to file'))\n grid_opt.Add(self.ckbx_meta, 0, wx.ALL, 5)\n self.ckbx_sb = wx.CheckBox(self, wx.ID_ANY, _('Write subtitles to video'))\n grid_opt.Add(self.ckbx_sb, 0, wx.ALL, 5)\n self.fcode = wx.ListCtrl(self, (wx.ID_ANY), style=(wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_SINGLE_SEL))\n sizer.Add(self.fcode, 1, wx.EXPAND | wx.ALL | wx.ALIGN_CENTER_HORIZONTAL, 10)\n tip = _('Enter the media \"Format Code\" here. You can specify multiple format codes by using slash, e.g. 22/17/18 . This box cannot left empty.')\n self.txt_maincode.SetToolTip(tip)\n tip = _('To merge audio/video use this box to indicate a second \"Format Code\"; this is optional. You can specify multiple format codes by using slash, e.g. 140/130/151 .')\n self.txt_mergecode.SetToolTip(tip)\n self.fcode.SetToolTip(_('try right-clicking to choose'))\n if OS == 'Darwin':\n self.fcode.SetFont(wx.Font(12, wx.MODERN, wx.NORMAL, wx.NORMAL))\n else:\n self.fcode.SetFont(wx.Font(9, wx.MODERN, wx.NORMAL, wx.NORMAL))\n self.txt_maincode.SetFont(wx.Font(9, wx.MODERN, wx.NORMAL, wx.BOLD))\n self.txt_mergecode.SetFont(wx.Font(9, wx.MODERN, wx.NORMAL, wx.BOLD))\n self.SetSizer(sizer_base)\n self.Layout()\n self.choice.Bind(wx.EVT_CHOICE, self.on_Choice)\n self.cmbx_vq.Bind(wx.EVT_COMBOBOX, self.on_Vq)\n self.cmbx_af.Bind(wx.EVT_COMBOBOX, self.on_Af)\n self.cmbx_aq.Bind(wx.EVT_COMBOBOX, self.on_Aq)\n self.ckbx_pl.Bind(wx.EVT_CHECKBOX, self.on_Playlist)\n self.ckbx_thumb.Bind(wx.EVT_CHECKBOX, self.on_Thumbnails)\n self.ckbx_meta.Bind(wx.EVT_CHECKBOX, self.on_Metadata)\n self.ckbx_sb.Bind(wx.EVT_CHECKBOX, self.on_Subtitles)\n self.txt_maincode.Bind(wx.EVT_TEXT, self.main_code)\n self.fcode.Bind(wx.EVT_CONTEXT_MENU, self.onContext)\n\n def main_code(self, event):\n \"\"\"default status bar when edit\"\"\"\n if not self.parent.sb.GetStatusText() == 'Youtube Downloader':\n self.parent.statusbar_msg('Youtube Downloader', None)\n\n def onContext(self, event):\n \"\"\"\n Create and show a Context Menu\n \"\"\"\n if not hasattr(self, 'popupID2'):\n self.popupID2 = wx.NewId()\n self.popupID3 = wx.NewId()\n self.popupID4 = wx.NewId()\n self.popupID5 = wx.NewId()\n self.popupID6 = wx.NewId()\n self.Bind((wx.EVT_MENU), (self.onPopup), id=(self.popupID2))\n self.Bind((wx.EVT_MENU), (self.onPopup), id=(self.popupID3))\n self.Bind((wx.EVT_MENU), (self.onPopup), id=(self.popupID4))\n self.Bind((wx.EVT_MENU), (self.onPopup), id=(self.popupID5))\n self.Bind((wx.EVT_MENU), (self.onPopup), id=(self.popupID6))\n else:\n menu = wx.Menu()\n if self.choice.GetSelection() == 3:\n itemOne = menu.Append(self.popupID2, _('Insert Format Code'))\n itemThree = menu.Append(self.popupID4, _('Append Format Code'))\n menu.AppendSeparator()\n itemTwo = menu.Append(self.popupID3, _('Insert for merging'))\n itemFour = menu.Append(self.popupID5, _('Append for merging'))\n menu.AppendSeparator()\n itemfive = menu.Append(self.popupID6, _('Play selected url'))\n else:\n itemfive = menu.Append(self.popupID6, _('Play selected url'))\n self.PopupMenu(menu)\n menu.Destroy()\n\n def onPopup(self, event):\n \"\"\"\n Evaluate the label string of the menu item selected and starts\n the related process\n \"\"\"\n itemId = event.GetId()\n menu = event.GetEventObject()\n menuItem = menu.FindItemById(itemId)\n item = self.fcode.GetFocusedItem()\n fc = self.fcode.GetItemText(item, 2)\n if menuItem.GetLabel() == _('Append Format Code'):\n if self.txt_maincode.GetValue().strip() == '':\n self.txt_maincode.AppendText(fc)\n else:\n self.txt_maincode.SetDefaultStyle(wx.TextAttr(wx.Colour(RED)))\n self.txt_maincode.AppendText('/')\n self.txt_maincode.SetDefaultStyle(wx.TextAttr(wx.NullColour))\n self.txt_maincode.AppendText('%s' % fc)\n else:\n if menuItem.GetLabel() == _('Append for merging'):\n if self.txt_mergecode.GetValue().strip() == '':\n self.txt_mergecode.AppendText(fc)\n else:\n self.txt_mergecode.SetDefaultStyle(wx.TextAttr(wx.Colour(RED)))\n self.txt_mergecode.AppendText('/')\n self.txt_mergecode.SetDefaultStyle(wx.TextAttr(wx.NullColour))\n self.txt_mergecode.AppendText('%s' % fc)\n else:\n if menuItem.GetLabel() == _('Insert Format Code'):\n self.txt_maincode.Clear()\n self.txt_maincode.AppendText(fc)\n else:\n if menuItem.GetLabel() == _('Insert for merging'):\n self.txt_mergecode.Clear()\n self.txt_mergecode.AppendText(fc)\n else:\n if menuItem.GetLabel() == _('Play selected url'):\n self.parent.ExportPlay(self)\n\n def get_libraryformatcode(self):\n \"\"\"\n Get URLs format code by generator object *youtube_info* and set\n populate the list control with new entries.\n \"\"\"\n self.fcode.ClearAll()\n self.fcode.InsertColumn(0, (_('Url')), width=60)\n self.fcode.InsertColumn(1, (_('Title')), width=200)\n self.fcode.InsertColumn(2, (_('Format Code')), width=120)\n self.fcode.InsertColumn(3, (_('Extension')), width=80)\n self.fcode.InsertColumn(4, (_('Resolution')), width=160)\n self.fcode.InsertColumn(5, (_('Video Codec')), width=110)\n self.fcode.InsertColumn(6, (_('fps')), width=60)\n self.fcode.InsertColumn(7, (_('Audio Codec')), width=110)\n self.fcode.InsertColumn(8, (_('Size')), width=80)\n index = 0\n for link in self.parent.data_url:\n data = IO_tools.youtube_info(link)\n for meta in data:\n if meta[1]:\n wx.MessageBox(meta[1], 'youtube_dl ERROR', wx.ICON_ERROR)\n return True\n\n formats = iter(meta[0].get('formats', [meta[0]]))\n for n, f in enumerate(formats):\n if f.get('vcodec'):\n vcodec, fps = f['vcodec'], '%sfps' % f.get('fps')\n else:\n vcodec, fps = ('', '')\n if f.get('acodec'):\n acodec = f['acodec']\n else:\n acodec = 'Video only'\n if f.get('filesize'):\n size = format_bytes(float(f['filesize']))\n else:\n size = 'N/A'\n self.fcode.InsertItem(index, link)\n self.fcode.SetItem(index, 1, meta[0]['title'])\n self.fcode.SetItem(index, 2, f['format_id'])\n self.fcode.SetItem(index, 3, f['ext'])\n self.fcode.SetItem(index, 4, f['format'].split('-')[1])\n self.fcode.SetItem(index, 5, vcodec)\n self.fcode.SetItem(index, 6, fps)\n self.fcode.SetItem(index, 7, acodec)\n self.fcode.SetItem(index, 8, size)\n if n == 0:\n self.fcode.SetItemBackgroundColour(index, 'GREEN')\n index += 1\n\n def get_info(self):\n \"\"\"\n Get media url informations by generator object *youtube_info* .\n If meta[1] is None set self.info attribute with dict objetc items\n and return None. Otherwise self.info is a empty list and return True\n \"\"\"\n for link in self.parent.data_url:\n data = IO_tools.youtube_info(link)\n for meta in data:\n if meta[1]:\n wx.MessageBox(meta[1], 'youtube_dl ERROR', wx.ICON_ERROR)\n del self.info[:]\n return True\n else:\n if 'entries' in meta[0]:\n meta[0]['entries'][0]\n if 'duration' in meta[0]:\n ftime = '%s (%s sec.)' % (time_human(meta[0]['duration']),\n meta[0]['duration'])\n else:\n ftime = 'N/A'\n date = meta[0].get('upload_date')\n self.info.append({'url':link, \n 'title':meta[0].get('title'), \n 'categories':meta[0].get('categories'), \n 'license':meta[0].get('license'), \n 'format':meta[0].get('format'), \n 'upload_date':date, \n 'uploader':meta[0].get('uploader'), \n 'view':meta[0].get('view_count'), \n 'like':meta[0].get('like_count'), \n 'dislike':meta[0].get('dislike_count'), \n 'average_rating':meta[0].get('average_rating'), \n 'id':meta[0].get('id'), \n 'duration':ftime, \n 'description':meta[0].get('description')})\n\n def get_executableformatcode(self):\n \"\"\"\n Get format code and set new items for list control by generator object\n *youtube_getformatcode_exec*\n \"\"\"\n self.fcode.ClearAll()\n self.fcode.InsertColumn(0, (_('Url')), width=200)\n self.fcode.InsertColumn(1, (_('Title')), width=50)\n self.fcode.InsertColumn(2, (_('Format Code')), width=120)\n self.fcode.InsertColumn(3, (_('Extension')), width=80)\n self.fcode.InsertColumn(4, (_('Resolution note')), width=500)\n for link in self.parent.data_url:\n index = 0\n self.fcode.InsertItem(index, link)\n self.fcode.SetItemBackgroundColour(index, 'GREEN')\n data = IO_tools.youtube_getformatcode_exec(link)\n for meta in data:\n if meta[1]:\n wx.MessageBox(meta[0], 'Videomass', wx.ICON_ERROR)\n self.info = []\n return True\n self.info.append(link)\n i = 0\n for count, fc in enumerate(meta[0].split('\\n')):\n if not count > i:\n i += 1\n else:\n if fc != '':\n index += 1\n self.fcode.InsertItem(index, link)\n self.fcode.SetItem(index, 1, 'N/A')\n self.fcode.SetItem(index, 2, fc.split()[0])\n self.fcode.SetItem(index, 3, fc.split()[1])\n note = ' '.join(fc.split()[2:])\n self.fcode.SetItem(index, 4, note)\n if fc.startswith('format code '):\n i = count\n\n def on_urls_list(self, quality):\n \"\"\"\n Populate list control with new entries as urls and\n related resolutions\n \"\"\"\n self.fcode.ClearAll()\n self.fcode.InsertColumn(0, (_('Url')), width=500)\n self.fcode.InsertColumn(1, (_('Title')), width=50)\n self.fcode.InsertColumn(2, (_('Resolution note')), width=250)\n if self.parent.data_url:\n index = 0\n for link in self.parent.data_url:\n self.fcode.InsertItem(index, link)\n self.fcode.SetItem(index, 1, 'N/A')\n self.fcode.SetItem(index, 2, quality)\n index += 1\n\n def on_show_info(self):\n \"\"\"\n show data information. This method is called by the main frame\n when the 'Show More' button is pressed.\n \"\"\"\n if PYLIB_YDL is not None:\n wx.MessageBox(_('\"Show more\" only is enabled when Videomass uses youtube-dl as imported library.'), 'Videomass', wx.ICON_INFORMATION)\n return\n if not self.info:\n ret = self.get_info()\n if ret:\n return\n dialog = YDL_Mediainfo(self.info, self.oS)\n dialog.Show()\n\n def on_format_codes(self):\n \"\"\"\n get data and info and show listctrl to choose format code\n \"\"\"\n if PYLIB_YDL is not None:\n ret = self.get_executableformatcode()\n if ret:\n return\n else:\n ret = self.get_libraryformatcode()\n if ret:\n return\n\n def on_Choice(self, event):\n if self.choice.GetSelection() == 0:\n (\n self.cmbx_af.Disable(), self.cmbx_aq.Disable())\n (self.cmbx_vq.Enable(), self.txt_maincode.Disable())\n (self.stext1.Disable(), self.stext2.Disable())\n (self.txt_mergecode.Disable(), self.txt_maincode.Clear())\n self.txt_mergecode.Clear()\n self.on_urls_list(opt['V_QUALITY'][1])\n else:\n if self.choice.GetSelection() == 1:\n (\n self.cmbx_af.Disable(), self.cmbx_aq.Enable())\n (self.cmbx_vq.Enable(), self.txt_maincode.Disable())\n (self.stext1.Disable(), self.stext2.Disable())\n (self.txt_mergecode.Disable(), self.txt_maincode.Clear())\n self.txt_mergecode.Clear()\n self.on_urls_list('%svideo+%saudio' % (opt['V_QUALITY'][1],\n opt['A_QUALITY'][1]))\n else:\n if self.choice.GetSelection() == 2:\n (\n self.cmbx_vq.Disable(), self.cmbx_aq.Disable())\n (self.cmbx_af.Enable(), self.txt_maincode.Disable())\n (self.stext1.Disable(), self.stext2.Disable())\n (self.txt_mergecode.Disable(), self.txt_maincode.Clear())\n self.txt_mergecode.Clear()\n self.on_urls_list('')\n else:\n if self.choice.GetSelection() == 3:\n (\n self.cmbx_vq.Disable(), self.cmbx_aq.Disable())\n (self.cmbx_af.Disable(), self.txt_maincode.Enable())\n (self.stext1.Enable(), self.stext2.Enable())\n self.txt_mergecode.Enable()\n self.on_format_codes()\n\n def on_Vq(self, event):\n opt['V_QUALITY'] = VQUALITY[self.cmbx_vq.GetValue()]\n index = 0\n if self.choice.GetSelection() == 0:\n q = opt['V_QUALITY'][1]\n else:\n if self.choice.GetSelection() == 1:\n q = '%svideo+%saudio' % (opt['V_QUALITY'][1], opt['A_QUALITY'][1])\n for link in self.parent.data_url:\n self.fcode.SetItem(index, 2, q)\n index += 1\n\n def on_Af(self, event):\n opt['A_FORMAT'] = AFORMATS.get(self.cmbx_af.GetValue())\n index = 0\n for link in self.parent.data_url:\n self.fcode.SetItem(index, 2, '')\n index += 1\n\n def on_Aq(self, event):\n opt['A_QUALITY'] = AQUALITY.get(self.cmbx_aq.GetValue())\n index = 0\n q = '%svideo+%saudio' % (opt['V_QUALITY'][1], opt['A_QUALITY'][1])\n for link in self.parent.data_url:\n self.fcode.SetItem(index, 2, q)\n index += 1\n\n def on_Playlist(self, event):\n if self.ckbx_pl.IsChecked():\n opt['NO_PLAYLIST'] = [\n False, '--yes-playlist']\n else:\n opt['NO_PLAYLIST'] = [\n True, '--no-playlist']\n\n def on_Thumbnails(self, event):\n if self.ckbx_thumb.IsChecked():\n opt['THUMB'] = [\n True, '--embed-thumbnail']\n else:\n opt['THUMB'] = [\n False, '']\n\n def on_Metadata(self, event):\n if self.ckbx_meta.IsChecked():\n opt['METADATA'] = [\n True, '--add-metadata']\n else:\n opt['METADATA'] = [\n False, '']\n\n def on_Subtitles(self, event):\n if self.ckbx_sb.IsChecked():\n opt['SUBTITLES'] = [\n True, '--write-auto-sub']\n else:\n opt['SUBTITLES'] = [\n False, '']\n\n def on_start(self):\n \"\"\"\n Builds command string to use with an embed youtube_dl as\n python library or using standard youtube-dl command line\n with subprocess. This depends on some cases.\n \"\"\"\n urls = self.parent.data_url\n logname = 'Youtube_LIB_downloader.log'\n\n def _getformatcode():\n code1 = self.txt_maincode.GetValue().strip()\n code2 = self.txt_mergecode.GetValue().strip()\n code = code1 if not code2 else code1 + '+' + code2\n return code\n\n if PYLIB_YDL is None:\n postprocessors = []\n if self.choice.GetSelection() == 2:\n postprocessors.append({'key':'FFmpegExtractAudio', 'preferredcodec':opt['A_FORMAT'][0]})\n if opt['METADATA'][0]:\n postprocessors.append({'key': 'FFmpegMetadata'})\n if opt['THUMB'][0]:\n postprocessors.append({'key':'EmbedThumbnail', 'already_have_thumbnail':False})\n if opt['SUBTITLES'][0]:\n postprocessors.append({'key': 'FFmpegEmbedSubtitle'})\n if self.choice.GetSelection() == 0:\n data = {'format':opt['V_QUALITY'][0], \n 'noplaylist':opt['NO_PLAYLIST'][0], \n 'writethumbnail':opt['THUMB'][0], \n 'outtmpl':'%(title)s.%(ext)s', \n 'extractaudio':False, \n 'addmetadata':opt['METADATA'][0], \n 'writesubtitles':opt['SUBTITLES'][0], \n 'writeautomaticsub':opt['SUBTITLES'][0], \n 'allsubtitles':opt['SUBTITLES'][0], \n 'postprocessors':postprocessors}\n if self.choice.GetSelection() == 1:\n data = {'format':'%svideo,%saudio' % (opt['V_QUALITY'][0],\n opt['A_QUALITY'][0]), 'noplaylist':opt['NO_PLAYLIST'][0], \n 'writethumbnail':opt['THUMB'][0], \n 'outtmpl':'%(title)s.f%(format_id)s.%(ext)s', \n 'extractaudio':False, \n 'addmetadata':opt['METADATA'][0], \n 'writesubtitles':opt['SUBTITLES'][0], \n 'writeautomaticsub':opt['SUBTITLES'][0], \n 'allsubtitles':opt['SUBTITLES'][0], \n 'postprocessors':postprocessors}\n else:\n if self.choice.GetSelection() == 2:\n data = {'format':'best', 'noplaylist':opt['NO_PLAYLIST'][0], \n 'writethumbnail':opt['THUMB'][0], \n 'outtmpl':'%(title)s.%(ext)s', \n 'extractaudio':True, \n 'addmetadata':opt['METADATA'][0], \n 'writesubtitles':opt['SUBTITLES'][0], \n 'writeautomaticsub':opt['SUBTITLES'][0], \n 'allsubtitles':opt['SUBTITLES'][0], \n 'postprocessors':postprocessors}\n if self.choice.GetSelection() == 3:\n code = _getformatcode()\n if not code:\n self.parent.statusbar_msg('Missing Format Code', RED)\n return\n data = {'format':code, \n 'noplaylist':opt['NO_PLAYLIST'][0], \n 'writethumbnail':opt['THUMB'][0], \n 'outtmpl':'%(title)s.f%(format_id)s.%(ext)s', \n 'extractaudio':False, \n 'addmetadata':opt['METADATA'][0], \n 'writesubtitles':opt['SUBTITLES'][0], \n 'writeautomaticsub':opt['SUBTITLES'][0], \n 'allsubtitles':opt['SUBTITLES'][0], \n 'postprocessors':postprocessors}\n self.parent.switch_to_processing('youtube_dl python package', urls, '', self.parent.file_destin, data, None, '', '', 'Youtube_LIB_downloader.log', len(urls))\n else:\n if self.choice.GetSelection() == 0:\n cmd = [\n f\"--format {opt['V_QUALITY'][1]} {opt['METADATA'][1]} {opt['SUBTITLES'][1]} {opt['THUMB'][1]} {opt['NO_PLAYLIST'][1]}\",\n '%(title)s.%(ext)s']\n if self.choice.GetSelection() == 1:\n cmd = [\n f\"--format {opt['V_QUALITY'][1]}video,{opt['A_QUALITY'][1]}audio {opt['METADATA'][1]} {opt['SUBTITLES'][1]} {opt['THUMB'][1]} {opt['NO_PLAYLIST'][1]}\",\n '%(title)s.f%(format_id)s.%(ext)s']\n else:\n if self.choice.GetSelection() == 2:\n cmd = [\n f\"{opt['A_FORMAT'][1]} {opt['METADATA'][1]} {opt['SUBTITLES'][1]} {opt['THUMB'][1]} {opt['NO_PLAYLIST'][1]}\",\n '%(title)s.%(ext)s']\n if self.choice.GetSelection() == 3:\n code = _getformatcode()\n if not code:\n self.parent.statusbar_msg('Missing Format Code', RED)\n return\n cmd = [\n f\"--format {code} {opt['METADATA'][1]} {opt['SUBTITLES'][1]} {opt['THUMB'][1]} {opt['NO_PLAYLIST'][1]}\",\n '%(title)s.f%(format_id)s.%(ext)s']\n self.parent.switch_to_processing('youtube-dl executable', urls, '', self.parent.file_destin, cmd, None, '', '', 'Youtube_EXEC_downloader.log', len(urls))","sub_path":"pycfiles/videomass-2.1.7-py3-none-any/youtubedl_ui.cpython-37.py","file_name":"youtubedl_ui.cpython-37.py","file_ext":"py","file_size_in_byte":26460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571074058","text":"import saxpy\nfrom saxpy.hotsax import find_discords_hotsax\n\ndef hotsax(matrix):\n\tresult = []\n\tindex_ts = 0\n\tfor ts in matrix.T:\n\t\tdiscords = find_discords_hotsax(ts)\n\t\tfor anomaly in discords:\n\t\t\tresult.append([index_ts, anomaly[0], anomaly[1]])\n\t\tindex_ts = index_ts + 1\n\treturn result\n","sub_path":"Databases/graphite/for-install/udf/hotsax.py","file_name":"hotsax.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"302564096","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n m = {}\n fake_head = head\n curr = head\n prev = None\n while curr:\n if curr.val in m:\n node_to_delete = curr\n prev.next = curr.next\n curr = curr.next\n del node_to_delete\n continue\n \n m[curr.val] = True\n prev = curr\n curr = curr.next\n\n return fake_head\n\nroot = ListNode(1)\nroot.next = ListNode(1)\nroot.next.next = ListNode(2)\nroot.next.next.next = ListNode(3)\nroot.next.next.next.next = ListNode(3)\n\nresult = Solution().deleteDuplicates(root)\n\ncur = result\nwhile cur:\n print(cur.val)\n cur = cur.next\n\n\n\n\n","sub_path":"remove-duplicate-linked-list/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"86874349","text":"handle = open('..\\Files\\mbox-short.txt')\nkey = 'From'\nlength = len(key)\nsenders = dict()\nsndr = None\n\nfor line in handle:\n if line.startswith(key) and line[length] != ':':\n line = line.rstrip()\n line = line.split()\n sender = line[1]\n\n if sender not in senders:\n senders[sender] = 1\n else:\n senders[sender] += 1\n\nmost = 0\n\nfor sender in senders:\n if most==0 or senders[sender] > most:\n most=senders[sender]\n sndr=sender\n\nprint(sndr,most)\n","sub_path":"Dictionaries/MaxSender.py","file_name":"MaxSender.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"413666671","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import division\n\nimport os\nimport sys\nimport traceback\nimport unittest\n\nlib_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nif not lib_path in sys.path:\n sys.path.append(lib_path)\nfrom common.google_music import google_Music\nfrom common.yt_music import YTMusic\nfrom common.native_music import native_Music\nfrom common.mods import Mods\nfrom common.base_test_case import BaseTestCase\n\n\nclass TestMusicPlayer(BaseTestCase):\n test_mod = Mods.Music\n\n @classmethod\n def setUpClass(cls):\n \"\"\"必须连接翻墙wifi\"\"\"\n super(TestMusicPlayer, cls).setUpClass()\n if cls.c.isMILAN_GL:\n cls.mod = native_Music(cls.c.device, cls.test_mod)\n else:\n cls.mod = YTMusic(cls.c.device, cls.test_mod)\n cls.mod.back_to_home()\n\n def testStability(self):\n self.case_play_music(int(self.dicttesttimes.get(\"Play_Music\".lower())))\n\n def case_play_music(self, times=1):\n '''play music\n '''\n self.mod.logger.debug(\"play music test %d times\" % times)\n # self.mod.enter()\n for loop in range(times):\n try:\n if self.mod.play_music():\n self.trace_success()\n else:\n self.trace_fail()\n except:\n self.mod.logger.warning(traceback.format_exc())\n self.mod.save_fail_img()\n finally:\n self.mod.back_to_home()\n self.mod.close_music()\n self.mod.back_to_home()\n self.mod.logger.debug(\"play music test %d times complete\" % times)\n\n\nif __name__ == '__main__':\n suiteCase = unittest.TestLoader().loadTestsFromTestCase(TestMusicPlayer)\n suite = unittest.TestSuite([suiteCase])\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"MILAN_MTBF/stability/11_MusicPlayer.py","file_name":"11_MusicPlayer.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463690862","text":"from exception import MalSystemException, WrongArgsNumException\nfrom mal_types import MalSymbol, MalList\n\n\nclass Env:\n def __init__(self, outer=None, binds=None, exprs=None):\n self.__outer = outer\n self.__env = dict()\n if binds is not None:\n self.bind(binds, exprs)\n\n def bind(self, binds, exprs):\n varbind = None\n if MalSymbol('&') in binds:\n binds, varbind = binds[:-2], binds[-1:]\n varbind = varbind[0] if varbind is not None else None\n if MalSymbol('&') in binds:\n raise MalSystemException(None, 'variadic binding must be the last in the bindings list')\n if varbind is not None and varbind == MalSymbol('&'):\n raise MalSystemException(None, 'missing variadic binding symbol')\n if varbind is not None and len(binds) > len(exprs):\n raise WrongArgsNumException(expected=len(binds), got=len(exprs), exact=False)\n if varbind is None and len(binds) != len(exprs):\n raise WrongArgsNumException(expected=len(binds), got=len(exprs), exact=True)\n symbols = binds + ([varbind] if varbind is not None else [])\n if len(symbols) != len(set(symbols)):\n raise MalSystemException(None, 'duplicate symbols in bindings list')\n self.__env.update(dict(zip(binds, exprs[:len(binds)])))\n if varbind is not None:\n exprs = exprs[len(binds):]\n if type(exprs) is not MalList:\n exprs = MalList(list(exprs))\n self.__env[varbind] = exprs\n\n def set(self, symbol, value):\n self.__env[symbol] = value\n\n def find(self, symbol):\n env = self\n while env is not None and symbol not in env.__env:\n env = env.__outer\n return env\n\n def get(self, symbol):\n env = self.find(symbol)\n return env.__env[symbol] if env is not None else None","sub_path":"src/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"112070540","text":"import datetime\nimport json\nfrom urllib.parse import urlencode, splitquery, parse_qs\n\nimport pytest\nfrom django.contrib.auth.models import User\nfrom django.core.management import call_command\n\nfrom openid_connect_op.models import OpenIDClient, OpenIDToken\nfrom openid_connect_op.utils.jwt import JWTTools\ntry:\n import secrets\nexcept ImportError:\n import openid_connect_op.utils.secrets_backport as secrets\n\nimport jwcrypto.jwk as jwk\n\n\n@pytest.mark.django_db\nclass TestTokenRequestClientSecretJWT:\n\n @pytest.fixture(autouse=True)\n def init_jwk(self):\n call_command('create_jwt_keys')\n\n @pytest.fixture\n def user(self):\n return User.objects.create(username='a')\n\n @pytest.fixture()\n def client_config(self):\n redirect_uri = 'http://localhost:8000/complete/test/?state=1234'\n\n ret = OpenIDClient.objects.create(\n client_id='test',\n redirect_uris=redirect_uri,\n client_auth_type=OpenIDClient.CLIENT_AUTH_TYPE_SECRET_JWT,\n )\n ret.set_client_secret('b')\n ret.save()\n return ret\n\n def test_logged_user(self, client, client_config, user, settings):\n code = self.get_authorization_code(client, client_config, user)\n\n token = {\n 'iss': client_config.client_id,\n 'sub': client_config.client_id,\n 'aud': ['http://testserver/openid/token'],\n }\n jwt_token = JWTTools.generate_jwt(token, client_config, datetime.timedelta(seconds=60),\n from_client=client_config)\n\n resp = client.get('/openid/token?' + urlencode({\n 'redirect_uri': client_config.redirect_uris,\n 'grant_type': 'authorization_code',\n 'code': code,\n 'client_assertion_type': 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n 'client_assertion': jwt_token\n }))\n\n self.check_token_response(settings, client_config, resp)\n\n @staticmethod\n def check_token_response(settings, client_config, resp, sub='a'):\n assert resp.status_code == 200\n data = json.loads(resp.content.decode('utf-8'))\n assert 'access_token' in data\n assert data['token_type'] == 'Bearer'\n assert 'refresh_token' in data\n assert data['expires_in'] == settings.OPENID_DEFAULT_ACCESS_TOKEN_TTL\n assert 'id_token' in data\n database_at = OpenIDToken.objects.get(token_hash=OpenIDToken.get_token_hash(data['access_token']))\n assert database_at.user.username == 'a'\n assert database_at.client == client_config\n assert database_at.token_type == OpenIDToken.TOKEN_TYPE_ACCESS_BEARER_TOKEN\n database_rt = OpenIDToken.objects.get(token_hash=OpenIDToken.get_token_hash(data['refresh_token']))\n assert database_rt.user.username == 'a'\n assert database_rt.client == client_config\n assert database_rt.token_type == OpenIDToken.TOKEN_TYPE_REFRESH_TOKEN\n # validate id token\n header, payload = JWTTools.validate_jwt(data['id_token'])\n assert header['alg'] == 'RS256'\n assert header['typ'] == 'JWT'\n assert payload['exp'] == int(payload['exp'])\n assert payload['iat'] == int(payload['iat'])\n assert payload['aud'] == ['test']\n assert payload['sub'] == sub # username\n assert payload['iss'] == 'http://testserver/'\n\n @staticmethod\n def get_authorization_code(client, client_config, user):\n client.force_login(user)\n resp = client.get('/openid/authorize?' + urlencode({\n 'redirect_uri': client_config.redirect_uris,\n 'client_id': 'test',\n 'scope': 'openid',\n 'response_type': 'code'\n }))\n assert resp.status_code == 302\n redirect_server, redirect_query = splitquery(resp.url)\n assert redirect_server == 'http://localhost:8000/complete/test/'\n redirect_query = parse_qs(redirect_query)\n assert redirect_query['state'] == ['1234']\n assert 'code' in redirect_query\n code = redirect_query['code'][0]\n return code\n","sub_path":"tests/openid_op_tests/test_token_request_client_secret_jwt.py","file_name":"test_token_request_client_secret_jwt.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"18847702","text":"import numpy as np\nfrom experiments import utils\nfrom models import autoencoder_model\nfrom keras.utils import to_categorical\nfrom keras.models import Model\n\nseed = 7\nnp.random.seed(seed)\n# Load data\nnm = '1m'\ntarget = '2c'\nx, y = utils.get_data(nm, target)\nx_train, y_train, x_test, y_test = utils.make_train_test(x, y, seed)\n\nparameters = {\n 'model_name': 'sae_'+nm+target,\n 'encoding_dim': 50,\n 'size_of_batch': 40,\n 'nb_epoch': 800,\n 'drop_rate': 0.5,\n 'g_noise': 0.0,\n 'nm_layer': [],\n 'active_rug': 1e-8,\n 'lr': 1e-4\n}\n\n# autoencoder = autoencoder_model.basic(nm, x_train, size_of_batch, nb_epoch)\nautoencoder = autoencoder_model.sparse_ae(x_train, parameters)\n# print(autoencoder.summary())\n\nencoder = Model(inputs=autoencoder.input, outputs=autoencoder.get_layer('encoder_out').output)\nx_predict = encoder.predict(x_train)\n\nutils.min_loss(autoencoder.history)\nutils.plot_autoencoder_loss(autoencoder.history)\n\nutils.plot_network(autoencoder, file_name=autoencoder.name)\n\n# utils.plot_autoencoder_2d(x_predict, y)\n\n\n\n# print('wait...')\n# encoder_layer_model = Model(inputs=autoencoder.input, outputs=autoencoder.get_layer('encoder_out').output)\n# x_ae = encoder_layer_model.predict(x)\n# utils.plot_autoencoder_2d(x_predict, y)","sub_path":"experiments/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"526914148","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# created by Lipson on 2018/5/10.\n# email to LipsonChan@yahoo.com\n#\nfrom NXSpider.common import tools, log\nfrom NXSpider.common.tools import RETURE_HTML\nfrom NXSpider.spider.api import get_playlist_detail, headers\nfrom NXSpider.spider.playlist import Playlist\n\n\ndef crawl_playlist_by_id(link, download_type=['mp3', 'mv'],\n save=True, file_check=True):\n playlist_detail = get_playlist_detail(link)\n with tools.ignored(Exception):\n log.print_info(\"%s author:%s\" % (\n \"<\" + playlist_detail['name'] + \">\",\n playlist_detail['creator']['nickname'],\n ))\n\n playlist_mo = Playlist()\n playlist_mo.parse_model(playlist_detail,\n save=save, download_type=download_type,\n file_check=file_check)\n pass\n\n\ndef crawl_playlist_by_page(page, dtype=\"全部\", download_type=['mp3', 'mv'],\n save=True, file_check=True):\n play_url = \"http://music.163.com/discover/playlist/?order=hot&cat={}&limit=35&offset={}\"\n play_url = play_url.format(dtype, page * 35)\n playlist_id = []\n titles = []\n try:\n acmsk = {'class': 'msk'}\n scnb = {'class': 'nb'}\n dcu = {'class': 'u-cover u-cover-1'}\n ucm = {'class': 'm-cvrlst f-cb'}\n data = tools.curl(play_url, headers, type=RETURE_HTML)\n lst = data.find('ul', ucm)\n for play in lst.find_all('div', dcu):\n title = play.find('a', acmsk)['title']\n link = play.find('a', acmsk)['href'].replace(\"/playlist?id=\", \"\")\n\n playlist_detail = get_playlist_detail(link)\n with tools.ignored(Exception):\n log.print_info(\"%s author:%s\" % (\n \"<\" + playlist_detail['name'] + \">\",\n tools.encode(playlist_detail['creator']['nickname']),\n ))\n\n playlist_mo = Playlist()\n playlist_mo.parse_model(playlist_detail,\n save=save, download_type=download_type,\n file_check=file_check)\n\n return titles\n except Exception as e:\n log.print_err(\"crawl html error:{} type:{} page:{}\".format(e, dtype, page))\n raise\n\n\ndef crawl_by_playlists():\n for i in range(36):\n crawl_playlist_by_page(i + 1)\n","sub_path":"NXSpider/spider/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"574582158","text":"# vim: set expandtab shiftwidth=4 softtabstop=4:\r\n\r\nfrom chimerax.core.tools import ToolInstance\r\nfrom chimerax.core.logger import PlainTextLog\r\n\r\n\r\nclass SampleTool(ToolInstance):\r\n\r\n SESSION_ENDURING = False\r\n SESSION_SKIP = True # No session saving for now\r\n CUSTOM_SCHEME = \"sample\" # HTML scheme for custom links\r\n display_name = \"Sample Tool\"\r\n\r\n def __init__(self, session, tool_name):\r\n # Standard template stuff for intializing tool\r\n super().__init__(session, tool_name)\r\n from chimerax.core.ui.gui import MainToolWindow\r\n self.tool_window = MainToolWindow(self)\r\n self.tool_window.manage(placement=\"side\")\r\n parent = self.tool_window.ui_area\r\n\r\n # Create an HTML viewer for our user interface.\r\n # We can include other Qt widgets if we want to.\r\n from PyQt5.QtWidgets import QGridLayout\r\n from chimerax.core.ui.widgets import HtmlView\r\n layout = QGridLayout()\r\n self.html_view = HtmlView(parent, size_hint=(575, 200),\r\n interceptor=self._navigate,\r\n schemes=[self.CUSTOM_SCHEME])\r\n layout.addWidget(self.html_view, 0, 0) # row 0, column 0\r\n parent.setLayout(layout)\r\n\r\n # Register for model addition/removal so we can update model list\r\n from chimerax.core.models import ADD_MODELS, REMOVE_MODELS\r\n t = session.triggers\r\n self._add_handler = t.add_handler(ADD_MODELS, self._update_models)\r\n self._remove_handler = t.add_handler(REMOVE_MODELS, self._update_models)\r\n\r\n # Go!\r\n self._update_models()\r\n\r\n def _update_models(self, trigger=None, trigger_data=None):\r\n # Called to update page with current list of models\r\n from chimerax.core.atomic import AtomicStructure\r\n html = [\"

Sample Tool

\", \"
    \"]\r\n from urllib.parse import quote\r\n for m in self.session.models.list(type=AtomicStructure):\r\n html.append(\"
  • %s - %s
  • \" %\r\n (self.CUSTOM_SCHEME, quote(m.atomspec()),\r\n m.id_string(), m.name))\r\n html.extend([\"
\",\r\n \"

Output:

\",\r\n '
Counts appear here
'])\r\n self.html_view.setHtml('\\n'.join(html))\r\n\r\n def _navigate(self, info):\r\n # Called when link is clicked.\r\n # \"info\" is an instance of QWebEngineUrlRequestInfo\r\n url = info.requestUrl()\r\n scheme = url.scheme()\r\n if scheme == self.CUSTOM_SCHEME:\r\n # Intercept our custom scheme.\r\n # Method may be invoked in a different thread than\r\n # the main thread where Qt calls may be made.\r\n self.session.ui.thread_safe(self._run, url.path())\r\n\r\n def _run(self, atomspec):\r\n # Execute \"sample count\" command for given atomspec\r\n from chimerax.core.commands import run\r\n from chimerax.core.logger import StringPlainTextLog\r\n with StringPlainTextLog(self.session.logger) as log:\r\n try:\r\n run(self.session, \"sample count \" + atomspec)\r\n finally:\r\n html = \"
\\n%s
\" % log.getvalue()\r\n js = ('document.getElementById(\"output\").innerHTML = %s'\r\n % repr(html))\r\n self.html_view.page().runJavaScript(js)\r\n\r\n\r\nclass CaptureLog(PlainTextLog):\r\n\r\n excludes_other_logs = True\r\n\r\n def __init__(self, logger):\r\n super().__init__()\r\n self.msgs = []\r\n self.logger = logger\r\n\r\n def __enter__(self):\r\n self.logger.add_log(self)\r\n return self\r\n\r\n def __exit__(self, *exc_info):\r\n self.logger.remove_log(self)\r\n\r\n def log(self, level, msg):\r\n self.msgs.append(msg)\r\n return True\r\n\r\n def getvalue(self):\r\n return ''.join(self.msgs)\r\n","sub_path":"sample/src/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"305867117","text":"#19952번: 인성 문제 있어??\nimport sys\nfrom collections import deque\ndef bfs(F,start,end):\n q=deque()\n q.appendleft((start,F)) # ((x,y),F)\n visited[start[0]][start[1]]=1\n while q:\n (x,y),F=q.pop()\n for d in dir:\n nx,ny=x+d[0],y+d[1]\n if 0 <= nx < H and 0 <= ny < W:\n if F-1 >= 0 and visited[nx][ny] == 0 and maze[nx][ny]-maze[x][y] <= F:\n if (nx,ny) == end:\n return '잘했어!!'\n q.appendleft(((nx,ny),F-1))\n visited[nx][ny]=1\n return '인성 문제있어??'\n\ndir=[(0,1),(0,-1),(1,0),(-1,0)]\nT=int(sys.stdin.readline())\nfor _ in range(T):\n H,W,O,F,xs,yx,xe,ye=map(int,sys.stdin.readline().split())\n maze=[[0]*W for _ in range(H)]\n visited=[[0]*W for _ in range(H)]\n for _ in range(O):\n x,y,h=map(int,sys.stdin.readline().split())\n maze[x-1][y-1]=h\n print(bfs(F,(xs-1,yx-1),(xe-1,ye-1)))","sub_path":"Algorithm/Ryan/BOJ19952.py","file_name":"BOJ19952.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"256364762","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import login, authenticate\nfrom django.http import HttpResponse, HttpResponseRedirect\n#auth\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import AdminPasswordChangeForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic.edit import UpdateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom .forms import SignUpForm, CreateClassroom, AddTeacher, AddStudent\nfrom .models import Superuser, Classroom, Teacher, Student\nfrom . import bools\nfrom question.models import Quiz\nfrom .decorators import is_superuser, is_teacher, is_teacher_or_super\n\n# Create your views here.\ndef index(request):\n\t# user = request.user\n\tis_teacher = bools.is_teacher(request)\n\tis_superuser = bools.is_superuser(request)\n\ttry:\n\t\tstudent_your_class = Student.objects.filter(user=request.user)\n\texcept:\n\t\tstudent_your_class = []\n\ttry:\t\t\n\t\tteacher_your_class = Teacher.objects.filter(user=request.user)\n\texcept:\n\t\tteacher_your_class = []\n\tquizes = Quiz.objects.all()\n\tstudent_your_quiz = []\n\tteacher_your_quiz = []\n\tfor q in quizes:\n\t\tfor c in student_your_class:\n\t\t\tif c.classroom == q.classroom:\n\t\t\t\tstudent_your_quiz.append(q)\n\tfor q in quizes:\n\t\tfor c in teacher_your_class:\n\t\t\tif c.classroom == q.classroom:\n\t\t\t\tteacher_your_quiz.append(q)\n\n\tdata = {'is_teacher' : is_teacher, 'is_superuser' : is_superuser, 'student_your_class' : student_your_class, 'student_your_quiz':student_your_quiz, 'teacher_your_class' : teacher_your_class, 'teacher_your_quiz': teacher_your_quiz}\n\treturn render(request, 'index.html', data)\n\ndef signup(request):\n\tif request.method == 'POST':\n\t\tform = SignUpForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\tusername = form.cleaned_data.get('username')\n\t\t\traw_password = form.cleaned_data.get('password1')\n\t\t\tuser = authenticate(username=username, password=raw_password)\n\t\t\tlogin(request, user)\n\t\t\treturn redirect('/')\n\telse:\n\t\tform = SignUpForm()\n\treturn render(request, 'registration/signup.html', {'form' : form})\n\n@login_required\ndef profile(request):\n\tuser = request.user\n\tauth = 0\n\tdata = {'user': user, 'auth': auth}\n\treturn render(request, 'profile.html', data)\n\nclass edit_profile(LoginRequiredMixin, UpdateView):\n\tmodel = User\n\tfields = ['first_name', 'last_name', 'email']\n\ttemplate_name = \"edit_profile.html\"\n\tslug_field = 'username'\n\tslug_url_kwarg = 'user'\n\n@login_required\ndef user_list(request):\n\tuser = request.user\n\tusers = User.objects.all()\n\tsu = Superuser.objects.all()\n\n\t# superusers = []\n\tsuperusers = [U.user for U in su]\n\t# su = [U for S in superusers if S.user == user]\n\t# for u in users:\n\t# \tif u == su.user:\n\n\tdata = {'users': users, 'superusers': superusers}\n\treturn render(request, 'user_list.html', data)\n\n@login_required\n@is_teacher_or_super\ndef user_info(request, id, backto):\n\tuser_target = User.objects.get(id=id)\n\tauth = 1\n\n\tsu = Superuser.objects.all()\n\tsuperuser = False\n\tfor i in su:\n\t\tif user_target == i.user:\n\t\t\tsuperuser = True\n\n\tmyself = False\n\tif user_target == request.user:\n\t\tmyself = True\n\n\tdata = {'user': user_target, 'auth': auth, 'superuser': superuser, 'backto': backto, 'myself': myself}\n\treturn render(request, 'profile.html', data)\n\n@login_required\n@is_superuser\ndef modify_super(request, op, id):\n\tuser_target = User.objects.get(id=id)\n\tauth = 0\n\tif op == \"make\":\n\t\ts = Superuser(user=user_target, auth=auth)\n\t\ts.save()\n\telif op == \"remove\":\n\t\ts = Superuser.objects.get(user=user_target)\n\t\ts.delete()\n\telse:\n\t\tpass\n\treturn HttpResponseRedirect('/user/')\n\n@login_required\n@is_superuser\ndef classroom_list(request):\n\tclassrooms = Classroom.objects.all()\n\tif request.method == \"POST\":\n\t\tform = CreateClassroom(request.POST)\n\t\tform.save()\n\t\treturn HttpResponseRedirect('/classroom/')\n\telse:\n\t\tform = CreateClassroom()\n\n\tdata = {'classrooms': classrooms, 'form': form}\n\treturn render(request, 'classroom.html', data)\n\n@login_required\n@is_superuser\ndef classroom_detail(request, cid):\n\tclassroom = Classroom.objects.get(id=cid)\n\tif request.method == \"POST\":\n\t\tif request.POST['op'] == 'add-teacher':\n\t\t\tform = AddTeacher(request.POST)\n\t\t\t# role = form.cleaned_data.get('user')\n\t\t\t# user = form.cleaned_data.get('user')\n\t\t\t# user = form.cleaned_data.get('user')\n\t\t\tf = form.save(commit=False)\n\t\t\tf.classroom = classroom\n\t\t\tf.save()\n\t\telif request.POST['op'] == 'add-student':\n\t\t\tform2 = AddStudent(request.POST)\n\t\t\tf = form2.save(commit=False)\n\t\t\tf.classroom = classroom\n\t\t\tf.save()\n\t\telse:\n\t\t\tpass\n\t\treturn HttpResponseRedirect('/classroom/{}'.format(cid))\n\telse:\n\t\tform = AddTeacher()\n\t\tform2 = AddStudent()\n\tt = Teacher.objects.filter(classroom=classroom)\n\tteachers = [i.user for i in t]\n\tl_tid = [i.id for i in teachers]\n\ts = Student.objects.filter(classroom=classroom)\n\tstudents = [i.user for i in s]\n\tquizes = Quiz.objects.filter(classroom=classroom)\n\t# quizes = [i.name for i in q]\n\n\n\tdata = {'form': form, 'form2': form2, 'teachers': teachers, 'students': students, 'quizes': quizes, 'cid': cid, 'l_tid': l_tid}\n\treturn render(request, 'classroom_detail.html', data)\n\n@login_required\n@is_superuser\ndef modify_teacher(request, op, cid, uid):\n\tif op == \"remove\":\n\t\tc = Classroom.objects.get(id=cid)\n\t\tu = User.objects.get(id=uid)\n\t\tt = Teacher.objects.get(classroom=c, user=u)\n\t\tt.delete()\n\telse:\n\t\tpass\n\treturn HttpResponseRedirect('/classroom/{}'.format(cid))\n","sub_path":"clatest/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"497048438","text":"from tkinter import *\n\nmaster = Tk()\nFrameBIG = Frame(master)\n\nMain = Canvas(FrameBIG,background=\"blue\", height = 500,width =500)\nMain.configure(scrollregion=Main.bbox(\"all\"))\n\nscroll = Scrollbar(FrameBIG ,orient=\"vertical\", command=Main.yview)\nMain.configure(yscrollcommand=scroll.set)\n\nscroll.pack(side=\"right\", fill=\"y\")\nMain.pack(side = BOTTOM, anchor = NW,fill=\"x\")\nFrameBIG.pack(anchor = W, fill = \"x\")\n\n\n\nmaster.mainloop()","sub_path":"ChatApplication-Server/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"434160724","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('heroes', '0003_auto_20160109_1905'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='hero',\n options={'verbose_name_plural': 'Heroes'},\n ),\n migrations.AlterModelOptions(\n name='herohistory',\n options={'verbose_name_plural': 'Heroes History'},\n ),\n migrations.RenameField(\n model_name='herohistory',\n old_name='critDamage',\n new_name='crit_damage',\n ),\n ]\n","sub_path":"heroes/migrations/0004_auto_20160110_1700.py","file_name":"0004_auto_20160110_1700.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"362225414","text":"import matplotlib.pyplot as pete\n# import _pera as ppp\n\n#ppp = struct.annainfo[]\n# papel = {\n# 'proyecto': './test_proj',\n# 'input': {\n# 'n_pisos': 4,\n# 'n_vanos': 3,\n# 'n_marcos': 4,\n# 'h_pisos': 300,\n# 'b_losas': 700,\n# 'd_losas': 700,\n# 'b_COL': 90,\n# 'b_VIG': 50,\n# 'h_VIG': 90,\n# 't_losas': 15,\n# '𝜈': 0.25,\n# 'fc': 25,\n# '𝛾': 2500,\n# 'valH': 75000,\n# 'valA': 1000,\n# 'zona': 3,\n# 'suelo': 'E',\n# 'categoria': 'II',\n# 'R': 7,\n# 'pMASA': 500,\n# 'Q_L': 0.25\n# }\n# }\n\ndef jandro(los_perfiles, las_fuerzas, papel):\n proyecto = papel['proyecto']\n fc = papel['input']['fc']*10 #transformación a kgf/cm2\n hmax_vig = papel['input']['h_VIG'] # cms\n bmax_vig = papel['input']['b_VIG'] # cms\n bmax_col = papel['input']['b_COL'] # cms\n H = papel['input']['h_pisos']/100 # transformación a metros\n Lo = papel['input']['b_losas']/100 # transformación a metros\n npisos = papel['input']['n_pisos']\n nbahias = papel['input']['n_vanos']\n ncol = npisos*(nbahias+1)\n nvig = npisos * nbahias\n cS = papel['input']['valA']*7850 # transformación a $/m3\n cH = papel['input']['valH']\n tabla= las_fuerzas['body']\n largosC = [[int(H) for i in range(nbahias+1)] for j in range(npisos)]\n largosV = [[int(Lo) for i in range(nbahias)] for j in range(npisos)]\n hColMax, hColMin= bmax_col, 30\n dList, deList = [16,18,22,25,28,32,36],[10,12,16]\n listadim= los_perfiles\n nelem=len(listadim)\n dp, es, ey, eu, fy = 5,2100000,0.002,0.003,4200\n dimV = [[[int(round((listadim[ncol:][(i)+j*(nbahias)][1])/5,1))*5+5,\n int(round((listadim[ncol:][(i)+j*(nbahias)][0])/5,1))*5+10,\n int((listadim[ncol:][(i)+j*(nbahias)][1]-0.01)/5)*5+5,\n int(round((listadim[ncol:][(i)+j*(nbahias)][0]-15)/5,1))*5]\n for i in range(nbahias)] for j in range(npisos)]\n dimC = [[[int(round((listadim[:ncol][(i)+j*(nbahias+1)][1])/5,1))*5+15,\n int(round((listadim[:ncol][(i)+j*(nbahias+1)][0])/5,1))*5+15,\n int(round((listadim[:ncol][(i)+j*(nbahias+1)][1])/5,1))*5,\n int(round((listadim[:ncol][(i)+j*(nbahias+1)][0])/5,1))*5]\n for i in range(nbahias+1)] for j in range(npisos)]\n\n def beta1(fc):\n if 550 >= fc >= 280:\n return round(0.85-0.05/70*(fc-280), 2)\n else:\n return 0.85 if fc < 280 else 0.65\n b1 = beta1(fc)\n\n def filtroCV(combis, combi_e, combi_s, tab, largosV, largosC):\n\n bars1=[[tab[i-1]+tab[i] for j in range(2) if j==1]\n for i in range(len(tab)) if i%2!=0]\n bars2=[bars1[i][0] for i in range(len(bars1))]\n bars=[[bars2[i] for i in range(combis*j, combis*j+combis)]\n for j in range(int(len(bars2)/combis))]\n\n exc=[]\n for i in range(len(bars)):\n temp1=[]\n maxim=0\n for j in range(len(bars[0])):\n for k in range(len(bars[0][0])):\n if bars[i][j][4]/bars[i][j][6]>bars[i][j][8]/bars[i][j][10]:\n pu=bars[i][j][4]\n mu=bars[i][j][6]\n else:\n pu=bars[i][j][8]\n mu=bars[i][j][10]\n ex=mu/pu\n if ex>maxim:\n maxim=ex\n list1=[round(mu,1), round(pu,1), round(ex,3)]\n temp1.append(list1)\n exc.append(temp1)\n\n bars_e1=[bars2[i] for i in range(len(bars2)) if 'E' in bars2[i][2]]\n bars_s1=[bars2[i] for i in range(len(bars2)) if 'E' not in bars2[i][2]]\n bars_e=[[bars_e1[i] for i in range(combi_e*j, combi_e*j+combi_e)]\n for j in range(int(len(bars_e1)/combi_e))]\n bars_s=[[bars_s1[i] for i in range(combi_s*j, combi_s*j+combi_s)]\n for j in range(int(len(bars_s1)/combi_s))]\n col_e=[[bars_e[j][i] for i in range(0, combi_e)] for j in range(len(bars_e))\n if bars_e[j][0][0]=='COL']\n col_s=[[bars_s[j][i] for i in range(0, combi_s) if bars_s[j][i][2]!='1.2 D + L']\n for j in range(len(bars_s)) if bars_s[j][0][0]=='COL']\n\n col_dl=[[bars_s[j][i] for i in range(0, combi_s) if bars_s[j][i][2]=='1.2 D + L']\n for j in range(len(bars_s)) if bars_s[j][0][0]=='COL']\n vig_e=[[bars_e[j][i] for i in range(0, combi_e)]\n for j in range(len(bars_e)) if bars_e[j][0][0]=='VIGA']\n vig_s=[[bars_s[j][i] for i in range(0, combi_s)if bars_s[j][i][2]!='1.2 D + L']\n for j in range(len(bars_s)) if bars_s[j][0][0]=='VIGA']\n vig_dl=[[bars_s[j][i] for i in range(0, combi_s)if bars_s[j][i][2]=='1.2 D + L']\n for j in range(len(bars_s)) if bars_s[j][0][0]=='VIGA']\n\n maTrix_ij = lambda lista:[[[round(lista[k][j][i],1) for j in range(len(lista[0]))]\n for i in [5,9]] for k in range(len(lista))]\n maxTrix_i = lambda lista:[[round(max([lista[k][j][i] for j in range(len(lista[0]))]),2)\n for i in [4,5,6]] for k in range(len(lista))]\n minTrix_i = lambda lista:[[round(min([lista[k][j][i] for j in range(len(lista[0]))]),2)\n for i in [4,5,6]] for k in range(len(lista))]\n maxTrix_j = lambda lista:[[round(max([lista[k][j][i] for j in range(len(lista[0]))]),2)\n for i in [8,9,10]] for k in range(len(lista))]\n minTrix_j = lambda lista:[[round(min([lista[k][j][i] for j in range(len(lista[0]))]),2)\n for i in [8,9,10]] for k in range(len(lista))]\n\n npisos, nbahias = len(col_e)-len(vig_e), int(len(vig_e)/(len(col_e)-len(vig_e)))\n\n\n forma_col = lambda lista, nbahias, npisos:[\n [lista[j] for j in range(i*(nbahias+1), (i+1)*(nbahias+1))] for i in range(npisos)]\n forma_vig = lambda lista, nbahias, npisos:[\n [lista[j] for j in range(i*(nbahias), (i+1)*(nbahias))] for i in range(npisos)]\n\n exc = forma_col(exc[:len(col_e)],nbahias, npisos)\n\n max_col_ei = forma_col(maxTrix_i(col_e),nbahias,npisos)\n max_col_si = forma_col(maxTrix_i(col_s),nbahias,npisos)\n max_col_dli = forma_col(maxTrix_i(col_dl),nbahias,npisos)\n\n min_col_ei = forma_col(minTrix_i(col_e),nbahias,npisos)\n min_col_si = forma_col(minTrix_i(col_s),nbahias,npisos)\n min_col_dli = forma_col(minTrix_i(col_dl),nbahias,npisos)\n\n max_col_ej = forma_col(maxTrix_j(col_e),nbahias,npisos)\n max_col_sj = forma_col(maxTrix_j(col_s),nbahias,npisos)\n max_col_dlj = forma_col(maxTrix_j(col_dl),nbahias,npisos)\n\n min_col_ej = forma_col(minTrix_j(col_e),nbahias,npisos)\n min_col_sj = forma_col(minTrix_j(col_s),nbahias,npisos)\n min_col_dlj = forma_col(minTrix_j(col_dl),nbahias,npisos)\n\n mat_col_e = forma_col(maTrix_ij(col_e),nbahias,npisos)\n mat_col_s = forma_col(maTrix_ij(col_s),nbahias,npisos)\n\n max_vig_ei = forma_vig(maxTrix_i(vig_e),nbahias,npisos)\n max_vig_si = forma_vig(maxTrix_i(vig_s),nbahias,npisos)\n max_vig_dli = forma_vig(maxTrix_i(vig_dl),nbahias,npisos)\n\n min_vig_ei = forma_vig(minTrix_i(vig_e),nbahias,npisos)\n min_vig_si = forma_vig(minTrix_i(vig_s),nbahias,npisos)\n min_vig_dli = forma_vig(minTrix_i(vig_dl),nbahias,npisos)\n\n max_vig_ej = forma_vig(maxTrix_j(vig_e),nbahias,npisos)\n max_vig_sj = forma_vig(maxTrix_j(vig_s),nbahias,npisos)\n max_vig_dlj = forma_vig(maxTrix_j(vig_dl),nbahias,npisos)\n\n min_vig_ej = forma_vig(minTrix_j(vig_e),nbahias,npisos)\n min_vig_sj = forma_vig(minTrix_j(vig_s),nbahias,npisos)\n min_vig_dlj = forma_vig(minTrix_j(vig_dl),nbahias,npisos)\n\n mat_vig_e = forma_vig(maTrix_ij(vig_e),nbahias,npisos)\n mat_vig_s = forma_vig(maTrix_ij(vig_s),nbahias,npisos)\n\n matCorte_col=[mat_col_e,mat_col_s]\n matCorte_vig=[mat_vig_e,mat_vig_s]\n\n #'axial', 'corte', 'momento'\n listaV=[]\n for i in range(len(max_vig_ei)):\n lista1=[]\n lista2=[]\n for j in range(len(max_vig_ei[i])):\n lista1=[[round(max_vig_si[i][j][1]/1000,2), round(max_vig_ei[i][j][1]/1000,2),\n round(max(max_vig_ei[i][j][2],max_vig_si[i][j][2])/1000,2),\n round(min(min_vig_ei[i][j][2],min_vig_si[i][j][2])/1000,2),round(max_vig_dli[i][j][1]/1000,2),\n largosV[i][j],mat_vig_s[i][j][0],mat_vig_e[i][j][0]],\n [round(max_vig_sj[i][j][1]/1000,2), round(max_vig_ej[i][j][1]/1000,2),\n round(max(max_vig_ej[i][j][2],max_vig_sj[i][j][2])/1000,2),\n round(min(min_vig_ej[i][j][2],min_vig_sj[i][j][2])/1000,2),round(max_vig_dlj[i][j][1]/1000,2),\n largosV[i][j],mat_vig_s[i][j][1],mat_vig_e[i][j][1]]]\n lista2.append(lista1)\n listaV.append(lista2)\n listaC=[]\n for i in range(len(max_col_ei)):\n lista1=[]\n lista2=[]\n for j in range(len(max_col_ei[i])):\n\n lista1=[[round(max(max_col_ei[i][j][0], max_col_si[i][j][0])/1000,2),\n round(min(min_col_ei[i][j][0], min_col_si[i][j][0])/1000,2), round(max_col_si[i][j][1]/1000,2),\n round(max_col_ei[i][j][1]/1000,2), round(max(max_col_ei[i][j][2],max_col_si[i][j][2],\n abs(min_col_ei[i][j][2]),abs(min_col_si[i][j][2]))/1000,2),\n largosC[i][j],mat_col_s[i][j][0],mat_col_e[i][j][0]],\n [round(max(max_col_ej[i][j][0], max_col_sj[i][j][0])/1000,2),\n round(min(min_col_ej[i][j][0], min_col_sj[i][j][0])/1000,2), round(max_col_sj[i][j][1]/1000,2),\n round(max_col_ej[i][j][1]/1000,2), round(max(max_col_ej[i][j][2],max_col_sj[i][j][2],\n abs(min_col_ej[i][j][2]),abs(min_col_sj[i][j][2]))/1000,2),\n largosC[i][j],mat_col_s[i][j][1],mat_col_e[i][j][1]]]\n lista2.append(lista1)\n listaC.append(lista2)\n return [listaV, listaC, exc]\n\n def V2vig(x1, lo, vuLsti, vueLsti, vuLstj, vueLstj, vupr, vc, state):\n vc = vc if state==1 else 0\n v2Calc = lambda v1, v2, x1, lo: round(v1 - x1 * (v1 - v2) / lo, 1)\n vupr2 = v2Calc(vupr,-vupr,x1,lo)/0.75-vc\n vu2 = max([v2Calc(vuLsti[i],vuLstj[i], x1, lo) for i in range(len(vuLsti))])/0.75-vc\n vue2 = max([v2Calc(vueLsti[i],vueLstj[i], x1, lo) for i in range(len(vueLsti))])/0.6\n return round(max(vupr2,vu2, vue2),1)\n\n def et(h,eu,dp,c): return round(eu*abs(h-dp-c)/c, 4)\n\n def aCir(d): return round(0.007854*d**2, 3)\n\n def phi(eu,et,ey):\n if ey <= et <= (eu+ey):\n return round(0.65+0.25/eu*(et-ey), 2)\n else:\n return 0.65 if et < ey else 0.9\n\n def aLstC(dEsq,dLat,nHor,nVer):\n a = round(aCir(dEsq)*2+nHor*aCir(dLat), 3)\n return [a]+[round(aCir(dLat)*2,3) for i in range(nVer)]+[a]\n\n def yLstC(dp,h,nVer):\n yLst = [dp]\n for i in range(1,nVer+1):\n yi = round((h-yLst[i-1]-dp)/(nVer+2-i)+yLst[i-1],0)\n yLst.append(int(yi))\n yLst.append(h-dp)\n return yLst\n\n def pmC(aLst,b,b1,c,es,eu,ey,fc,fy,h,yLst):\n eiLst = [round(eu*(c-i)/c, 5) for i in yLst]\n fsLst = [fy*abs(i)/i if abs(i)>ey else es*i for i in eiLst]\n psLst = [fsLst[i] * aLst[i] for i in range(len(aLst))]\n Pc = 0.85*b1*fc*b*c\n Ps = sum(psLst)\n Mc = Pc/2*(h-0.85*c)\n Ms = sum((psLst[i]*(h/2-yLst[i]) for i in range(len(aLst))))\n return [round((Pc+Ps)/1000, 2), round((Mc+Ms)/100000, 2)]\n\n def cPn(aLst,b,b1,dp,es,eu,ey,fc,fy,h,pnB,yLst):\n c1 = 0\n c2 = max(h/b1, 3*(h-dp))\n PnMax = round((0.85*fc*(h*b-sum(aLst))+sum(aLst)*fy)/1000, 2)\n PhiPnMax = PnMax*0.8*0.65\n PnMin = round((-sum(aLst)*fy)/1000, 2)\n PhiPn = pnB+10\n i = 0\n if pnB > PnMin * 0.9 + 10:\n pnB = PhiPnMax if pnB >= PhiPnMax else pnB\n while abs(pnB-PhiPn) > 0.1 and i<15:\n c = round((c1+c2)/2,3)\n i += 1\n PMC = pmC(aLst,b,b1,c,es,eu,ey,fc,fy,h,yLst)\n eT = et(h,eu,dp,c)\n Phi = phi(eu,eT,ey)\n PhiPn = (PMC[0])*Phi\n PhiMn = (PMC[1])*Phi\n c2 = c if PhiPn > pnB else c2\n c1 = c if PhiPn < pnB else c1\n else:\n c = 0\n PhiPn = PnMin*0.9\n PhiMn = 0\n Phi = 0.9\n return [round(c, 2), abs(round(PhiMn, 1)), round(PhiPn, 1), Phi]\n\n def cFind(aLst, b, b1, dp, es, eu, ey, fc, fy, h, mu, pu, yLst):\n mu = round(abs(mu),3)\n pu = round(pu,3)\n PhiPnMin = round((-sum(aLst)*fy)/1000*0.9,1)\n PhiPnMax = round((0.85*fc*(h*b-sum(aLst))+sum(aLst)*fy)*0.8*0.65/1000,1)\n if puPhiPnMax:\n pu = PhiPnMax\n elif abs(pu) <= 0.1:\n return cPn(aLst,b,b1,dp,es,eu,ey,fc,fy,h,0,yLst)\n e = min(mu/pu,999)\n i = 0\n c2 = 0\n ex = e+1\n c1 = h/b1 if e > 0 else cPn(aLst,b,b1,dp,es,eu,ey,fc,fy,h,0,yLst)[0]\n while abs(round(e,3)-ex) > 0.001 and i < 15:\n c = round((c1+c2)/2,2)\n i += 1\n PMC = pmC(aLst,b,b1,c,es,eu,ey,fc,fy,h,yLst)\n ex = round((abs(PMC[1]))/(PMC[0]),3)\n c1 = c if ex < e else c1\n c2 = c if ex > e else c2\n e = ex\n eT = round(eu*abs(h-dp-c)/c,4)\n Phi = phi(eu,eT,ey)\n asdf=pmC(aLst,b,b1,c,es,eu,ey,fc,fy,h,yLst)\n phipn = PMC[0]*Phi\n phimn = PMC[1]*Phi\n return [c,abs(round(phimn,1)),round(phipn,1), Phi, e, PhiPnMin, PhiPnMax]\n\n def resumen(aLst, c, b, dp, h, eu, fy, fc, b1, es, ey, yLst):\n PMC = pmC(aLst, b, b1, c, es, eu, ey, fc, fy, h, yLst)\n eT = round(eu*abs(h-dp-c)/c, 4)\n Phi = phi(eu, eT, ey)\n PMCpr = pmC(aLst, b, b1, c, es, eu, ey, fc, fy*1.25, h, yLst)\n return [PMC[0]*Phi,PMC[0],PMCpr[0],PMC[1]*Phi,PMC[1],PMCpr[1]]\n\n def FU(pu, mu, pn, mn):\n if abs(mu) < 0.1:\n return abs(pu/(pn+0.01))\n else:\n return max(abs(pu/(pn+0.01)), abs(mu/(mn+0.01)))\n\n def yLstV(h, dp, db):\n # se busca el minimo de niveles barras laterales complementarias\n blat = min(int((h-2*dp-db/4)/25), int((h-2*dp-db/4)/20)+1)\n # se crea lista con dos primeros niveles (1/4*10=2.5 veces el diámetro mayor)\n Y = [dp, max(dp+db/4, 2*dp)]\n #se agrega cada nivel de barras complementarias\n for i in range(blat):\n Y.append(round(Y[-1]+(h-2*dp-db/4)/(blat+1), 0))\n # la función retorna la lista de posiciones de barras completa\n return Y + [h - dp] if Y[-1] < (h-dp) else Y\n\n # función para el cálculo de área requerida asegurando et>=0.005\n def areaV(mu, b, b1, h, fc, fy, dp):\n muu = round(mu/(0.9*0.85/100000*fc*b*(h-dp)**2), 3)\n muu = 0.5 if muu > 0.5 else muu\n ulim = round(0.375*b1*(1-0.1875*b1), 3)\n wp = 0 if muu < ulim else round((muu-ulim)/(1-dp/(h-dp)), 3)\n w = 0.375+wp if wp > 0 else round(1-(1-2*muu)**0.5, 3)\n return round(w*0.85*fc*b*(h-dp)/fy, 2)\n\n def listadiam1(A, b, dp, h, dList, v):\n sup = [i for i in range(int(1+(b-2*dp)/15), 2+int((b-2*dp)/10))]\n listadiam = []\n for i in sup:\n n2 = int(i/2) if i>2 else 0\n n1 = i-n2\n for j in range(len(dList)):\n j = dList[j]\n if n2>0:\n for k in range(len(dList)):\n k = dList[k]\n if A<=n1*aCir(j)+n2*aCir(k) and j+v>=k>=j-v:\n listadiam+=[[n1, j, n2, k, round(aCir(j)*n1+aCir(k)*n2, 2)]]\n else:\n continue\n else:\n if 1.2*A>=n1*aCir(j)>=A:\n listadiam+=[[n1, j, n2, 0, round(n1*aCir(j), 2)]]\n else:\n continue\n return listadiam\n\n def listadiam(A, b, dp, h, dList, v):\n amin = 10*A\n A /= 2\n lista1 = listadiam1(A, b, dp, h, dList, v)\n lista2 = []\n minimos = []\n for i in range(len(lista1)):\n if lista1[i][4]<=1.2*A:\n lista2+=[lista1[i]]\n else:\n continue\n for i in range(len(lista2)):\n L1 = lista2[i]\n ar1= L1[4]\n ar2=round(2*A-ar1, 2)\n ar2 = ar2 if ar2>0 else 0\n lista3 = listadiam1(ar2, b, dp, h, dList, v)\n if lista3 == []:\n continue\n for j in range(len(lista2)):\n L2 = lista3[i]\n if 2*A>L1[4]+L2[4]:\n continue\n else:\n if L1[4]+L2[4]L1[4]:\n minimos = [L2, L1, round(amin, 2)]\n else:\n minimos = [L1, L2, round(amin, 2)]\n return minimos\n\n def critVC(vigas,columnas):\n newcol=[]\n for i in range(len(vigas)-1):\n new=[]\n for j in range(len(vigas[0])):\n if i == 0:\n mc1=columnas[i][j]\n mc2=columnas[i+1][j]\n mv1=vigas[i][j][0]\n mc=mc1+mc2\n dif=1.2*mv1-mc\n if dif > 0:\n columnas[i][j]=dif*mc1/(mc1+mc2)+mc1\n columnas[i+1][j]=dif*mc2/(mc1+mc2)+mc2\n elif i == len(vigas[0])-1:\n mc1 = columnas[i][j]\n mc2 = columnas[i + 1][j]\n mv2 = vigas[i][j][1]\n mc = mc1 + mc2\n dif = 1.2 * mv2 - mc\n if dif > 0:\n columnas[i][j] = dif * mc1 / (mc1 + mc2) + mc1\n columnas[i+1][j] = dif * mc2 / (mc1 + mc2) + mc2\n else:\n mc1 = columnas[i][j]\n mc2 = columnas[i+1][j]\n mv1 = vigas[i][j][0]\n mv2 = vigas[i][j][1]\n mc = mc1 + mc2\n dif = 1.2 * (mv1+mv2) - mc\n if dif > 0:\n columnas[i][j] = dif * mc1 / (mc1 + mc2) + mc1\n columnas[i+1][j] = dif * mc2 / (mc1 + mc2) + mc2\n newcol.append(new)\n newcol.append(columnas[-1])\n return newcol\n\n def extMat(lista, indice):\n mat1=[]\n for i in lista:\n mat2=[]\n for j in i:\n mat2.append(j[indice])\n mat1.append(mat2)\n return mat1\n\n def replMat(lista1, lista2, indice):\n for i in range(len(lista2)):\n for j in range(len(lista2[i])):\n lista1[i][j][indice]=lista2[i][j]\n return lista1\n\n def matElemV(lista, bmaxV, hmaxV, cH, cS, b1, dp, es, ey, eu, fc, fy, dList, ai, deList, v):\n #se itera en la lista\n listaV = []\n for i in lista:\n # se filtra la lista por piso\n tempV=[]\n for j in i:\n elem = optimusVig(j[2],j[3],es,eu,ey,b1,fc,fy,dp,dList,hmaxV,bmaxV,ai,j[5],cH,cS,v)\n tempV.append(elem)\n listaV.append(tempV)\n return listaV\n\n def Lramas(xList):\n lar=len(xList)\n lista = [xList[0]]\n if lar%2 == 0:\n rango = xList[-1]-xList[0]\n for i in range(1, lar-1):\n if xList[i]-lista[-1]==30:\n lista.append(xList[i])\n elif xList[i]-lista[-1]>30:\n lista.append(xList[i-1])\n lista.append(xList[-1])\n minram = int((len(lista)+1)/2)*2\n maxram = len(xList)\n rlist = [i for i in range(minram, maxram+1, 2)]\n listas = []\n for i in rlist:\n sep = round(rango/(i-1), 1)\n complist = [xList[0]]\n for _ in range(i-1):\n complist.append(sep+complist[-1])\n lista2 = [xList[0]]\n for j in range(1, len(complist)-1):\n dif=999\n for k in xList:\n if abs(k-complist[j])30:\n lista.append(midL[i-1])\n lista.append(midL[-1])\n if lista[-2]-(xList[0]+xList[-1])/2<=15:\n lista.remove(lista[-1])\n lista2 = []\n for j in reversed(lista):\n lista2.append(xList[-1]+xList[0]-j)\n lista+=lista2\n listas=[lista]\n minram=2\n maxram=len(xList)\n rlist=[i for i in range(minram, maxram+1)]\n for i in rlist:\n sep = round(rango/(i-1), 1)\n complist = [xList[0]]\n rango=xList[-1]-xList[0]\n for _ in range(i-1):\n complist.append(sep+complist[-1])\n lista2 = [xList[0]]\n for j in range(1, len(complist)-1):\n dif=999\n for k in xList:\n if abs(k-complist[j])30:\n borrar=1\n if borrar!=1:\n listas2.append(i)\n return listas2\n\n def estribosV(xList, ramas):\n Lestrib = []\n medio = xList[int(len(xList)/2)]\n for j in ramas:\n mid=int(len(j)/2)\n L1 = j[0:mid]\n if len(j)%2!=0:\n L2 = j[mid+1:]\n cond=1\n else:\n L2 = j[mid:]\n cond=0\n estribos=[[L1[i],L2[i]] for i in range(len(L1))]\n if cond==1:\n estribos+=[[medio]]\n Lestrib.append(estribos)\n return Lestrib\n\n\n def ldC(fy,fc,db):\n return round(max(0.075*fy*0.1*db/(fc)**0.5, 0.0044*fy*0.1*db),1)\n\n#traslapo vigas\n def ldV(db, fc, fy):\n if db<19:\n return 0.1*db*fy/(21*(fc/10)**0.5)\n else:\n return 0.1*db*fy/(17*(fc/10)**0.5)\n\n def ldhV(fy, db, fc):\n return fy*db/(170*(fc)**0.5)\n\n def lGanchoC(db, fc, fy, h, dp):\n if db<19:\n ld = round(max(0.1*db*fy/(3.46*(fc)**0.5), 2.5*db+10),1)\n return [round(ldC(fy,fc,db)+0.6*3.1416/4*db+ld,1), ld]\n else:\n ld = round(max(0.1*db*fy/(4.4*(fc)**0.5), 2.5*db+10))\n return [round(ldC(fy,fc,db)+0.6*3.1416/4*db+ld,1), ld]\n\n def lGanchoV(fy, db, fc):\n return round(ldhV(fy,db,fc)+1.05*db-5,1)\n\n def rematC(db, ldV, h, dp):\n return max(2.5*db+10, ldV+dp-h)\n\n def aminV(fc,b,fy):\n return max(0.2*(fc)**0.5*b/fy,3.5*b/fy)\n\n def countram(ramas):\n nramas=[]\n for i in ramas:\n nramas+=[len(i)]\n return nramas\n\n def Lest(h, b, dp, de):\n return round((2*(h+b-4*dp+0.2*de)*10+6.75*de*3.1416+2*max(75, 6*de))/10, 2)\n\n def Ltrab(h, dp, de):\n return round((3.75*de*3.1416+2*max(75, 6*de)+(h+0.2*de-dp)*10)/10, 2)\n\n def vc(fc, b, h, dp):\n return round(0.53*(fc)**0.5*b*(h-dp)/1000, 2)\n\n def ashS(h, b, dp, fc, fy):\n return round(max(0.3*((b*h)/((h-dp)*(b-dp)))*(fc/fy), 0.09*(h-dp)*fc/fy), 3)\n\n def loCol(h, b, H):\n return round(max(h, b, H/6, 45), 1)\n\n def lEmp(fy, db):\n return round(max(0.00073*fy*db if fy<= 4200 else (0.0013*fy-2.4)*db, 30),0)\n\n #wo es corte y no carga distribuida\n def vprV(h, b, l, mpr1, mpr2, wo):\n return 100*(mpr1+mpr2)/l + wo/50\n\n def VcAx(Nu, fc, b, h, dp):\n return round(0.53*(1+Nu*1000/(140*h*b))*(fc)**0.5*b*(h-dp)/1000, 1)\n\n def vsLim(fc, b, h, dp):\n return round(2.2*(fc)**0.5*b*(h-dp)/1000,2)\n\n def sRotV(h, dp, db):\n return round(max(min(15, 0.6*db, (h-dp)/4),8), 1)\n\n def sRotC(h, b, db, hx):\n return round(min(max(min(15,0.6*db,(10+(35-hx)/3)),8),10),1)\n\n def sMax(fc, b, h, dp, sm):\n return min(round((h-dp)/4 if vc(fc, b, h, dp)>0.33*(h-dp)*b*(fc/10)**0.5 else (h-dp)/2, 2), sm)\n\n def sEmp(h, dp):\n return round(min(10, (h-dp)/4), 1)\n\n def sCol(db):\n return min(0.6*db, 15)\n\n def cubEstV(h, dp, de, Le):\n lista1 = []\n lista2 = []\n for i in Le:\n if len(i)%2 == 0:\n b = i[1]-i[0]\n lista1 += [Lest(h, b, dp, de)]\n else:\n lista2 += [Ltrab(h, dp, de)]\n return [round((sum(lista1)+sum(lista2))*aCir(de) ,1), lista1, lista2]\n\n def estribosC(xList):\n lista = []\n ramas = Lramas(xList)\n count = []\n for i in ramas:\n count.append(len(i))\n Lestrib = []\n temp = i\n while len(temp) > 0:\n if len(temp) >= 2:\n Lestrib.append([temp[0],temp[-1]])\n temp.remove(temp[0])\n temp.remove(temp[-1])\n elif len(temp) == 1:\n Lestrib.append([temp[0]])\n temp.remove(temp[0])\n else:\n break\n lista.append(Lestrib)\n Lestrib = []\n return lista, count\n\n def xLst(sup, b, dp):\n mid = int(sup[0] / 2)\n if sup[2]%2==0:\n l1=[sup[1] for i in range(mid)]\n l2=[sup[3] for i in range(sup[2])]\n else:\n l1=[sup[1] for i in range(mid)]\n l2=[sup[3] for i in range(sup[2])]\n lista=l1+l2+l1\n xList=yLstC(dp, b, len(lista)-2)\n return lista, xList\n\n def minEstC(mpr1, mpr2, Nu, H, vu, vue, yList, deList, db, h, b, dp, fy, fc, cS,hvig):\n salida1, salida2, salida3 = 0, 0, 0\n H*=100\n vu = vu*1000\n vue = vue*1000\n mpr1*=100000\n mpr2*=100000\n Vc = VcAx(Nu, fc, b, h, dp)*1000\n vupr = round((mpr1+mpr2)/H,1)\n vupr1 = vupr if Nu*1000 < 0.05 * fc * (h * b) else vupr-Vc\n vupr2 = vupr-Vc\n vu1 = round(max((vu-Vc)/0.75, vue/0.6, vupr1/0.75),1)\n vslim = vsLim(fc, b, h, dp)*1000*1.1\n lo = loCol(h, b, H)\n vu2 = round(max((vu-Vc)/0.75, vue/0.6, (vupr1-Vc)/0.75), 1)\n s = round(sCol(db))\n estr = estribosC(yList)\n est = estr[0]\n nRam = estr[1]\n ramas = Lramas(yList)\n if len(ramas)>1:\n srotL = [int(sRotC(h, b, db, l)) for l in [min(k) for k in [[i[j]-i[j-1] for j in range(1,len(i))] for i in ramas]]]\n else:\n ramitas = ramas[0]\n aux1=[ramitas[i]-ramitas[i-1] for i in range(1,len(ramitas))]\n srotL = [int(sRotC(h, b, db, max(aux1)))]\n sash = round(max(ashS(h, b, dp, fc, fy),aminV(fc,b,fy)), 3)\n s1L = [[i, j, k, l] for i in range(len(nRam)) for j in deList for l in deList if l <= j\n for k in range(8, min(int(sRotC(h, b, db, srotL[i])), int(round(100/((sash * 100 / (2 * aCir(j) + (nRam[i] - 2) * aCir(l)))-1), 1))+1))\n if vu1 <= round((2*aCir(j)+(nRam[i]-2)*aCir(l))*fy*(h-dp)/k, 1) <= vslim]\n if s1L==[]:\n return 0\n minimo = 99999999\n for i, j, k, l in s1L:\n ramas1 = est[i]\n l1 = Lest(h, ramas1[0][1]-ramas1[0][0], dp, j)\n l2 = sum([Lest(h, ramas1[m][1]-ramas1[m][0], dp, l) if len(ramas1[m])==2 else Ltrab(h, dp, l)\n for m in range(1,len(ramas1))])\n s1 = int((lo-0.01)/k)+1\n costo = round(2*s1*(l1*aCir(j)+2*l2*aCir(l))*cS/1000000, 0)\n if costo [costo, n° ramas, de_externo, espaciamiento, de_interno, n° estribos, largo1, largos2, largo_tot2, d_ramas, dist]\n # lista2 --> [costo, n° ramas, de_externo, espaciamiento, de_interno, n° estribos, largo1, largos2, largo_tot2, d_ramas, dist]\n # lista3 --> [costo, n° ramas, de_externo, espaciamiento, de_interno, n° estribos, largo1, largos2, largo_tot2, d_ramas, dist]\n salida=salida1+salida2+salida3\n if salida == 3:\n lLibre = round((H - 2 * lo - l_emp) / 2)\n pos1 = H\n pos2 = H-hvig-lo\n pos3 = (H-hvig+l_emp)/2\n pos4 = (H-hvig-l_emp)/2\n pos5 = lo\n ubc1 = lista1[9][1:-1] if len(lista1[9][1:-1]) >= 1 else []\n ubc2 = lista2[9][1:-1] if len(lista2[9][1:-1]) >= 1 else []\n ubc3 = lista3[9][1:-1] if len(lista3[9][1:-1]) >= 1 else []\n phiVn1 = round((2*aCir(lista1[2])+aCir(lista1[4])*(lista1[1]-2))*fy*(h-dp)/lista1[3],1)\n fuV1 = round(100*vu1/(phiVn1),1)\n phiVn2 = round((2*aCir(lista2[2])+aCir(lista2[4])*(lista2[1]-2))*fy*(h-dp)/lista2[3],1)\n fuV2 = round(100*vu2/phiVn2,1)\n phiVn3 = round((2*aCir(lista3[2])+aCir(lista3[4])*(lista3[1]-2))*fy*(h-dp)/lista3[3],1)\n fuV3 = round(100*vu2/phiVn3,1)\n\n salidaCC={'Ubicacion nodo y rotula1':[pos2, pos1],\n 'Ubicacion rotula2':[0,pos5],\n 'N° ramas rotula':lista1[1],\n 'N° estribos':lista1[5],\n 'espaciamiento rotula':lista1[3],\n \n 'Diametro estribo exterior rotula':lista1[2],\n 'Largo diametro exterior':lista1[6],\n\n 'Diametro estribo interior rotula':lista1[4],\n 'Lista largos interiores rotula':lista1[7],\n 'Lista ubicaciones horizontales exteriores rotula': lista1[9][0],\n 'Lista ubicaciones horizontales interiores rotula':ubc1,\n\n 'Ubicacion zona libre superior':[pos3, pos2],\n 'Ubicacion zona libre inferior':[pos5, pos4],\n 'N° ramas zona libre':lista2[1],\n 'N° estribos zona libre':lista2[5],\n 'Espaciamiento zona libre':lista2[3],\n\n 'Diametro exterior zona libre':lista2[2],\n 'Largo exterior zona libre':lista2[6],\n\n 'Diametro estribo interior zona libre':lista2[4],\n 'Lista largos interiores zona libre':lista2[7],\n 'Lista ubicaciones horizontales interiores zona libre':lista2[9][0],\n 'Lista ubicaciones horizontales interiores zona libre':ubc2,\n\n 'Ubicación empalme:':[pos3, pos4],\n 'N° Ramas empalme':lista3[1],\n 'N° Estribos empalme':lista3[5],\n 'Espaciamiento empalme':lista3[3],\n\n 'Diámetro estribo exterior empalme':lista3[2],\n 'Largo diámetro exterior empalme':lista3[6],\n\n 'Diámetro estribos interiores empalme':lista3[4],\n 'Lista largos interiores empalme':lista3[7],\n 'Lista ubicaciones horizontales exteriores empalme':lista3[9][0],\n 'Lista ubicaciones horizontales interiores empalme':ubc3\n }\n\n resCC={'phiVnC1':phiVn1,\n 'FUC1':fuV1,\n 'vu1':vu1,\n 'phiVnC2':phiVn2,\n 'FUC2':fuV2,\n 'vu2':vu2,\n 'phiVnC3':phiVn3,\n 'FUC3': fuV3\n }\n\n return [lista1,lista2,lista3,costo_total,vu1,vu2,hvig, salidaCC, resCC]\n else:\n return 0\n\n def optimusCol(b1, dp, es, eu, ey, fc, fy, muC, muCmin, puCmin, puCmax, dList, hmax,\n hmin, cH, cS, H, vu, vue, deList, iguales, hvig):\n salida=0\n minor = 9999999\n hmin = hmin if hmin >= 30 else 30\n hmax = hmax if hmax >= 30 else 30\n hList = [i for i in range(hmin, hmax+5,5)]\n lista = ([b, h] for b in hList for h in hList if b == h)\n for b, h in lista:\n nH = [i for i in range(int((b-2*dp)/15)-1, int(round((b-2*dp)/10, 0)), 1)]\n nV = nH\n listaND = ([j, k] for j in nH for k in nV if 10 <= (b-2*dp)/(j+1) <= 15 and\n 10 <= (h-2*dp)/(k+1) <= 15 and j == k)\n for j, k in listaND:\n if iguales == 0:\n listaDm = ([l, m] for l in dList for m in dList if m <= l >=16)\n else:\n listaDm = ([l, m] for l in dList for m in dList if m == l >= 16)\n for l, m in listaDm:\n ylist = yLstC(dp, h, k)\n alist = aLstC(l, m, j, k)\n cF = cFind(alist, b, b1, dp, es, eu, ey, fc, fy, h, muC, puCmax, ylist)\n cF2 = cFind(alist, b, b1, dp, es, eu, ey, fc, fy, h, muCmin, puCmin, ylist)\n fu = round(FU(puCmax, muC, cF[2], cF[1])*100,1)\n fu2 = round(FU(puCmin, muCmin, cF2[2], cF2[1])*100,1)\n aS = aCir(l)*4+aCir(m)*(2*j+2*k)\n cuan = round(aS/(b*h), 5)\n mpr1 = max(pmC(alist, b, b1, cF[0], es, eu, ey, fc, fy*1.25, h, ylist)[1],\n pmC(alist, b, b1, cF2[0], es, eu, ey, fc, fy*1.25, h, ylist)[1])\n mpr2 = mpr1\n #agregar a entrada H, vu, vue, deList\n if fu < 95 and fu2 < 95 and 0.01 <= cuan <= 0.06:\n corte1 = minEstC(mpr1, mpr2, muC, H, vu, vue, ylist,\n deList, min(l, m), h, b, dp, fy, fc, cS,hvig)\n if corte1 != 0:\n costo2 = corte1[3]\n volumen_as1 = round(aS*(corte1[2][10]+H*100)/1000000,6)\n peso_as=round(volumen_as1*7850,1)\n peso_as2 = round(costo2/cS*7850,1)\n volumen_ha = round(b*h*(corte1[2][10]+H*100)/1000000,2)\n costo1 = volumen_as1*cS + volumen_ha*cH\n costo = costo1+costo2\n if costo < minor:\n # corte = minEstC(mpr1, mpr2, muC, H, vu, vue, ylist, deList, min(l, m), h, b, dp, fy, fc, cS)\n minor, e = costo, round(cF[1] / (cF[2] + 0.001), 3)\n optimo = [minor, h, b, j, k, l, m, fu, fu2, cuan, cF[0], cF2[0], e, alist, ylist, cF[1],\n cF[2], muC, puCmax, puCmin, H, iguales, round(muCmin/puCmin,3), cF2[1], cF2[2], costo1, costo2, dp]\n salida=1\n corte=corte1\n\n else:\n continue\n\n if salida==1:\n salidaC={}\n\n salidaCC = corte[7]\n resCC = corte[8]\n\n salidaCF={'H':H,\n 'hvig':hvig,\n 'h':h,\n 'b':b,\n 'l_emp':corte[2][10],\n 'Lista Niveles':ylist,\n 'Lista de areas':alist,\n 'Cuantia':cuan,\n }\n\n resCF={'Mayor excentricidad':e,\n 'Mu_max':muC,\n 'phiMn1':cF[1],\n 'phiMn2':cF2[1],\n 'Pu_max':puCmax,\n 'Pu_min':puCmin,\n 'phiPn1':cF[2],\n 'phiPn2':cF2[2],\n 'FUCF1':fu,\n 'FUCF2':fu2,\n 'Volumen hormigon': volumen_ha,\n 'Peso acero longitudinal': peso_as,\n 'Peso acero transversal': peso_as2\n }\n\n salidaC.update(salidaCF)\n salidaC.update(salidaCC)\n salidaC.update(resCC)\n salidaC.update(resCF)\n salidaClist = list(salidaC.keys())\n\n return [optimo, corte, salidaC]\n else:\n return 0\n\n def minEstV(mpr1, mpr2, vuLsti,vueLsti,vuLstj,vueLstj, xList, deList, db, h, b, lo, dp, fy,\n fc, cS, wo, yLst, hcol, emp1, emp2):\n lo*=100\n Vc = vc(fc, b, h, dp)*1000\n vupr = round(vprV(h, b, lo, mpr1, mpr2,wo),3)*1000\n smax = sMax(fc, b, h, dp, 20)\n srot = int(sRotV(h, dp, db))\n sL1 = [i for i in range(8, int(srot)+1)]\n sL2 = [i for i in range(8, int(smax)+1)]\n vsL = vsLim(fc, b, h, dp)*1000*1.1\n ramas = Lramas(xList)\n est = estribosV(xList, ramas)\n nRam = countram(ramas)\n x1 = 2*h\n x2 = lo/2-2*h\n amin=aminV(fc,b,fy)\n Lout=[]\n for n in range(x1, x1 + 5, 5):\n xa1 = n\n xa2 = (x1 + x2) - xa1\n vsB1 = V2vig(0,lo,vuLsti,vueLsti,vuLstj,vueLstj,vupr,Vc,0)\n vsB2 = V2vig(xa1,lo,vuLsti,vueLsti,vuLstj,vueLstj,vupr,Vc,1)\n lista=[[i,j,k,l,m] for i in nRam for j in sL1 for k in deList for l in nRam\n for m in sL2 if vsB1/(fy*(h-dp))<=i*aCir(k)/j<=vsL/(fy*(h-dp))\n and vsB2/(fy*(h-dp))<=l*(aCir(k))/m<=vsL/(fy*(h-dp)) and i*aCir(k)>amin]\n minim = 999999999\n if lista!=[]:\n for i in lista:\n nr1, s1, de, nr2, s2 = i\n s3 = sEmp(h, dp)\n Lest1 = est[nRam.index(nr1)]\n Lest2 = est[nRam.index(nr2)]\n LestH = Ltrab(b, dp, de)\n ns1=int((xa1*2)/s1)\n if s2>10:\n ns2=int((xa2-(emp1+emp2)/2-0.01)*2/s2)+1\n ns3=int(((emp1+emp2)-0.01)/10)\n ns4 = ns2 if ns2>0 else 0\n ns2=ns4+ns3\n else:\n ns2 = int((xa2-0.01)*2 / s2) + 1\n nsH=ns1+ns2\n numH=len(yLst)-2\n cub1=cubEstV(h, dp, de, Lest1)\n cub2=cubEstV(h, dp, de, Lest2)\n mini = (cub1[0]*ns1+cub2[0]*ns2+LestH*nsH*numH)*cS/1000000\n X1 = xa1-5 if xa1 > 2*h else 2*h\n X2 = 2*((x1+x2)-X1)\n X3 = emp1+emp2\n X2 = round(X2-X3,1) if X2-X3>0 else 0\n phiVn1 = round(aCir(de)*nr1*fy*(h-dp)/s1,1)\n fuV1 = round(100*vsB1/(phiVn1),1)\n phiVn2 = round(aCir(de)*nr2* fy*(h-dp)/s2, 1)\n fuV2 = round(100*vsB2/phiVn2,1)\n if mini < minim:\n minim = round(mini, 2)\n #[costo, dist rot, n° ramas, espaciamiento, n° estribos, dist de rotula al centro, n° ramas, espaciamiento, n° estribos, de]\n Lout = [minim, X1, nr1, s1, ns1, X2, nr2, s2, ns2, de, vsB1, vsB2, cub1, cub2, nsH, numH,\n LestH,X3,emp1,emp2]\n aSVC = minim/cS * 7850\n\n salidaVC={ 'Ubicacion rotula':[0, X1, lo-hcol-X1, lo-hcol],\n 'Diametro rotula':de,\n 'N° ramas rotula':nr1,\n 'Estribos rotula':ns1,\n 'Espaciamiento rotula':s1,\n 'Largo de estribos':cub1,\n\n 'Ubicación central': [X1, lo-hcol-X1],\n 'Diametro central':de,\n 'N° ramas central':nr2,\n 'Longitud empalme barras inferiores':emp1,\n 'Longitud empalme barras superiores':emp2,\n 'Espaciamiento normal':s2,\n 'N° estribos normal':ns4,\n 'N° estribos empalme':ns3,\n 'Espaciamiento zona de empalme':s3,\n 'Largos de estribos':cub2,\n\n 'N° trabas laterales por estribo':nsH,\n 'N° estribos con traba lateral':numH,\n 'Largo trabas laterales':LestH\n }\n\n resVC={'phiVn1':phiVn1,\n 'fuV1':fuV1,\n 'phiVn2':phiVn2,\n 'fuV2':fuV2,\n }\n\n return Lout,salidaVC,resVC\n\n def optimusVig(mpp,mnn,es,eu,ey,b1,fc,fy,dp,dList,dimV,ai,lo,cH,cS,v,allVu,deList,wo,nbahias,hcol):\n lo-=hcol/100\n di = round((ai*200/3.1416)**0.5,1)\n mnn=abs(mnn)\n salida=0\n minim = 999999999\n hmax = dimV[0] if dimV[0]>=30 else 30\n bmax = dimV[1] if dimV[1]>=25 else 25\n hmin = dimV[2] if dimV[2]>=30 else 30\n bmin = dimV[3] if dimV[3]>=25 else 25\n hList = [i for i in range(hmin, hmax+5,5)]\n bList = [i for i in range(bmin, bmax+5,5)]\n lista = ([i, j] for i in hList if i >= 100*lo/16 for j in bList if i >= j and j >= 0.4*i)\n for h, b in lista:\n A1 = areaV(mpp, b, b1, h, fc, fy, dp)\n # print(A1)\n A2 = areaV(mnn, b, b1, h, fc, fy, dp)\n # print(A2)\n L1 = listadiam(A1, b, dp, h, dList, v)\n if L1==[]:\n continue\n L2 = listadiam1(A2, b, dp, h, dList, v)\n mi1 = 10*A2\n lis=[]\n for i in range(len(L2)):\n L=L2[i]\n if L[4]0 else 99\n ,L1[0][3] if L1[0][3]>0 else 99\n ,lis[1] if lis[1]>0 else 99\n ,lis[3] if lis[3]>0 else 99])\n sup=L1[0]\n xlistV = xLst(sup, 30, 5)[1]\n FU = round(max(mnn / cpn[1], mpp / cpnrev[1]) * 100, 1)\n if 0.025 >= cuan1 >= cumin and 0.025 >= cuan2 >= cumin\\\n and cpn[1] >= mnn and cpnrev[1] >= mpp and 85<=FU<=95:\n cond = True\n corte1 = minEstV(mpr1, mpr2, allVu[0], allVu[1], allVu[2], allVu[3], xlistV, deList, db, h, b, lo, dp,\n fy, fc, cS, wo, ylst,hcol,traslp1,traslp4)\n costoHF = (h * b) * nbahias * cH / 10000\n costoVC = corte1[0][0]*nbahias\n costoVF = (volSup + volBar) * cS / 1000000\n costo = round(costoHF+costoVC+costoVF, 0)\n if costo < minim and cond != False:\n minim = costo\n hormVF=round(costoHF/cH)\n aceroVF=round(costoVF/cS*7850)\n aceroVC=round(costoVC/cS*7850)\n FU = round(max(mnn/cpn[1], mpp/cpnrev[1])*100, 1)\n corte=corte1[0]\n salidaC=corte1[1:]\n listaT = [minim, h, b, aSLst, ylst, cuan1, cuan2, ylstrev, alstrev,c , round(abs(mnn),2),\n round(abs(mpp),2), L1, lis, cpn[1], cpnrev[1], max(cpn[1],cpnrev[1]), lo, FU, lDetail, xlistV]\n salida = 1\n if salida == 1:\n salidaVF = {'Largo libre':lo,\n 'Alto':h,\n 'Ancho':b,\n\n 'Lista de posiciones':ylst,\n 'Lista de Areas':aSLst,\n\n 'N° barras tipo 1 nivel 1':L1[0][0],\n 'Diametro barras tipo 1 nivel 1':L1[0][1],\n 'N° barras tipo 2 nivel 1': L1[0][2],\n 'Diametro barras tipo 2 nivel 1': L1[0][3],\n 'N° barras tipo 1 nivel 2': L1[1][0],\n 'Diametro barras tipo 1 nivel 2': L1[1][1],\n 'N° barras tipo 2 nivel 2': L1[1][2],\n 'Diametro barras tipo 2 nivel 2': L1[1][3],\n 'Cuantia superior': cuan1,\n\n 'Diametro barras laterales':di,\n 'N° de niveles laterales':len(aSLst)-3,\n\n 'N° barras tipo 1 nivel 4':lis[0],\n 'Diametro barras tipo 1 nivel 4':lis[1],\n 'N° barras tipo 2 nivel 4': lis[2],\n 'Diametro barras tipo 2 nivel 4': lis[3],\n 'Cuantia inferior':cuan2,\n\n 'Longitud de traslapo superior':traslp1,\n 'Desarrollo de gancho superior':ldh1,\n 'Gancho superior':gancho1,\n 'db superior':db,\n '12db superior':round(1.2*db,1),\n\n 'Longitud de traslapo suple': traslp2,\n 'Desarrollo de gancho suple': ldh2,\n 'Gancho': gancho2,\n 'db': db2,\n '12db': round(1.2 * db2,1),\n 'Largo suple esquina':suple1,\n 'Largo suple intermedio':suple2,\n 'Ancho cruce columna':hcol,\n\n 'Longitud de traslapo superior':traslp3,\n 'Desarrollo de gancho superior':ldh3,\n 'Gancho superior':gancho3,\n 'db superior':db3,\n '12db superior':round(1.2*db3,1),\n\n 'Longitud de traslapo superior': traslp4,\n 'Desarrollo de gancho superior': ldh4,\n 'Gancho superior': gancho4,\n 'db superior': db4,\n '12db superior': round(1.2 * db4,1),\n }\n resVF = { 'Mpp':cpn[1],\n 'Mnn':cpnrev[1],\n 'FU':FU,\n 'Volumen hormigon':hormVF,\n 'Peso acero longitudinal':aceroVF,\n 'Peso acero transversal':aceroVC\n }\n\n salidaV={}\n salidaV.update(salidaVF)\n salidaV.update(salidaC[0])\n salidaV.update(salidaC[1])\n salidaV.update(resVF)\n salidaVlist = list(salidaV.keys())\n\n\n return [listaT, corte, salidaV]\n else:\n return 0\n\n def XYplotCurv(alst, b, h, dp, eu, fy, fc, b1, es, ey, ylst, ce, mu, pu, mn, pn, titulo):\n PnMax = round((0.85*fc*(h*b-sum(alst))+sum(alst)*fy)/1000, 2)\n PnMaxPr = round(PnMax+sum(alst)*fy*0.25/1000, 2)\n PnMin = sum(alst)*-fy/1000\n phiPnMin = 0.9*sum(alst)*-fy/1000\n PnMinPr = 1.25*sum(alst)*-fy/1000\n C = [0]+[i/50*h for i in range(2, 51)]\n X1 = [0]\n X2 = [0]\n X3 = [0]\n Y1 = [phiPnMin]\n Y2 = [PnMin]\n Y3 = [PnMinPr]\n for c in C[1::]:\n res = resumen(alst, c, b, dp, h, eu, fy, fc, b1, es, ey, ylst)\n X1.append(res[3])\n Y1.append(res[0])\n X2.append(res[4])\n Y2.append(res[1])\n X3.append(res[5])\n Y3.append(res[2])\n X1.append(0)\n X2.append(0)\n X3.append(0)\n Y1.append(Y1[-1])\n Y2.append(PnMax)\n Y3.append(PnMaxPr)\n fig = pete.figure(figsize=[4,6], dpi=200)\n pete.plot(X1, Y1, label='ØMn - ØPn', color='steelblue')\n pete.plot(X2, Y2, label='Mn - Pn', color='crimson')\n pete.plot(X3, Y3, label='Mpr - Ppr', color='forestgreen')\n pete.plot([mu], [pu], marker='x', markersize=10, color='red', label='Mu - Pu', lw='1')\n res1 = resumen(alst, ce, b, dp, h, eu, fy, fc, b1, es, ey, ylst)\n pete.plot([0, mu], [0, pu], ls='--', color='black')\n # pete.plot([mu, mn], [pu, pn], ls='--', color='gray')\n pete.xlabel('Mn[tonf-m]')\n pete.xlim([0, max(X3)+0.1])\n pete.ylabel('Pn[tonf]')\n pete.title(titulo)\n pete.legend()\n pete.grid()\n # pete.show()\n pete.close()\n fig.savefig( proyecto + '/src/' + titulo)\n return 0\n\n def dimv(hmax,bmax,hmin,bmin,npisos,nbahias):\n return [[[hmax,bmax,hmin,bmin]for i in range(nbahias)]for j in range(npisos)]\n\n def matElemV(lista, cH, cS, b1, dp, es, ey, eu, fc, fy, dList, ai, deList, v, nbahias, dimC):\n #se itera en la lista\n listaV = []\n for i in range(len(lista)):\n # se filtra la lista por piso\n tempV=[]\n for j in range(len(lista[0])):\n\n ultimo = 1 if i == len(lista)-1 else 0\n elem = optimusVig(lista[i][j][0],lista[i][j][1],es,eu,ey,b1,fc,fy,dp,dList,\n lista[i][j][5],ai,lista[i][j][3],cH,cS,v,lista[i][j][4],\n deList,lista[i][j][2],nbahias,dimC[i][1][0])\n cont=0\n while elem == 0 and cont<10:\n cont+=1\n lista[i][j][0]=lista[i][j][0]*1.1\n lista[i][j][1]=lista[i][j][1]*1.1\n elem = optimusVig(lista[i][j][0], lista[i][j][1], es, eu, ey, b1, fc, fy, dp, dList,\n lista[i][j][5], ai, lista[i][j][3], cH, cS, v, lista[i][j][4], deList,\n lista[i][j][2],nbahias,dimC[i][1][0])\n tempV.append(elem)\n listaV.append(tempV)\n return listaV\n\n def detVig(detvig, nbahias, hCol):\n # agregar lista de barras horizontales\n RUGodV = open(proyecto + '/tmp/detViga.txt', 'w', encoding='utf-8')\n di = 12\n ai = 2.26\n contv = 0\n npisos=len(detvig)\n #print(\"Reporte de diseño y cubicación de la estructura\")\n RUGodV.write(\"Reporte de diseño y cubicación de la estructura\")\n\n #print(\"\\ncantidad pisos\",npisos)\n RUGodV.write(\"\\ncantidad pisos \" + str(npisos))\n \n #print(\"cantidad vigas tipo por piso\",len(detvig[0]), \"\\n\\n\")\n RUGodV.write(\"cantidad vigas tipo por piso \" + str(len(detvig[0])) + \"\\n\\n\")\n\n acum=0\n\n salvig = []\n for i in detvig:\n\n tempvig=[]\n for j in i:\n hcol=hCol[contv][0]\n\n \"\"\" Identificador \"\"\"\n\n contv+=1\n tempvig.append(contv)\n #print(\"Viga n° \",contv)\n RUGodV.write(f\"Viga n° {contv}\")\n\n #print(\"Viga tipo del piso\", contv,\"\\n\\n\")\n RUGodV.write(f\"Viga tipo del piso {contv},\\n\\n\")\n\n\n \"\"\"Dimensiones\"\"\"\n\n #print(\"Dimensiones\\n\")\n RUGodV.write(\"Dimensiones\\n\")\n\n #print(\"Largo : \", j[0][17], \"[m]\")\n RUGodV.write(f\"Largo : {j[0][17]} [m]\")\n\n tempvig.append(j[0][17]-hCol[contv][0])\n #print(\"Alto : \",j[0][1], \"[cm]\")\n RUGodV.write(f\"Alto : {j[0][1]} [cm]\")\n\n tempvig.append(j[0][1])\n #print(\"Ancho : \",j[0][2], \"[cm]\\n\")\n RUGodV.write(f\"Ancho : {j[0][2]} [cm]\\n\")\n\n tempvig.append(j[0][2])\n\n \"\"\"Refuerzo longitudinal\"\"\"\n\n #print(\"Refuerzo longitudinal\\n\")\n RUGodV.write(\"Refuerzo longitudinal\\n\")\n\n #print(\"Armadura superior principal\")\n RUGodV.write(\"Armadura superior principal\")\n\n numB2=\" barras\" if j[0][12][0][2]>1 else \" barra\"\n barr2 = \"\" if j[0][12][0][2]==0 else \", \"+str(j[0][12][0][2])+str(numB2)+\" Ø \"+\\\n str(j[0][12][0][3])+\"[mm] en la posición y = \"+\\\n str(j[0][4][0])+\" [cm], área = \"+str(j[0][3][0])+\" [cm2]\"\n #print(j[0][12][0][0],\"barras Ø\",j[0][12][0][1],\"[cm]\",barr2)\n RUGodV.write(f\"{j[0][12][0][0]}\" + \"barras Ø\" + f\"{j[0][12][0][1]}\" + \"[cm]\" +f\"{barr2}\")\n\n\n #print(\"\\nArmadura suplementaria\")\n RUGodV.write(\"\\nArmadura suplementaria\")\n\n numB3 = \" barras\" if j[0][12][0][2] > 1 else \" barra\"\n barr3 = \"\" if j[0][12][1][2] == 0 else \", \" + str(j[0][12][1][2])+str(numB3)+\\\n \" Ø \"+str(j[0][12][1][3])+\"[mm] en la posición y = \"+\\\n str(j[0][4][1])+\" [cm], área = \"+str(j[0][3][1])+\" [cm2]\"\n #print(j[0][12][1][0], \"barras Ø\", j[0][12][1][1],\"[cm]\",barr3)\n RUGodV.write(f\"{j[0][12][1][0]}\" + \"barras Ø\" + f\"{j[0][12][1][1]} [cm] {barr3}\")\n\n if len(j[0][3])>3:\n #print(\"\\nArmadura lateral\")\n RUGodV.write(\"\\nArmadura lateral\")\n\n for i in range(len(j[0][3])-3, len(j[0][3])-1):\n #print(\"2 barras Ø\",di,\"[mm] en la posición y = \",j[0][4][i],\"cm, área = \",ai,\"[cm2]\")\n RUGodV.write(\"2 barras Ø\" + f\"{di}\" + \"[mm] en la posición y = \" + f\"{j[0][4][i]}\" + \"cm, área = \" + f\"{ai} [cm2]\")\n\n #print(\"\\nArmadura inferior principal\")\n RUGodV.write(\"\\nArmadura inferior principal\")\n\n numB4 = \" barras\" if j[0][13][2] > 1 else \" barra\"\n barr4 = \"\" if j[0][13][2] == 0 else \", \" + str(j[0][13][2])+str(numB3)+\" Ø \"+str(j[0][13][3])+\\\n \"[mm] en la posición y = \"+str(j[0][4][-1])+\" [cm], área = \"+\\\n str(j[0][3][-1])+\" [cm2]\"\n #print(f\"{j[0][13][0]} barras Ø {j[0][13][1]} [cm] {barr4}\\n\")\n RUGodV.write(f\"{j[0][13][0]} barras Ø {j[0][13][1]} [cm] {barr4}\\n\")\n\n\n\n \"\"\"Cuantías\"\"\"\n\n #print(\"\\nCuantías\")\n RUGodV.write(\"\\nCuantías\")\n\n #print(\"Superior = \",j[0][5])\n RUGodV.write(\"Superior = \" + f\"{j[0][5]}\")\n\n #print(\"Inferior = \",j[0][6],\"\\n\")\n RUGodV.write(f\"Inferior = {j[0][6]}\\n\")\n\n\n det=j[0][19]\n\n #print(\"Cubicación de acero en barras longitudinales.\\n\")\n RUGodV.write(\"Cubicación de acero en barras longitudinales.\\n\")\n\n\n #print(\"Largos de suples : \")\n RUGodV.write(\"Largos de suples : \")\n\n\n #print(\"0.25lo : \", round(det[4][0],1),\"[cm]\")\n RUGodV.write(f\"0.25lo : {round(det[4][0],1)} [cm]\")\n\n #print(\"0.3lo : \",round(det[4][1],1),\"[cm]\")\n RUGodV.write(f\"0.3lo : {round(det[4][1],1)} [cm]\")\n\n #print(\"kg de barras de suples : \",round(det[4][2]*0.007850,1) ,\"[kg]\")\n RUGodV.write(\"kg de barras de suples : \" + f\"{round(det[4][2]*0.007850,1)}\" + \"[kg]\")\n\n #print(\"kg de otras barras : \", round(det[4][3] * 0.007850,1), \"[kg]\\n\")\n RUGodV.write(\"kg de otras barras : \" f\"{round(det[4][3] * 0.007850,1)}\" + \"[kg]\\n\")\n\n vHorm=j[0][1]*j[0][2]*nbahias*(j[0][17])/10000\n #print(\"Volumen de hormigón : \", vHorm,\"[m3]\\n\")\n RUGodV.write(\"Volumen de hormigón : \" + f\"{vHorm}\" + \"[m3]\\n\")\n\n cAc=round(det[4][2]*0.007850+det[4][3] * 0.007850,1)*1000\n #print(\"Costo de acero: $\",cAc)\n RUGodV.write(f\"Costo de acero: $ {cAc}\")\n\n cHorm=75000 * j[0][1] * j[0][2] * nbahias * (j[0][17]) / 10000\n #print(\"Costo de hormigón : $\", cHorm,\"\\n\")\n RUGodV.write(\"\\nCosto de hormigón : $\" + f\"{cHorm}\" + \"\\n\")\n\n\n # rem = 0 if contv < npisos else round(j[0][25]-j[0][21],1)\n\n #print(\"Barras superiores : \\n\")\n RUGodV.write(\"Barras superiores : \\n\")\n\n\n #print(\"Longitud de traslapo de armadura superior : \",det[0][3],\"[cm]\")\n RUGodV.write(\"Longitud de traslapo de armadura superior : \" + f\"{det[0][3]}\" + \"[cm]\")\n\n #print(\"Desarrollo de gancho : \",det[0][4],\"[cm]\")\n RUGodV.write(\"Desarrollo de gancho : \" + f\"{det[0][4]}\" + \"[cm]\")\n\n #print(\"Gancho : \", det[0][2], \"[cm]\")\n RUGodV.write(\"Gancho : \" + f\"{det[0][2]}\" + \"[cm]\")\n\n #print(\"Diámetro : \", det[0][0], \"[mm]\")\n RUGodV.write(\"Diámetro : \" + f\"{det[0][0]}\" + \"[mm]\")\n\n #print(\"12db : \", round(det[0][1],1), \"[cm]\\n\")\n RUGodV.write(\"12db : \" + f\"{round(det[0][1],1)}\" + \"[cm]\\n\")\n\n\n #print(\"Barras suplementarias : \\n\")\n RUGodV.write(\"Barras suplementarias : \\n\")\n\n\n\n #print(\"Desarrollo de gancho : \", det[1][4], \"[cm]\")\n RUGodV.write(\"Desarrollo de gancho : \" + f\"{det[1][4]}\" + \"[cm]\")\n\n #print(\"Gancho : \", det[1][2], \"[cm]\")\n RUGodV.write(\"Gancho : \" + f\"{det[1][2]}\" + \"[cm]\")\n\n #print(\"Diámetro : \", det[1][0], \"[mm]\")\n RUGodV.write(\"Diámetro : \" + f\"{det[1][0]}\" + \"[mm]\")\n\n #print(\"12db : \", round(det[1][1],1), \"[cm]\\n\")\n RUGodV.write(\"12db : \" + f\"{round(det[1][1],1)}\" + \"[cm]\\n\")\n\n\n #print(\"Barras laterales : \\n\")\n RUGodV.write(\"Barras laterales : \\n\")\n\n\n #print(\"Longitud de traslapo de armadura lateral : \", det[2][3], \"[cm]\")\n RUGodV.write(\"Longitud de traslapo de armadura lateral : \" + f\"{det[2][3]}\" + \"[cm]\")\n\n #print(\"Desarrollo de gancho : \", det[2][4], \"[cm]\")\n RUGodV.write(\"Desarrollo de gancho : \" + f\"{det[2][4]}\" + \"[cm]\")\n\n #print(\"Gancho : \", det[2][2], \"[cm]\")\n RUGodV.write(\"Gancho : \" + f\"{det[2][2]}\" + \"[cm]\")\n\n #print(\"Diámetro : \", det[2][0], \"[mm]\")\n RUGodV.write(\"Diámetro : \" + f\"{det[2][0]}\" + \"[mm]\")\n\n #print(\"12db : \", round(det[2][1],1), \"[cm]\\n\")\n RUGodV.write(\"12db : \" + f\"{round(det[2][1],1)}\" + \"[cm]\\n\")\n\n\n #print(\"Barras inferiores : \\n\")\n RUGodV.write(\"Barras inferiores : \\n\")\n\n\n #print(\"Longitud de traslapo de armadura inferior : \", det[3][3], \"[cm]\")\n RUGodV.write(\"Longitud de traslapo de armadura inferior : \" + f\"{det[3][3]}\" + \"[cm]\")\n\n #print(\"Desarrollo de gancho : \", det[3][4], \"[cm]\")\n RUGodV.write(\"Desarrollo de gancho : \" + f\"{det[3][4]}\" + \"[cm]\")\n\n #print(\"Gancho : \", det[3][2], \"[cm]\")\n RUGodV.write(\"Gancho : \" + f\"{det[3][2]}\" + \"[cm]\")\n\n #print(\"Diámetro : \", det[3][0], \"[mm]\")\n RUGodV.write(\"Diámetro : \" + f\"{det[3][0]}\" + \"[mm]\")\n\n #print(\"12db : \", round(det[3][1],1), \"[cm]\\n\")\n RUGodV.write(\"12db : \" + f\"{round(det[3][1],1)}\" + \"[cm]\\n\")\n\n\n \"\"\"Refuerzo transversal\"\"\"\n\n #print(\"Refuerzo transversal\")\n RUGodV.write(\"Refuerzo transversal\")\n\n #print(\"\\nZonas de rótula plástica, de 0 a\",j[1][1],\"[cm] y \",j[0][17]*100-j[1][1],\"a\",j[0][17]*100,\"[cm]:\")\n RUGodV.write(f\"\\nZonas de rótula plástica, de 0 a {j[1][1]} [cm] y {j[0][17]*100-j[1][1]} a {j[0][17]*100} [cm]:\")\n\n #print(\"Diámetro : \",j[1][9],\"[cm]\")\n RUGodV.write(f\"Diámetro : {j[1][9]} [cm]\")\n\n #print(\"N° ramas : \",j[1][2])\n RUGodV.write(f\"N° ramas : {j[1][2]}\")\n\n cont=0\n #print(\"Estribos =\",len(j[1][12][1]))\n RUGodV.write(f\"Estribos = {len(j[1][12][1])}\")\n\n\n #guardar\n for i in j[1][12][1]:\n cont+=1\n #print(\"Largo de estribo n°\",cont,\"=\",i,\"[cm]\")\n RUGodV.write(f\"Largo de estribo n° {cont} = {i} [cm]\")\n\n if j[1][12][2]!=[]:\n #print(\"Traba central: si\")\n RUGodV.write(\"Traba central: si\")\n\n #print(\"Largo de traba =\",j[1][12][2][0],\"[cm]\")\n RUGodV.write(f\"Largo de traba = {j[1][12][2][0]} [cm]\")\n\n else:\n #print(\"Traba central: no\")\n RUGodV.write(\"Traba central: no\")\n\n #guardar\n\n #print(\"Espaciamiento : \",j[1][3],\"[cm]\")\n RUGodV.write(f\"Espaciamiento : {j[1][3]} [cm]\")\n\n #print(\"N° estribos : \",int(round(j[1][4]/2,0)),\" en cada extremo\")\n RUGodV.write(f\"N° estribos : {int(round(j[1][4]/2,0))} en cada extremo\")\n\n # vol1t=\n #print(\"Volumen de acero en zona de rótulas plásticas : \", round(j[1][12][0]*j[1][4],1),\"[cm3]\")\n RUGodV.write(f\"Volumen de acero en zona de rótulas plásticas : {round(j[1][12][0]*j[1][4],1)} [cm3]\")\n\n p1=round(j[1][12][0]*j[1][4]*0.00785,1)\n #print(\"Peso del acero\", p1,\"[kg]\\n\")\n RUGodV.write(f\"Peso del acero {p1} [kg]\\n\")\n\n\n #print(\"\\nZonas central, de \",j[1][1],\"a\",j[0][17]*100-j[1][1],\"[cm]:\")\n RUGodV.write(f\"\\nZonas central, de {j[1][1]} a {j[0][17]*100-j[1][1]} [cm]:\")\n\n #print(\"Diámetro : \", j[1][9], \"[cm]\")\n RUGodV.write(f\"Diámetro : {j[1][9]} [cm]\")\n\n #print(\"N° ramas : \", j[1][6])\n RUGodV.write(f\"N° ramas : {j[1][6]}\")\n\n #print(\"longitud de empalme barras inferiores : \",j[1][18],\"[cm]\")\n RUGodV.write(f\"longitud de empalme barras inferiores : {j[1][18]} [cm]\")\n\n #print(\"longitud de empalme barras superiores : \",j[1][19],\"[cm]\")\n RUGodV.write(f\"longitud de empalme barras superiores : {j[1][19]} [cm]\")\n\n #print(\"espaciamiento normal :\",j[1][7],\"[cm]\")\n RUGodV.write(f\"espaciamiento normal : {j[1][7]} [cm]\")\n\n #print(\"espaciamiento zona de empalme : 10[cm]\")\n RUGodV.write(\"espaciamiento zona de empalme : 10[cm]\")\n\n\n cont=0\n for i in j[1][13][1]:\n cont+=1\n #print(\"Largo de estribo n°\",cont,\"=\",i,\"[cm]\")\n RUGodV.write(f\"Largo de estribo n° {cont} = {i} [cm]\")\n\n if j[1][13][2]!=[]:\n #print(\"Traba central: si\")\n RUGodV.write(\"Traba central: si\")\n\n #print(\"Largo de traba =\",j[1][13][2][0],\"[cm]\")\n RUGodV.write(f\"Largo de traba = {j[1][13][2][0]} [cm]\")\n\n else:\n #print(\"Traba central: no\")\n RUGodV.write(\"Traba central: no\")\n\n #print(\"Espaciamiento : \", j[1][7],\"[cm]\")\n RUGodV.write(f\"Espaciamiento : {j[1][7]} [cm]\")\n\n #print(\"N° estribos : \", j[1][8])\n RUGodV.write(f\"N° estribos : {j[1][8]}\")\n\n #print(\"Volumen de acero en zona central : \", round(j[1][13][0] * j[1][8],1) , \"[cm3]\")\n RUGodV.write(f\"Volumen de acero en zona central : {round(j[1][13][0] * j[1][8],1)} [cm3]\")\n\n p2=round(j[1][12][0] * j[1][8] * 0.00785,1)\n #print(\"Peso del acero\", p2,\"[kg]\\n\")\n RUGodV.write(\"Peso del acero\" + f\"{p2}\" +\"[kg]\\n\")\n\n\n #print(\"Trabas Horizontales\")\n RUGodV.write(\"Trabas Horizontales\")\n\n #print(\"N° Trabas por estribo = \",j[1][15])\n RUGodV.write(f\"N° Trabas por estribo = {j[1][15]}\")\n\n #print(\"N° de estribos donde va traba = \",j[1][14])\n RUGodV.write(f\"N° de estribos donde va traba = {j[1][14]}\")\n\n #print(\"Largo trabas = \",j[1][16],\"[cm]\")\n RUGodV.write(f\"Largo trabas = {j[1][16]} [cm]\")\n\n #print(\"Volumen de acero en trabas horizontales : \", round(j[1][15]*j[1][14]*j[1][16]*ai*0.5,1), \"[cm3]\")\n RUGodV.write(f\"Volumen de acero en trabas horizontales : {round(j[1][15]*j[1][14]*j[1][16]*ai*0.5,1)} [cm3]\")\n\n p3=round(j[1][15]*j[1][14]*j[1][16]*ai*0.5*0.00785,1)\n #print(\"Peso del acero : \", p3,\"[kg]\\n\")\n RUGodV.write(f\"Peso del acero : {p3} [kg]\\n\")\n\n\n #print(\"Acero total : \",round(p1+p2+p3,1),\"[kg]\")\n RUGodV.write(f\"Acero total : {round(p1+p2+p3,1)} [kg]\")\n\n #print(\"Hormigón total : \",round(vHorm,2),\"[m3]\")\n RUGodV.write(f\"Hormigón total : {round(vHorm,2)} [m3]\")\n\n #print(\"Costo hormigón : $\", cHorm)\n RUGodV.write(f\"Costo hormigón : $ {cHorm}\")\n\n #print(\"Costo acero : $\", cAc+(p1+p2+p3)*1000)\n RUGodV.write(f\"Costo acero : $ {cAc+(p1+p2+p3)*1000}\")\n\n #print(\"Costo total de vigas por piso : $\",cAc+(p1+p2+p3)*1000+cHorm)\n RUGodV.write(f\"Costo total de vigas por piso : $ {cAc+(p1+p2+p3)*1000+cHorm}\")\n\n acum+=cAc+(p1+p2+p3)*1000+cHorm\n\n \"\"\"Resultados\"\"\"\n\n #print(\"Resultados del análisis\\n\")\n RUGodV.write(\"Resultados del análisis\\n\")\n\n #print(\"Flexión\")\n RUGodV.write(\"Flexión\")\n\n #print(\"ØMn+ = \", j[0][15], \"[tf-m]\")\n RUGodV.write(f\"ØMn+ = {j[0][15]} [tf-m]\")\n\n #print(\"ØMn- = \", -j[0][14], \"[tf-m]\")\n RUGodV.write(f\"ØMn- = {-j[0][14]} [tf-m]\")\n\n #print(\"F.U. mayor = \", j[0][18], \"%\\n\")\n RUGodV.write(f\"F.U. mayor = {j[0][18]} %\\n\")\n\n\n #print(\"Corte\")\n RUGodV.write(\"Corte\")\n\n phiVn1 = round(aCir(j[1][9])*j[1][2]*fy*(j[0][1]-dp)/j[1][3],1)\n #print(\"ØVn1 = \",round(phiVn1/1000,1), \"[tf]\")\n RUGodV.write(f\"ØVn1 = {round(phiVn1/1000,1)} [tf]\")\n\n fuV1 = round(100*j[1][10]/(phiVn1),1)\n #print(\"F.U.1 = \",fuV1, \"%\")\n RUGodV.write(f\"F.U.1 = {fuV1} %\")\n\n phiVn2 = round(aCir(j[1][9])*j[1][6]*fy*(j[0][1]-dp)/j[1][7], 1)\n #print(\"ØVn2 = \",round(phiVn2/1000,1), \"[tf]\")\n RUGodV.write(f\"ØVn2 = {round(phiVn2/1000,1)} [tf]\")\n\n fuV2 = round(100*j[1][11]/phiVn2,1)\n #print(\"F.U.2 = \",fuV2,\"%\\n\")\n RUGodV.write(f\"F.U.2 = {fuV2} %\\n\")\n\n #print(\"\\n\")\n RUGodV.write(\"\\n\")\n RUGodV.close()\n return acum\n\n def detCol(detcol):\n\n print(\"\\nNota: todas las columnas son simétricas, por lo tanto, su ancho y alto es igual.\")\n print(\"Por otro lado, las trabas y/o estribos interiores perpendiculares al eje x se replican al eje y\")\n cont = 0\n npisos = len(detcol)\n ncol = len(detcol[0])\n acum=0\n\n for i in detcol:\n for j in i:\n\n \"\"\" Identificador \"\"\"\n\n cont+=1\n piso=npisos if cont%npisos==0 else cont%npisos\n tipo = 2 if cont>nbahias+1 else 1\n print(\"Columna\")\n print(\"\\n\\nPiso N°\",piso)\n\n clasecol = \"externa\" if tipo == 1 else \"interna\"\n print(\"Tipo :\",clasecol,\"\\n\\n\")\n\n \"\"\"Dimensiones\"\"\"\n\n print(\"Dimensiones\\n\")\n print(\"Largo : \", j[0][20], \"[m]\")\n print(\"Alto : \",j[0][1], \"[cm]\")\n print(\"Ancho : \",j[0][2], \"[cm]\\n\")\n\n \"\"\"Refuerzo longitudinal\"\"\"\n\n print(\"Refuerzo longitudinal\\n\")\n list = []\n if j[0][21]!=1:\n print(\"Armadura superior\")\n if j[0][3]>0:\n print(\"2 barras Ø\",j[0][5],\"[mm] y\",j[0][3],\"barras Ø\",j[0][6],\"[mm] en la posición y =\",j[0][14][0],\n \"[cm], área =\",j[0][13][0],\"[cm2]\")\n else:\n print(\"2 barras Ø\",j[0][5],\"[mm] en la posición y =\",j[0][14][0],\"[cm], área =\",j[0][13][0],\"[cm2]\")\n else:\n print(2+j[0][3],\"barras Ø\",j[0][5],\"[mm] en la posición y =\",j[0][14][0],\"[cm], área =\",j[0][13][0],\"[cm2]\")\n if j[0][4]>0:\n for i in range(j[0][4]):\n print(\"2 barras Ø\",j[0][6],\"[mm] en la posición y =\",j[0][14][i+1],\"[cm], área =\",j[0][13][i+1],\"[cm2]\")\n if j[0][21]!=1:\n print(\"Armadura superior\")\n if j[0][3]>0:\n print(\"2 barras Ø\",j[0][5],\"[mm] y\",j[0][3],\"barras Ø\",j[0][6],\n \"[mm] en la posición y =\",j[0][14][-1],\"[cm], área =\",j[0][13][-1],\"[cm2]\")\n else:\n print(\"2 barras Ø\",j[0][5],\"[mm] en la posición y =\",j[0][14][-1],\"[cm], área =\",j[0][13][-1],\"[cm2]\")\n else:\n print(2+j[0][3],\"barras Ø\",j[0][5],\"[mm] en la posición y =\",j[0][14][-1],\"[cm], área =\",j[0][13][-1],\"[cm2]\")\n\n\n \"\"\"Cuantía\"\"\"\n\n print(\"\\nCuantía = \",j[0][9],\"\\n\\n\")\n\n \"\"\"Uniones y remates\"\"\"\n print(\"Uniones y remates\\n\")\n\n if piso!=npisos and piso>1:\n if cont>npisos:\n print(\"Columna para zonas centrales\\n\")\n print(\"Para unión superior\\n\")\n ldc = ldC(fy, fc, j[0][5])\n print(\"Longitud de empalme unión viga-columna = \", ldc, \"cm\\n\")\n print(\"Para unión inferior\\n\")\n print(\"Longitud de gancho-remate = \", lG, \"[cm]\")\n ldc = ldC(fy, fc, j[0][5])\n else:\n print(\"Columna para zonas laterales\\n\")\n print(\"Para unión superior\\n\")\n ldc = ldC(fy, fc, j[0][5])\n print(\"Longitud de empalme unión viga-columna = \", ldc, \"[cm]\\n\")\n lG = lGanchoC(j[0][5], fc, fy, j[0][1], dp)\n print(\"Longitud de gancho-remate = \",lG,\"[cm]\")\n print(\"Para unión inferior\\n\")\n ldc = ldC(fy, fc, j[0][5])\n print(\"Longitud de empalme unión viga-columna = \", ldc, \"[cm]\\n\")\n\n elif piso==1:\n if cont>npisos:\n print(\"Columna para zonas centrales\\n\")\n print(\"Para unión superior\\n\")\n ldc = ldC(fy, fc, j[0][5])\n print(\"Longitud de empalme unión viga-columna = \", ldc, \"[cm]\\n\")\n\n else:\n print(\"Columna para zonas laterales\\n\")\n print(\"Para unión superior\\n\")\n ldc = ldC(fy, fc, j[0][5])\n print(\"Longitud de empalme unión viga-columna = \", ldc, \"[cm]\\n\")\n lG = lGanchoC(j[0][5], fc, fy, j[0][1], dp)\n print(\"Longitud de gancho-remate = \",lG,\"[cm]\")\n\n else:\n if cont>npisos:\n print(\"Columna para zonas centrales\\n\")\n print(\"Para unión superior\\n\")\n lG = lGanchoC(j[0][5], fc, fy, j[0][1], dp)\n print(\"Longitud de gancho-remate = \",lG,\"[cm]\")\n print(\"Para unión inferior\\n\")\n lG = lGanchoC(j[0][5], fc, fy, j[0][1], dp)\n print(\"Longitud de gancho-remate = \", lG, \"[cm]\")\n else:\n print(\"Columna para zonas laterales\\n\")\n print(\"Para unión superior\\n\")\n lG = lGanchoC(j[0][5], fc, fy, j[0][1], dp)\n print(\"Longitud de gancho-remate = \",lG,\"[cm]\")\n print(\"Para unión inferior\\n\")\n ldc = ldC(fy, fc, j[0][5])\n print(\"Longitud de empalme unión viga-columna = \", ldc, \"[cm]\\n\")\n\n # lista1 --> [costo0, n° ramas1, de_externo2, espaciamiento3, de_interno4, n° estribos5, largo16, largos27, largo_tot28, d_ramas9, dist10]\n # lista2 --> [costo, n° ramas, de_externo, espaciamiento, de_interno, n° estribos, largo1, largos2, largo_tot2, d_ramas, dist]\n # lista3 --> [costo, n° ramas, de_externo, espaciamiento, de_interno, n° estribos, largo1, largos2, largo_tot2, d_ramas, dist]\n\n\n \"\"\"Refuerzo transversal\"\"\"\n # return [lista1, lista2, lista3, costo_total, vu1, vu2, hvig]\n\n print(\"\\n\\nRefuerzo transversal\\n\")\n\n print(\"\\nZonas de rótula plástica y nodo\\n\")\n\n print(\"\\nUbicación de nodo y zona de RP superior: de\",j[1][7]['Ubicacion nodo y rotula1'][0] ,\"[cm] a \",j[1][7]['Ubicacion nodo y rotula1'][1],\"[cm]:\")\n print(\"\\nUbicación de zona de RP inferior: de\",j[1][7]['Ubicacion rotula2'][0],\"a\", j[1][7]['Ubicacion rotula2'][1], \"[cm]:\")\n print(\"N° ramas : \",j[1][0][1])\n print(\"N° de estribos rótulas : \",j[1][0][5])\n print(\"Espaciamiento : \",j[1][0][3],\"[cm]\")\n est1=int(j[1][6] / j[1][0][5]) + 1+j[1][0][5]\n print(\"N° Estribos nodo : \", int(j[1][6]/j[1][0][5])+1)\n print(\"\\nRefuerzo exterior\\n\")\n print(\"Diámetro estribo exterior: \",j[1][0][2],\"[cm]\")\n print(\"Largo del estribo exterior\",j[1][0][6],\"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\",j[1][0][9][0][0],\"[cm] y x =\",j[1][0][9][0][1],\"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\",j[1][0][9][0][0],\"[cm] e y =\",j[1][0][9][0][1],\"[cm]\")\n if j[1][0][1]>2:\n print(\"\\nRefuerzo interior\\n\")\n if j[1][0][1]%2!=0:\n print(\"Diámetro de estribos y trabas interiores\",j[1][0][4],\"[cm]\")\n if len(j[1][0][7])-1>0:\n for i in range(len(j[1][0][7])-1):\n print(\"Largo estribo interior n°\",i+1,\"=\",j[1][0][7][i],\"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][0][9][i+1][0], \"[cm] y x =\",\n j[1][0][9][i+1][1], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][0][9][0][0], \"[cm] e y =\",\n j[1][0][9][0][1], \"[cm]\")\n print(\"Largo de traba interior n°1 =\",j[1][0][7][-1],\"[cm]\")\n #Revisar\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][0][9][-1][0], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][0][9][0][0], \"[cm] e y =\",\n j[1][0][9][0][1], \"[cm]\")\n else:\n print(\"Diámetro de estribos interiores\",j[1][0][4],\"[cm]\")\n if len(j[1][0][7])-1>0:\n for i in range(len(j[1][0][7])-1):\n print(\"Largo estribo interior n°\",i+1,\"=\",j[1][0][7][i],\"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][0][9][i + 1][0], \"[cm] y x =\",\n j[1][0][9][i + 1][1], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][0][9][0][0], \"[cm] e y =\",\n j[1][0][9][0][1], \"[cm]\")\n print(\"Largo de estribo interior n°\", len(j[1][0][7]), \"=\", j[1][0][7][-1], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][0][9][-1][0], \"[cm] y x =\",\n j[1][0][9][-1][1], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][0][9][0][0], \"[cm] e y =\",\n j[1][0][9][0][1], \"[cm]\")\n\n\n\n\n \"\"\" asdfasdfasdf\"\"\"\n\n\n\n\n print(\"\\n\\nZona central\\n\")\n\n print(\"\\nUbicación superior:\", j[1][7]['Ubicacion zona libre superior'][0], \"[cm] -\", j[1][7]['Ubicacion zona libre superior'][1], \"[cm]\")\n print(\"\\nUbicación inferior:\", j[1][7]['Ubicacion zona libre inferior'][0], \"[cm] -\", j[1][7]['Ubicacion zona libre inferior'][1], \"[cm]\")\n print(\"N° ramas : \", j[1][1][1])\n print(\"N° de estribos por extremo: \", int(round((j[1][7]['Ubicacion zona libre superior'][1]-\n j[1][7]['Ubicacion zona libre superior'][0])\n / j[1][1][3], 0)))\n print(\"Espaciamiento : \", j[1][1][3], \"[cm]\")\n print(\"\\nRefuerzo exterior\\n\")\n print(\"Diámetro estribo exterior: \", j[1][1][2], \"[cm]\")\n print(\"Largo del estribo exterior\", j[1][1][6], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][1][9][0][0], \"[cm] y x =\",\n j[1][1][9][0][1],\n \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][1][9][0][0], \"[cm] e y =\",\n j[1][1][9][0][1],\n \"[cm]\")\n if j[1][1][1] > 2:\n print(\"\\nRefuerzo interior\\n\")\n if j[1][1][1] % 2 != 0:\n print(\"Diámetro de estribos y trabas interiores\", j[1][1][4], \"[cm]\")\n if len(j[1][1][7]) - 1 > 0:\n for i in range(len(j[1][1][7]) - 1):\n print(\"Largo estribo interior n°\", i + 1, \"=\", j[1][1][7][i], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][1][9][i + 1][0],\n \"[cm] y x =\",\n j[1][1][9][i + 1][1], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][1][9][0][0], \"[cm] e y =\",\n j[1][1][9][0][1], \"[cm]\")\n print(\"Largo de traba interior n°1 =\", j[1][1][7][-1], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][0][9][-1][0], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][1][9][0][0], \"[cm] e y =\",\n j[1][1][9][0][1], \"[cm]\")\n else:\n print(\"Diámetro de estribos interiores\", j[1][1][4], \"[cm]\")\n if len(j[1][1][7]) - 1 > 0:\n for i in range(len(j[1][1][7]) - 1):\n print(\"Largo estribo interior n°\", i + 1, \"=\", j[1][1][7][i], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][1][9][i + 1][0],\n \"[cm] y x =\",\n j[1][1][9][i + 1][1], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][1][9][0][0], \"[cm] e y =\",\n j[1][1][9][0][1], \"[cm]\")\n print(\"Largo de estribo interior n°\", len(j[1][1][7]), \"=\", j[1][1][7][-1], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][1][9][-1][0], \"[cm] y x =\",\n j[1][1][9][-1][1], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][1][9][0][0], \"[cm] e y =\",\n j[1][1][9][0][1], \"[cm]\")\n\n\n\n\n print(\"\\n\\nEmpalme central\\n\")\n\n print(\"\\nUbicación : de\", j[1][7]['Ubicación empalme:'][0], \"[cm] -\",\n j[1][7]['Ubicación empalme:'][1], \"[cm]\")\n distancia=j[1][7]['Ubicación empalme:'][0]-j[1][7]['Ubicación empalme:'][1]\n\n print(\"N° ramas : \", j[1][2][1])\n print(\"N° de estribos : \",int(distancia/j[1][2][3]))\n est2=int(distancia/j[1][2][3])\n print(\"Espaciamiento : \", j[1][2][3], \"[cm]\")\n print(\"\\nRefuerzo exterior\\n\")\n print(\"Diámetro estribo exterior: \", j[1][2][2], \"[cm]\")\n print(\"Largo del estribo exterior\", j[1][2][6], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][2][9][0][0], \"[cm] y x =\", j[1][2][9][0][1],\n \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][2][9][0][0], \"[cm] e y =\", j[1][2][9][0][1],\n \"[cm]\")\n if j[1][2][1] > 2:\n print(\"\\nRefuerzo interior\\n\")\n if j[1][2][1] % 2 != 0:\n print(\"Diámetro de estribos y trabas interiores\", j[1][2][4], \"[cm]\")\n if len(j[1][2][7]) - 1 > 0:\n for i in range(len(j[1][2][7]) - 1):\n print(\"\\nLargo estribo interior n°\", i + 1, \"=\", j[1][2][7][i], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][2][9][i+1][0], \"[cm] y x =\",\n j[1][2][9][i + 1][1], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][2][9][0][0], \"[cm] e y =\",\n j[1][2][9][0][1], \"[cm]\")\n print(\"\\nLargo de traba interior n°1 =\", j[1][2][7][-1], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][0][9][-1][0], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][2][9][0][0], \"[cm] e y =\",\n j[1][2][9][0][1], \"[cm]\")\n vol1 = (j[1][0][6] * aCir(j[1][0][2]) + sum(j[1][0][7])*2 * aCir(j[1][0][4]))*est2\n vol2 = (j[1][2][6] * aCir(j[1][2][2]) + sum(j[1][2][7])*2 * aCir(j[1][2][4]))*est2\n print(\"Peso total de estribos : \", round((vol1+vol2)*0.007850,1),\"[kg]\")\n print(\"Peso total barras longitudinales : \", round(sum(j[0][13])*(j[1][2][10]+j[0][20])*0.007850,1),\"[kg]\")\n acerT=round(((vol1+vol2)+sum(j[0][13])*(j[1][2][10]+j[0][20]*100))*0.00785,1)\n print(\"Volumen Hormigón : \", round(j[0][20]*j[0][1]*j[0][2]*0.0001,5),\"[m3]\")\n print(\"Costo acero : $\",round(acerT*1000,1))\n print(\"Costo hormigón : $\",j[0][20]*j[0][1]*j[0][2]*7.5)\n costoT=round(acerT*1000,1)+j[0][20]*j[0][1]*j[0][2]*7.5\n print(\"Costo total de columna tipo: $\",round(acerT*1000,1)+j[0][20]*j[0][1]*j[0][2]*7.5)\n\n else:\n print(\"Diámetro de estribos interiores\", j[1][2][4], \"[cm]\")\n if len(j[1][2][7]) - 1 > 0:\n for i in range(len(j[1][2][7]) - 1):\n print(\"\\nLargo estribo interior n°\", i + 1, \"=\", j[1][2][7][i], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][2][9][i+1][0], \"[cm] y x =\",\n j[1][2][9][i+1][1], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][2][9][0][0], \"[cm] e y =\",\n j[1][2][9][0][1], \"[cm]\")\n print(\"\\nLargo de estribo interior n°\", len(j[1][2][7]), \"=\", j[1][2][7][-1], \"[cm]\")\n print(\"Ubicación entre ejes de barras horizontales: x =\", j[1][0][9][-1][0], \"[cm]\")\n print(\"Ubicación entre ejes de barras verticales: y =\", j[1][2][9][0][0], \"[cm] e y =\",\n j[1][2][9][0][1], \"[cm]\")\n\n vol1 = (j[1][0][6] * aCir(j[1][0][2]) + sum(j[1][0][7])*2 * aCir(j[1][0][4]))*est2\n vol2 = (j[1][2][6] * aCir(j[1][2][2]) + sum(j[1][2][7])*2 * aCir(j[1][2][4]))*est2\n print(\"Peso total de estribos : \", round((vol1+vol2)*0.007850,1),\"[kg]\")\n print(\"Peso total barras longitudinales : \", round(sum(j[0][13])*(j[1][2][10]+j[0][20])*0.007850,1),\"[kg]\")\n acerT=round(((vol1+vol2)+sum(j[0][13])*(j[1][2][10]+j[0][20]*100))*0.00785,1)\n print(\"Volumen Hormigón : \", j[0][20]*j[0][1]*j[0][2]*0.0001,\"[m3]\")\n print(\"Costo acero : $\",round(acerT*1000,1))\n print(\"Costo hormigón : $\",j[0][20]*j[0][1]*j[0][2]*7.5)\n costoT=round(acerT*1000,1)+j[0][20]*j[0][1]*j[0][2]*7.5\n print(\"Costo total de columna tipo: $\",round(acerT*1000,1)+j[0][20]*j[0][1]*j[0][2]*7.5)\n\n\n \"\"\"Resultados\"\"\"\n\n print(\"\\n\\nResultados\\n\")\n print(\"Flexión\\n\")\n print(\"Mayor excentricidad\", round(j[0][22] * 100,1), \"cm\\n\")\n print(\"Momentos\\n\")\n print(\"Mu_max = \", j[0][17], \"[tf-m]\")\n print(\"Momento nominal ajustado a Mu y Pu máximos\")\n print(\"ØMn1 = \", j[0][15], \"[tf-m]\")\n print(\"Momento nominal ajustado a Mu máximo debido a mayor excentricidad:\")\n print(\"ØMn2 = \", j[0][23], \"[tf-m]\\n\")\n\n print(\"Cargas\\n\")\n print(\"Pu_max = \", j[0][18], \"[tf]\")\n print(\"Pu_min = \", j[0][19], \"[tf]\")\n print(\"Carga nominal que verifica Pu_max:\")\n print(\"ØPn1 = \", j[0][16], \"[tf]\")\n print(\"Carga nominal que verifica Pu_min:\")\n print(\"ØPn2 = \", j[0][24], \"[tf]\\n\")\n print(\"F.U. 1 = \", j[0][7], \"%\")\n print(\"F.U. 2 = \", j[0][8], \"%\\n\")\n\n print(\"Corte\")\n\n print(\"\\nCorte en zona de rótula plástica\")\n phiVn1 = round((2*aCir(j[1][0][2])+aCir(j[1][0][4])*(j[1][0][1]-2))*fy*(j[0][1]-j[0][27])/j[1][0][3],1)\n print(\"ØVn1 = \",round(phiVn1/1000,1), \"[tf]\")\n fuV1 = round(100*j[1][4]/(phiVn1),1)\n print(\"F.U.1 = \",fuV1, \"%\\n\")\n\n print(\"Corte en zona central\")\n phiVn2 = round((2*aCir(j[1][1][2])+aCir(j[1][1][4])*(j[1][1][1]-2))*fy*(j[0][1]-j[0][27])/j[1][1][3],1)\n print(\"ØVn2 = \",round(phiVn2/1000,1), \"[tf]\")\n fuV2 = round(100*j[1][5]/phiVn2,1)\n print(\"F.U.2 = \",fuV2,\"%\\n\")\n\n print(\"Corte en zona de empalme\")\n phiVn3 = round((2*aCir(j[1][2][2])+aCir(j[1][2][4])*(j[1][2][1]-2))*fy*(j[0][1]-j[0][27])/j[1][2][3],1)\n print(\"ØVn2 = \",round(phiVn3/1000,1), \"[tf]\")\n fuV3 = round(100*j[1][5]/phiVn3,1)\n print(\"F.U.2 = \",fuV3,\"%\\n\")\n print(\"\\n\")\n tempa=costoT*2 if tipo==1 else costoT*(nbahias-1)\n acum+=tempa\n return acum\n\n def max_ind(lista,ind):\n temp=[]\n for i in range(len(lista)):\n maxim=0\n for j in range(len(lista[0])):\n if lista[i][j][ind]>maxim:\n maxim=lista[i][j][ind]\n list1=lista[i][j]\n temp.append(list1)\n return temp\n\n def optimusFrame(tabla, largosC, largosV, dimV, cH, cS, b1, dp, es, ey, eu, fc, fy, dList,\n deList, hColMax, hColMin):\n ai=2.26\n dList=[16,18,22,25,28,32,36]\n deList=[10,12]\n combis = 7\n combi_e = 4\n combi_s = 3\n tab = tabla\n filtro=filtroCV(combis, combi_e, combi_s, tab, largosV, largosC)\n listaV=filtro[0]\n listaC=filtro[1]\n exc_col=filtro[2]\n mpp1=[max([max([max(listaV[i][j][0][2], listaV[i][j][1][2]) for j in range(len(listaV[0]))])\n for k in range(len(listaV[0][0]))]) for i in range(len(listaV))]\n mpp2=[[mpp1[j] for i in range(len(listaV[0]))] for j in range(len(listaV))]\n mpp3=[max(listaV[i][0][0][2], listaV[i][-1][1][2]) for i in range(len(listaV))]\n mnn1=[min([min([min(listaV[i][j][0][3], listaV[i][j][1][3]) for j in range(len(listaV[0]))])\n for k in range(len(listaV[0][0]))]) for i in range(len(listaV))]\n mnn2=[[mnn1[j] for i in range(len(listaV[0]))] for j in range(len(listaV))]\n mnn3 = [max(listaV[i][0][0][3], listaV[i][-1][1][3]) for i in range(len(listaV))]\n allVuL = [[[listaV[i][j][0][6], listaV[i][j][0][7], listaV[i][j][1][6],\n listaV[i][j][1][7]] for j in range(len(listaV[0]))] for i in range(len(listaV))]\n wo1 = [max([max(listaV[i][j][0][4],listaV[i][j][1][4]) for j in range(len(listaV[0]))]) for i in range(len(listaV))]\n wo2 = [[wo1[j] for i in range(len(listaV[0]))] for j in range(len(listaV))]\n minLo = [min(i) for i in largosV]\n maxLo = [max(i) for i in largosV]\n lV = []\n for i in allVuL:\n a=[[],[],[],[]]\n a[0].append(max([i[j][0][0] for j in range(len(i))]))\n a[0].append(max([i[j][0][1] for j in range(len(i))]))\n a[1].append(max([i[j][1][0] for j in range(len(i))]))\n a[1].append(max([i[j][1][1] for j in range(len(i))]))\n a[1].append(min([i[j][1][2] for j in range(len(i))]))\n a[1].append(max([i[j][1][3] for j in range(len(i))]))\n a[2].append(min([i[j][2][0] for j in range(len(i))]))\n a[2].append(min([i[j][2][1] for j in range(len(i))]))\n a[3].append(min([i[j][3][0] for j in range(len(i))]))\n a[3].append(min([i[j][3][1] for j in range(len(i))]))\n a[3].append(min([i[j][3][2] for j in range(len(i))]))\n a[3].append(max([i[j][3][3] for j in range(len(i))]))\n lV.append(a)\n\n lV2=[[i for j in range(len(allVuL[0]))] for i in lV]\n listaVig = [[[mpp2[i][j],mnn2[i][j],wo2[i][j],largosV[i][j],lV2[i][j], dimV[i][j]]\n for j in range(len(listaV[0]))] for i in range(len(listaV))]\n listaVig2 = [[listaVig[i][0]] for i in range(len(listaVig))]\n detvig2=matElemV(listaVig2, cH, cS, b1, dp, es, ey, eu, fc, fy, dList, ai, deList, 5, nbahias, dimC)\n detvig = [[detvig2[j] for i in range(len(listaVig[0]))] for j in range(len(listaVig))]\n listaCol =[[[max(abs(listaC[i][j][0][k]), abs(listaC[i][j][1][k])) for k in range(6)]\n for j in range(len(listaC[0]))] for i in range(len(listaC))]\n exc_col=[[exc_col[i][j][0] for j in range(len(exc_col[0]))] for i in range(len(exc_col))]\n exc1=max_ind([[exc_col[i][0],exc_col[i][-1]] for i in range(len(exc_col))],2)\n exc2 = max_ind([exc_col[i][1:-1] for i in range(len(exc_col))],2)\n tempCol = extMat(listaCol, 4)\n tempVig = [[[abs(listaVig[i][j][0]),abs(listaVig[i][j][1])]\n for j in range(len(listaVig[0]))] for i in range(len(listaVig))]\n colDef=replMat(listaCol,critVC(tempVig, tempCol),4)\n\n lC1 = []\n for i in range(len(colDef)):\n col1=[max(colDef[i][0][j],colDef[i][-1][j]) for j in range(len(colDef[0][0]))]+exc1[i]\n col2=[max([colDef[i][k][j] for k in range(len(colDef[0])-2)]) for j in range(len(colDef[0][0]))]+exc2[i]\n lC1.append([col1, col2])\n detcol=[]\n cont=0\n listC_bh1 = []\n listC_bh2 = []\n hmax1 = dimC[0][0][0]\n hmax2 = dimC[0][1][0]\n hmin1 = dimC[0][0][2]\n hmin2 = dimC[0][1][2]\n for j in range(len(lC1[0])):\n tempC=[]\n for i in range(len(lC1)):\n if j==0:\n\n cont+=1\n elem=optimusCol(b1, dp, es, eu, ey, fc, fy, lC1[i][j][4], round(lC1[i][j][7]/1000,1),\n round(lC1[i][j][6]/1000,1), lC1[i][j][0], dList, hmax1, hmin1, cH,\n cS, lC1[i][j][5], lC1[i][j][2], lC1[i][j][3], deList, 1, dimV[i][0][0]-5)\n titulo = str(\"Columna tipo \"+ str(j+1)+ \" del piso \" + str(i+1))\n XYplotCurv(elem[0][13], elem[0][2], elem[0][1], dp, eu, fy, fc, b1, es, ey,\n elem[0][14], elem[0][10], lC1[i][j][4], lC1[i][j][0], elem[0][15], elem[0][16], titulo)\n\n # optimusCol(b1, dp, es, eu, ey, fc, fy, muC, muCmin, puCmin, puCmax, dList, hmax, hmin, cH, cS, H, vu,\n # vue, deList, iguales)\n\n # optimo = [minor0, h1, b2, j3, k4, l5, m6, fu7, fu2 8, cuan9, cF[0]10, cF2[0]11, e12,\n # alist13, ylist14, cF[1]15, cF[2]16, muC17, puCmax18, puCmin19, H20, iguales21, round(muCmin / puCmin, 3)22,\n # cF2[1]23, cF2[2]24, costo1 25, costo2 26, dp27]\n tempC.append(elem)\n hmax1=elem[0][1]\n hmin1=hmax1-5\n listC_bh1.append([elem[0][2],elem[0][1]])\n else:\n cont+=1\n elem = optimusCol(b1, dp, es, eu, ey, fc, fy, lC1[i][j][4], round(lC1[i][j][7] / 1000, 1),\n round(lC1[i][j][6] / 1000, 1), lC1[i][j][0], dList, hmax2, hmin2, cH, cS,\n lC1[i][j][5], lC1[i][j][2], lC1[i][j][3], deList, 1,dimV[i][1][0]-5)\n # optimusCol(b1, dp, es, eu, ey, fc, fy, muC, muCmin, puCmin, puCmax, dList, hmax, hmin, cH, cS, H, vu,\n # vue, deList, iguales)\n\n titulo = str(\"Columna tipo \"+ str(j+1)+ \" del piso \" + str(i+1))\n XYplotCurv(elem[0][13], elem[0][2], elem[0][1], dp, eu, fy, fc, b1, es, ey, elem[0][14], elem[0][10],\n lC1[i][j][4], lC1[i][j][0], elem[0][15], elem[0][16], titulo)\n hmax2=elem[0][1]\n hmin2=hmax2-5\n listC_bh2.append([elem[0][2],elem[0][1]])\n tempC.append(elem)\n detcol.append(tempC)\n listC_bh=[]\n cont=0\n for i in range(len(listaC)):\n for j in range(len(listaC[0])):\n if j==0 or j==len(listaC):\n cont+=1\n listC_bh.append((listC_bh1[i][0],listC_bh1[i][1]))\n else:\n cont += 1\n listC_bh.append((listC_bh1[i][0],listC_bh1[i][1]))\n listV_bh=[]\n cont=0\n for i in detvig:\n for j in i:\n cont+=1\n listV_bh.append((j[0][0][2],j[0][0][1]))\n print(detcol)\n detC=detCol(detcol)\n print(detvig2)\n detV=detVig(detvig2,nbahias,listV_bh)\n col1=sum([detcol[0][i][0][0]*2 for i in range(len(detcol[0]))])\n col2=sum([detcol[1][i][0][0]*(nbahias-1) for i in range(len(detcol[0]))])\n costoT1=col1+col2\n costoT2=sum([detvig2[i][j][0][0] for i in range(len(detvig2)) for j in range(len(detvig2[0]))])\n print(\"valor columnas\", round(costoT1))\n print(\"valor vigas\", round(costoT2))\n costoT=round(costoT1+costoT2)\n print(\"valor total\", costoT )\n # print(\"drift maximo :\",ppp.tabla['drift'],\"‰\")\n list_bh = listC_bh+listV_bh\n\n \"\"\" Detallamiento de Vigas y columnas \"\"\"\n\n # Descripción general\n\n des_gral=[round(cS/7850), cH, round(costoT1), round(costoT2), costoT]\n\n descripcion_gral = [\"Costo de acero \"+str(des_gral[0])+\" [$/kg]\",\\\n \"Costo de hormigón \"+str(des_gral[1])+\" [$/m3]\",\\\n \"Costo vigas $ \"+str(des_gral[2]),\\\n \"Costo columnas $ \"+str(des_gral[3]),\\\n \"Costo total $ \"+str(des_gral[4])]\n RUGod = open(proyecto + '/tmp/descGral.txt', 'w', encoding='utf-8')\n for i in descripcion_gral:\n print(i + '\\n')\n RUGod.write(i + '\\n')\n RUGod.close()\n return [detcol,detvig2, list_bh, des_gral]\n\n from time import time\n t1=time()\n asd=optimusFrame(tabla, largosC, largosV, dimV, cH, cS, b1, dp,\n es, ey, eu, fc, fy, dList, deList, hColMax, hColMin)\n t2=time()-t1\n print(\"tiempo de ejecución\",round(t2,5),\"segundos\")\n print(asd[0],\"\\n\",asd[1])\n print(asd[2])\n # print(asd[3])\n # print('pete')\n return asd[2]\n\n#jandro()\n","sub_path":"src/bbeam/opti.py","file_name":"opti.py","file_ext":"py","file_size_in_byte":103068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"77599286","text":"from django.contrib import admin\nfrom .models import Category, Photo\n# Register your models here.\n\n# ここでAdminページでどうやって表示させるかを決めれる。\n# CategoryモデルもAdminページに表示させておきたい。\nclass CategoryAdmin(admin.ModelAdmin):\n list_display = ('id', 'title')\n list_display_links = ('id', 'title')\n\nclass PhotoAdmin(admin.ModelAdmin):\n list_display = ('id', 'title')\n list_display_links = ('id', 'title')\n\nadmin.site.register(Category, CategoryAdmin)\nadmin.site.register(Photo, PhotoAdmin)","sub_path":"app/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"178223985","text":"import tensorflow as tf\n\n# 第一个例子,计算两个数的加法\na = tf.constant(2)\nb = tf.constant(3)\nx = tf.add(a, b)\n\n# 在tensorboard中查看\n# 执行命令 tensorboard --logdir=/Users/xingoo/PycharmProjects/ml-in-action/实践-tensorflow/03-stanford/graphs\n\nwith tf.Session() as sess:\n print(sess.graph.as_graph_def())\n\n writer = tf.summary.FileWriter('./graphs', sess.graph)\n print(sess.run(x))\n\nwriter.close()","sub_path":"01-实践-tensorflow/03-stanford/03-普通的数据流图.py","file_name":"03-普通的数据流图.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"448545035","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom database_setup import Base, User, Categories, Items\n\n# Database connection\nengine = create_engine('sqlite:///catalog.db')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n# Create dummy user\nuser1 = User(name=\"Edward the Great\", email=\"edwardthegreat@madeup.com\",\n picture=\"http://www.bagulho.net/wp-content/uploads/2011/03/\"\n \"Edward-the-Great.jpg\")\nsession.add(user1)\nsession.commit()\n\n#Items for cars\ncars = Categories(name='Cars', user_id=1)\nsession.add(cars)\nsession.commit()\n\nm3 = Items(name='BMW M3', description='Pretty cool looking car. Also fast, and'\n ' apparently fun to drive. I wouldn\\'t '\n 'know',\n image='http://api.ning.com/files/kV4MbYiv7oR5dmjXk-4z-'\n 'wd6k5xx*EGFRdI0lLHU6D9jPyMP1BcqQWN*zUkTX4HE6pi4xLO361WGmdp4'\n 'RrhO3EI0OA*q5UnE/1082035334.jpeg', category_id=1, user_id=1)\nsession.add(m3)\nsession.commit()\n\nfiesta = Items(name='Ford Fiesta ST', description='Looks cool and has an engine'\n ' with more power than an'\n ' engine it size has any'\n ' business having. It\\'s'\n ' crazy',\n image='https://photos-1.carwow.co.uk/models/1600x800/'\n 'FiestaST_031.jpg',\n category_id=1, user_id=1)\nsession.add(fiesta)\nsession.commit()\n\ngti = Items(name='Volkswagen Golf GTI', description='Zippy and fun to drive '\n 'apparently. Maybe avoid '\n 'since the whole dieselgate'\n ' thing',\n image='http://www.topgear.com/sites/default/files/styles/'\n '16x9_1280w/public/cars-car/image/2015/02/buyers_guide_-_'\n 'vw_golf_gti_2014_-_front_quarter.jpg?itok=lwiRtMw0',\n category_id=1, user_id=1)\nsession.add(gti)\nsession.commit()\n\n\n#Items for whatever\nconsoles = Categories(name='Consoles', user_id=1)\nsession.add(consoles)\nsession.commit()\n\nxbox = Items(name='Xbox One', description='Current Microsoft console. Has a '\n 'very nice controller. '\n 'Updates frequently. '\n 'Nearly identical to the PS4',\n image='http://static1.gamespot.com/uploads/original/'\n '1534/15343359/2823737-6174472236-26119.jpg',\n category_id=2, user_id=1)\nsession.add(xbox)\nsession.commit()\n\nps4 = Items(name='Playstation 4', description='Current Sony console. More '\n 'powerful than the Xbox One, '\n 'but otherwise nearly identical',\n image='http://www.geek.com/wp-content/uploads/2016/03/'\n 'PlayStation-4.jpg',\n category_id=2, user_id=1)\nsession.add(ps4)\nsession.commit()\n\nwiiu = Items(name='Wii U', description='Great for playing Nintendo games.'\n ' Weak hardware otherwise',\n image='http://www.nintendo.com/images/page/wiiu/features/'\n 'hero-1.jpg',\n category_id=2, user_id=1)\nsession.add(wiiu)\nsession.commit()\n\n\n#items for whatever\nprocessors = Categories(name='Processors', user_id=1)\nsession.add(processors)\nsession.commit()\n\namd = Items(name='AMD', description='Advanced Micro Devices is a company that '\n 'develops processors and graphics cards. '\n 'Currently they lag behind Intel in '\n 'performance',\n image='http://i1-news.softpedia-static.com/images/news2/AMD-FX-'\n '6100-and-FX-4100-Bulldozer-CPUs-Arrive-in-Europe-2.jpg',\n category_id=3, user_id=1)\nsession.add(amd)\nsession.commit()\n\nintel = Items(name='Intel', description='Current leader in computer processors.'\n ' Unmatched in performance, albeit at a'\n ' price premium',\n image='http://cdn.phys.org/newman/gfx/news/hires/2012/'\n '1-intelintrodu.jpg',\n category_id=3, user_id=1)\nsession.add(intel)\nsession.commit()\n\nprint('Catalog populated')","sub_path":"Vagrant/app/catalog_populate.py","file_name":"catalog_populate.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63326543","text":"# coding:utf-8\nimport argparse\n\n\ndef parser_param():\n parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\n # parser.add_argument('-data', '--data', default='/ifs/training_data/ImageNet2012', type=str, metavar='P',\n parser.add_argument('--data', '--data', default='/home/lingc1/data/ImageNet2012', type=str, metavar='P',\n help='path to dataset')\n parser.add_argument('-j', '--workers', default=24, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\n parser.add_argument('--batch-size', '--batch-size', default=32, type=int,\n metavar='N',\n help='mini-batch size (default: 256), this is the total '\n 'batch size of all GPUs on the current node when '\n 'using Data Parallel or Distributed Data Parallel')\n # parser.add_argument('--lr', '--learning-rate', default=0.025, type=float,\n parser.add_argument('--lr', '--learning-rate', default=0.1, type=float,\n metavar='LR', help='initial learning rate', dest='lr')\n parser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\n parser.add_argument('--wd', '--weight-decay', default=0.0005, type=float,\n metavar='W', help='weight decay (default: 1e-4)',\n dest='weight_decay')\n parser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\n parser.add_argument('--epochs', default=120, type=int, metavar='N',\n help='number of total epochs to run')\n parser.add_argument('--debug', dest='debug', action='store_true', default=False,\n help='debug training')\n parser.add_argument('-p', '--print-freq', default=100, type=int,\n metavar='N', help='print frequency (default: 10)')\n\n # distribute parameters\n parser.add_argument('--backend', default='nccl', type=str,\n help='distributed backend')\n parser.add_argument('--url', default='tcp://127.0.0.1:12345', type=str,\n help='url used to set up distributed training')\n parser.add_argument('--rank', default=0, type=int,\n help='node rank for distributed training')\n parser.add_argument('--world-size', default=1, type=int,\n help='number of nodes for distributed training')\n parser.add_argument('--last-node-gpus', default=0, type=int,\n help='number of nodes for distributed training')\n parser.add_argument('--sync_bn', action='store_true', default=False,\n help='synchronization the batch normal on different GPUs.')\n parser.add_argument('--distribute', action='store_true', default=False,\n help='Use multi-processing distributed training to launch '\n 'N processes per node, which has N GPUs. This is the '\n 'fastest way to use PyTorch for either single node or '\n 'multi node data parallel training')\n\n args = parser.parse_args()\n return args\n","sub_path":"project/distributed/Darknet_v2.0/parse_param.py","file_name":"parse_param.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"645303715","text":"import os\nimport shutil\nimport pandas\n\n\nds = pandas.read_csv(\"imagenet-contributors.csv\", skipinitialspace=True)\ncinic_sets = ds[\"cinic_set\"].unique()\ncinic_classes = ds[\"class\"].unique()\nunique_sets = ds[\"synset\"].unique()\n\n\nsrc = \"/home/lengx/SSD/imagenet_subset/\"\ndst = \"/home/lengx/SSD/cinic-10-original/\"\n\n# verify all images required are in the src folder\ndownloaded = os.listdir(src)\nassert all([unique_set in downloaded for unique_set in unique_sets])\n\nfor cinic_set in cinic_sets:\n for cinic_class in cinic_classes:\n class_set_path = os.path.join(dst, cinic_set, cinic_class)\n # create dataset folder\n if not os.path.exists(class_set_path):\n os.makedirs(class_set_path)\n subset = ds[(ds[\"cinic_set\"] == cinic_set) & (ds[\"class\"] == cinic_class)]\n for _, row in subset.iterrows():\n imagenet_set = row[\"synset\"]\n imagenet_num = row[\"image_num\"]\n # copy images\n img_name = f\"{imagenet_set}_{imagenet_num}.JPEG\"\n shutil.copyfile(\n os.path.join(src, imagenet_set, img_name),\n os.path.join(class_set_path, img_name)\n )\n","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"157492070","text":"from behave import given, when, then\nfrom selenium.webdriver.common.by import By\n\norders_link_icon = (By.CSS_SELECTOR, \"a#nav-orders\")\nsign_in = (By.CSS_SELECTOR, \"div h1.a-spacing-small\")\n\n\n@when('Click Amazon Orders link')\ndef orders_link(context):\n # context.driver.find_element(*orders_link_icon).click()\n context.app.main_page.order_link()\n\n\n@then('Verify {text} page is opened')\ndef sign_in_open(context, text):\n # actual = context.driver.find_element(*sign_in).text\n # assert text == actual, f'Expected text {text}, but got {actual}'\n context.app.sign_in_page.check_text(text)\n","sub_path":"hw_7/features/steps/sign_in.py","file_name":"sign_in.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"52700178","text":"#!/usr/bin/python3\n\nimport os\nimport sys\n\nclass TaxRule:\n start = 0\n stop = 0\n rate = 0\n def __init__(self, start, stop, rate):\n self.start = start\n self.stop = stop\n self.rate = rate\n \n def calc_tax(self, income):\n if income <= self.start:\n return 0\n if self.stop >= 0 and income > self.stop:\n income = self.stop\n return (income - self.start) * self.rate\n\ndef calc_get(income, rules):\n sum = 0\n for rule in rules:\n sum += rule.calc_tax(income - 3500)\n return income - sum\n\ndef calc_income(get, rules):\n incs = []\n for last in range(len(rules)):\n tax = 0\n for i in range(0,last):\n tax += rules[i].calc_tax(get)\n rule = rules[last]\n income = get + tax\n income = (income - rule.start) / (1 - rule.rate) + rule.start\n if calc_get(income,rules) == get:\n return income\n return -1\n\ntax_rules = [\n TaxRule(0, 1500, 0.03),\n TaxRule(1500, 4500, 0.10),\n TaxRule(4500, 9000, 0.20),\n TaxRule(9000, 35000, 0.25),\n TaxRule(35000, 55000, 0.30),\n TaxRule(55000, 80000, 0.35),\n TaxRule(80000, -1, 0.45),\n]\n\ndef solve(func, out, start=0, step=100, count=100):\n last_x = start\n last_y = func(last_x)\n print('out:{0}, start:{1}, step:{2}'.format(out,start,step))\n if abs(last_y-out) < 0.01:\n return start\n while True:\n curr_x = last_x + step\n curr_y = func(curr_x)\n if (last_y-out)*(curr_y-out) < 0:\n print('success:[{0},{2}) => [{1},{3})'.format(last_x,last_y,curr_x,curr_y))\n break\n if curr_y==out:\n return curr_x\n count -= 1\n if count == 0:\n print('fail:[{0},{2}) => [{1},{3})'.format(last_x,last_y,curr_x,curr_y))\n return -1\n last_x,last_y = curr_x,curr_y\n return solve(func,out,start,step/10,count)\n\ndef solve2(func, y, xerr = 0.0001, yerr = 0.001, base = 10):\n x1 = 0\n x2 = 1\n y1 = func(x1)\n y2 = func(x2)\n while True:\n if (y1 - y) * (y2 - y) <= 0:\n break\n x2 = -x2\n y2 = func(x2)\n\n if (y1 - y) * (y2 - y) <= 0:\n break\n x2 *= base\n y2 = func(x2)\n \n while True:\n if abs(y1 - y) <= yerr:\n return x1\n if abs(x1 - x2) <= xerr:\n return (x1 + x2) / 2\n step = (x2 - x1) / base\n for i in range(0,base):\n x2 = x1 + step\n y2 = func(x2)\n if abs(y2 - y) <= yerr:\n return x2\n if (y1 - y) * (y2 - y) <= 0:\n break\n x1,y1 = x2,y2\n else:\n print('error at:({0},{1})'.format(x1,x2))\n \nget = 0\nif len(sys.argv) > 1:\n get = float(sys.argv[1])\nelse:\n get = float(input('get:'))\n\n#print('income:{0}'.format(solve(lambda income:calc_get(income,tax_rules),get,0,count=100000)))\nprint('income:{0}'.format(solve2(lambda income:calc_get(income,tax_rules),get)))\n","sub_path":"tax.py","file_name":"tax.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"264006952","text":"# 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。\n#\n# 示例:\n#\n# 输入: n = 4, k = 2\n# 输出:\n# [\n# [2,4],\n# [3,4],\n# [2,3],\n# [1,2],\n# [1,3],\n# [1,4],\n# ]\n\n\nclass Zh(object):\n def __init__(self):\n pass\n def zuhe2(self,n,k):\n result=[]\n nums=[i for i in range(1,n+1)]\n\n res=nums[:k]\n print(\"res=\",res)\n result.append(res)\n\n changeidx=-1\n\n while changeidx>-k:\n res2=self.changeonde(changeidx,k,n,res)\n result.append(res2)\n changeidx-=1\n return result\n def changeonde(self,changeidx,k,n,res):\n for j in range(k+1,n+1):\n del res[changeidx]\n res.append(j)\n return res\n\nzh=Zh()\nprint(zh.zuhe2(4,2))","sub_path":"Week_03/组合.py","file_name":"组合.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"231992391","text":"'''\r\n@File : cmdHelper.py\r\n@Time : 2019/02/27\r\n@Author : Yaron Huang \r\n@Version : 1.0\r\n@Contact : yaronhuang@qq.com\r\n@Desc : \r\n'''\r\n#!/usr/bin/env python\r\n# -*- encoding: utf-8 -*-\r\nimport sys\r\nimport ctypes\r\nimport platform\r\nfrom enum import Enum\r\n\r\n\r\ndef isInputYes(inputstr):\r\n \"\"\"\r\n #Func : 输入的字符串是否为yes \r\n #Param : inputstr [in] 输入串 \r\n #Return : True/False \r\n \"\"\"\r\n if inputstr is None:\r\n return False\r\n inputstr = str(inputstr).lower()\r\n if inputstr == 'yes' or inputstr == 'y':\r\n return True\r\n return False\r\n\r\ndef myinput(desc):\r\n \"\"\"\r\n #Func : 输入优化-支持python2.x/3.x \r\n #Param : desc [in] 描述 \r\n #Return : 输入的参数\r\n \"\"\"\r\n v = sys.version_info\r\n if v[0] > 2:\r\n return input(desc)\r\n else:\r\n return raw_input(desc)\r\n\r\ndef myinputInt(desc, default):\r\n \"\"\"\r\n #Func : 输入整型优化-支持python2.x/3.x \r\n #Param : desc [in] 描述 \r\n #Param : default [in] 默认的整型数 \r\n #Return : 输入的整型数 \r\n \"\"\"\r\n try:\r\n stri = myinput(desc)\r\n ret = int(stri)\r\n return ret\r\n except:\r\n return default\r\n\r\ndef myinputFloat(desc, default):\r\n \"\"\"\r\n #Func : 输入浮点数优化-支持python2.x/3.x \r\n #Param : desc [in] 描述 \r\n #Param : default [in] 默认的浮点数 \r\n #Return : 输入的浮点数 \r\n \"\"\"\r\n try:\r\n stri = myinput(desc)\r\n ret = float(stri)\r\n return ret\r\n except:\r\n return default\r\n\r\n\r\ndef findInArgv(stri):\r\n \"\"\"\r\n #Func : mian参列表中查找第一个有此子串的项 \r\n #Param : stri [in] 子串 \r\n #Return : None/子项 \r\n \"\"\"\r\n if sys.argv == None or len(sys.argv) == 0:\r\n return None\r\n \r\n for item in sys.argv:\r\n if item == sys.argv[0]:\r\n continue\r\n if item.find(stri) >= 0:\r\n return item\r\n return None\r\n\r\ndef converArgvToStr(array):\r\n \"\"\"\r\n #Func : 将列表转成main参字符串 \r\n #Param : list [in] 项列表 \r\n #Return : 字符串 \r\n \"\"\"\r\n stri = ''\r\n for item in array:\r\n if stri != '':\r\n stri = stri + ' '\r\n stri = stri + '\"' + item + '\"'\r\n return stri\r\n\r\n\r\nclass TextColor(Enum):\r\n \"\"\"\r\n #Func : 前景颜色\r\n \"\"\"\r\n if platform.system() == 'Windows':\r\n Black = 0x00\r\n Blue = 0x09\r\n Green = 0x0a\r\n Red = 0x0c\r\n Yellow = 0x0e\r\n White = 0x0f\r\n else:\r\n Black = 30\r\n Blue = 34\r\n Green = 32\r\n Red = 31\r\n Yellow = 33\r\n White = 37\r\n\r\nclass BackGroundColor(Enum):\r\n \"\"\"\r\n #Func : 背景颜色\r\n \"\"\"\r\n if platform.system() == 'Windows':\r\n Black = 0x00\r\n Blue = 0x90\r\n Green = 0xa0\r\n Red = 0xc0\r\n Yellow = 0xe0\r\n White = 0xf0\r\n else:\r\n Black = 40\r\n Blue = 44\r\n Green = 42\r\n Red = 41\r\n Yellow = 43\r\n White = 47\r\nclass WinCmdHandleID(Enum): \r\n \"\"\"\r\n #Func : Windows的输入、输出、错误输出的句柄ID\r\n \"\"\"\r\n Input = -10\r\n Output = -11\r\n Error = -12\r\n\r\ndef myprint(desc,textColor=None,backgroundColor=None):\r\n \"\"\"\r\n #Func : 输出 \r\n #Param : desc [in] 信息 \r\n #Param : textColor [in] 前景颜色 \r\n #Param : backgroundColor [in] 背景颜色 \r\n #Return : None \r\n \"\"\"\r\n if textColor is None and backgroundColor is None:\r\n sys.stdout.write(desc)\r\n else:\r\n if platform.system() == 'Windows':\r\n color = 0\r\n if textColor is not None:\r\n color = color | textColor.value\r\n if backgroundColor is not None:\r\n color = color | backgroundColor.value\r\n #获取输出句柄,修改颜色\r\n handle = ctypes.windll.kernel32.GetStdHandle(WinCmdHandleID.Output.value)\r\n ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)\r\n sys.stdout.write(desc)\r\n #设置回原来的颜色\r\n value = TextColor.Red.value | TextColor.Green.value | TextColor.Blue.value\r\n ctypes.windll.kernel32.SetConsoleTextAttribute(handle, value)\r\n else:\r\n color = ''\r\n if textColor is not None:\r\n color = str(textColor.value)\r\n if backgroundColor is not None:\r\n if color != '':\r\n color = color +';'\r\n color = color + str(backgroundColor.value)\r\n color = color + 'm'\r\n sys.stdout.write(\"\\033[\" + color + str(desc) + \"\\033[0m\")\r\n\r\ndef showTable(columns, rows, colsColor=None, rowsColor=None):\r\n \"\"\"\r\n #Func : 显示表格 \r\n #Param : columns [in] 列名数组 \r\n #Param : rows [in] 行值数组-二维数组 \r\n #Param : colsColor [in] 列名颜色 \r\n #Param : rowsColor [in] 行颜色 \r\n #Return : True/False \r\n \"\"\"\r\n try:\r\n widths = []\r\n for item in columns:\r\n name = str(item) \r\n widths.append(len(name))\r\n \r\n for rObj in rows:\r\n index = 0\r\n for item in rObj:\r\n if len(item) > widths[index]:\r\n widths[index] = len(item)\r\n index = index + 1\r\n if len(widths) <= index:\r\n break\r\n \r\n boardstr = '-'\r\n for item in widths:\r\n for i in range(item + 2 + 1):\r\n boardstr = boardstr + '-'\r\n\r\n print(boardstr)\r\n index = 0\r\n for item in columns:\r\n item = item.center(widths[index] + 2)\r\n print('|', end='')\r\n myprint(item, colsColor)\r\n index = index + 1\r\n if len(widths) <= index:\r\n break\r\n print('|')\r\n print(boardstr)\r\n for rObj in rows:\r\n index = 0\r\n for item in rObj:\r\n item = item.center(widths[index] + 2)\r\n print('|',end='')\r\n myprint(item, rowsColor)\r\n index = index + 1\r\n if len(widths) <= index:\r\n break\r\n print('|')\r\n print(boardstr)\r\n return True\r\n except:\r\n return False\r\n","sub_path":"aigpy/cmdHelper.py","file_name":"cmdHelper.py","file_ext":"py","file_size_in_byte":6683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"36954318","text":"# Lint as: python3\n# Copyright 2020 DeepMind Technologies Limited. 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\"\"\"Lifting parameters in Haiku.\"\"\"\n\nfrom absl.testing import absltest\nfrom haiku._src import base\nfrom haiku._src import lift\nfrom haiku._src import module\nfrom haiku._src import transform\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n\n\nclass Bias(module.Module):\n\n def __call__(self, x):\n b = base.get_parameter(\"b\", (), init=jnp.ones)\n return x + b\n\n\nclass LiftTest(absltest.TestCase):\n\n def test_functionalize(self):\n def inner_fn(x):\n assert x.ndim == 1\n return Bias()(x)\n\n def outer_fn(x):\n assert x.ndim == 2\n x = Bias()(x)\n inner = transform.transform(inner_fn)\n inner_p = lift.lift(inner.init)(base.next_rng_key(), x[0])\n vmap_inner = jax.vmap(inner.apply, in_axes=(None, 0))\n return vmap_inner(inner_p, x)\n\n key = jax.random.PRNGKey(428)\n init_key, apply_key = jax.random.split(key)\n data = np.zeros((3, 2))\n\n outer = transform.transform(outer_fn, apply_rng=True)\n outer_params = outer.init(init_key, data)\n self.assertEqual(outer_params, {\n \"bias\": {\"b\": np.ones(())},\n \"lifted/bias\": {\"b\": np.ones(())},\n })\n\n out = outer.apply(outer_params, apply_key, data)\n np.testing.assert_equal(out, 2 * np.ones((3, 2)))\n\n\nif __name__ == \"__main__\":\n absltest.main()\n","sub_path":"haiku/_src/lift_test.py","file_name":"lift_test.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"13675856","text":"from innovation import *\r\nfrom genotype import *\r\nfrom species import *\r\nfrom phenotype import *\r\nfrom consts import *\r\n\r\nclass GeneticAlgorithm:\r\n def __init__(self, task):\r\n self.genomes = []\r\n self.species = []\r\n self.best_ever = None\r\n self.innovation_db = InnovationDB()\r\n self.task = task\r\n self.generation = 0\r\n self.next_genome_id = 0\r\n self.next_species_id = 0\r\n\r\n self.highest_fitness = 0.0\r\n self.highest_last_changed = 0\r\n\r\n while len(self.genomes) < Neat.pop_size:\r\n genome = Genome(self.next_genome_id, self.innovation_db, None, None, self.task.n_inputs, self.task.n_outputs)\r\n self.genomes.append(genome)\r\n #genome.str()\r\n self.next_genome_id += 1\r\n\r\n self.speciate()\r\n\r\n for g in self.genomes:\r\n network = Network(g)\r\n g.fitness = self.task.evaluate(network)\r\n\r\n self.genomes.sort(key = lambda x: x.fitness, reverse = True)\r\n self.generation += 1\r\n\r\n for s in self.species:\r\n for g in s.members:\r\n print(s.id, \" : \", g.id)\r\n\r\n\r\n def speciate(self):\r\n for g in self.genomes:\r\n if len(self.species)==0:\r\n newspecies = Species(g, self.next_species_id)\r\n self.next_species_id += 1\r\n self.species.append(newspecies)\r\n\r\n else:\r\n found = False\r\n for s in self.species:\r\n if Species.compatibility_score(g, s.members[0]) < Neat.compat_threshold:\r\n s.add_member(g)\r\n found = True\r\n break\r\n\r\n if found == False:\r\n newspecies = Species(g, self.next_species_id)\r\n self.next_species_id += 1\r\n self.species.append(newspecies)\r\n\r\n def epoch(self):\r\n total_organisms = Neat.pop_size\r\n total = 0.0\r\n #sorted_species = sorted(self.species, key = lambda x: x.members[0].orig_fitness, reverse = True)\r\n\r\n #if generation%30 == 0:\r\n # for i in range(len(sorted_species)-1, -1, -1):\r\n # if sorted_species[i].age >= 20\r\n # sorted_species[i].obliterate=True\r\n # break\r\n\r\n for s in self.species:\r\n s.adjust_fitness()\r\n\r\n for g in self.genomes:\r\n total += g.fitness\r\n\r\n overall_average = total / total_organisms\r\n\r\n\r\n for g in self.genomes:\r\n g.spawns_required = g.fitness / overall_average\r\n\r\n skim = 0.0\r\n total_expected = 0\r\n for s in self.species:\r\n skim = s.count_offspring(skim)\r\n total_expected += s.spawns_required\r\n\r\n if total_expected < total_organisms:\r\n print('ERROR')\r\n max_expected = 0\r\n final_expected = 0\r\n for s in self.species:\r\n if s.spawns_required >= max_expected:\r\n max_expected = s.spawns_required\r\n best_species = s\r\n final_expected += s.spawns_required\r\n\r\n best_species.spawns_required += 1\r\n final_expected += 1\r\n\r\n if final_expected < total_organisms:\r\n print(\"MASSIVE ERROR\")\r\n for s in self.species:\r\n s.spawns_required = 0\r\n best_species.spawns_required = total_organisms\r\n\r\n sorted_species = sorted(self.species, key = lambda x: x.members[0].orig_fitness, reverse = True)\r\n best_species_num = sorted_species[0].id\r\n\r\n if sorted_species[0].members[0].orig_fitness > self.highest_fitness:\r\n self.highest_fitness = sorted_species[0].members[0].orig_fitness\r\n self.highest_last_changed = 0\r\n else:\r\n self.highest_last_changed += 1\r\n '''\r\n if self.highest_last_changed >= Neat.dropoff_age+5:\r\n print(\"RESET\")\r\n self.highest_last_changed = 0\r\n half_pop = int(Neat.pop_size/2)\r\n\r\n s = sorted_species[0]\r\n s.members[0].super_champ_offspring = half_pop\r\n s.spawns_required = half_pop\r\n s.age_of_last_improvement = s.age\r\n\r\n if len(sorted_species)>1:\r\n s = sorted_species[1]\r\n s.members[0].super_champ_offspring = Neat.pop_size - half_pop\r\n s.spawns_required = Neat.pop_size - half_pop\r\n s.age_of_last_improvement = s.age\r\n\r\n for s in sorted_species[2:]:\r\n s.spawns_required = 0\r\n\r\n else:\r\n s = sorted_species[0]\r\n s.members[0].super_champ_offspring += Neat.pop_size - half_pop\r\n s.spawns_required += Neat.pop_size - half_pop\r\n '''\r\n '''\r\n print('Before eliminate: ')\r\n for s in self.species:\r\n for g in s.members:\r\n print(s.id, \" : \", g.id)\r\n '''\r\n for g in self.genomes[:]:\r\n if g.eliminate:\r\n g.species.remove_member(g)\r\n self.genomes.remove(g)\r\n\r\n\r\n #self.genomes = list(filter(lambda x: not x.eliminate, self.genomes))\r\n #for s in self.species:\r\n # s.members = list(filter(lambda x: not x.eliminate, s.members))\r\n '''\r\n print('\\nAfter eliminate:')\r\n for s in self.species:\r\n for g in s.members:\r\n print(s.id, \" : \", g.id)\r\n print('\\nGenomes:')\r\n for g in self.genomes:\r\n print(g.id)\r\n '''\r\n last_id = self.species[0].id\r\n for s in self.species:\r\n s.reproduce(self.generation, self, sorted_species)\r\n last_id = s.id\r\n '''\r\n print(\"After reproduce:\")\r\n for s in self.species:\r\n for g in s.members:\r\n print(s.id, \" : \", g.id)\r\n print('\\nGenomes:')\r\n for g in self.genomes:\r\n print(g.id)\r\n '''\r\n for g in self.genomes[:]:\r\n g.species.remove_member(g)\r\n self.genomes.remove(g)\r\n\r\n for s in self.species[:]:\r\n if len(s.members) == 0:\r\n self.species.remove(s)\r\n\r\n else:\r\n s.age += 1\r\n\r\n for m in s.members:\r\n self.genomes.append(m)\r\n '''\r\n print('\\nAfter more eliminate:')\r\n for s in self.species:\r\n for g in s.members:\r\n print(s.id, \" : \", g.id)\r\n print('\\nGenomes:')\r\n for g in self.genomes:\r\n print(g.id)\r\n '''\r\n for g in self.genomes:\r\n network = Network(g)\r\n g.fitness = self.task.evaluate(network)\r\n\r\n self.genomes.sort(key = lambda x: x.fitness, reverse = True)\r\n '''\r\n print('\\nAfter sorting:')\r\n print('\\nGenomes:')\r\n for g in self.genomes:\r\n print(g.id)\r\n '''\r\n\r\n for s in self.species:\r\n for g in s.members:\r\n print(s.id, \" : \", g.id, ' : ', len(g.neurons), ' : ', g.fitness-200)\r\n\r\n self.generation += 1\r\n","sub_path":"neat2.py","file_name":"neat2.py","file_ext":"py","file_size_in_byte":7172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"135971228","text":"import unittest\nfrom app import *\n\n\nclass MyTestCase(unittest.TestCase):\n\n \"\"\"\n On réalise des tests avec comme critère la couverture des branches\n \"\"\"\n\n def test_List(self):\n\n MyList = List()\n\n # test de check() et peek() sans premier élément\n with self.assertRaises(ValueError):\n MyList.check()\n with self.assertRaises(ValueError):\n MyList.peek()\n\n # test de append() sans élément et check() avec un élément\n item = 1\n MyList.append(item)\n self.assertEqual(MyList.size(), 1)\n self.assertEqual(MyList.check(), 1)\n\n # test de peek() avec un élément\n self.assertEqual(MyList.peek(), 1)\n self.assertEqual(MyList.size(), 0)\n\n # test de predpend() sans élément\n MyList.prepend(item)\n self.assertEqual(MyList.size(), 1)\n self.assertEqual(MyList.check(), 1)\n\n # test de append() avec un élément\n item2 = 2\n MyList.append(item2)\n self.assertEqual(MyList.size(), 2)\n self.assertEqual(MyList.liste[1], 2)\n\n # test de prepend() avec un élément\n item3 = 3\n MyList.prepend(item3)\n self.assertEqual(MyList.size(), 3)\n self.assertEqual(MyList.check(), 3)\n self.assertEqual(MyList.liste[1], item)\n\n def test_Queue(self):\n\n queue = Queue(2)\n\n # test de dequeue() sans élément\n with self.assertRaises(ValueError):\n queue.dequeue()\n self.assertTrue(queue.isEmpty())\n\n # test de enqueue() sans élément\n item = 1\n queue.enqueue(item)\n self.assertEqual(queue.size(), 1)\n self.assertEqual(queue.check(), 1)\n\n # test de enqueue() avec un élément\n item2 = 2\n queue.enqueue(item2)\n self.assertEqual(queue.size(), 2)\n self.assertEqual(queue.liste[1], 2)\n\n # test de enqueue() au max de la capacité\n item3 = 3\n with self.assertRaises(ValueError):\n queue.enqueue(item3)\n\n queue.dequeue()\n self.assertEqual(queue.size(), 1)\n\n def test_Stack(self):\n stack = Stack(2)\n\n # test de pop() sans élément\n with self.assertRaises(ValueError):\n stack.pop()\n self.assertTrue(stack.isEmpty())\n\n # test de push() sans élément\n item = 1\n stack.push(item)\n self.assertEqual(stack.size(), 1)\n self.assertEqual(stack.check(), 1)\n\n # test de push() avec un élément\n item2 = 2\n stack.push(item2)\n self.assertEqual(stack.size(), 2)\n self.assertEqual(stack.liste[1], 1)\n self.assertEqual(stack.check(), 2)\n\n # test de push() au max de la capacité de la queue\n item3 = 3\n with self.assertRaises(ValueError):\n stack.push(item3)\n\n # test de pop() au max de la capacité de la queue\n stack.pop()\n self.assertEqual(stack.size(), 1)\n\n def test_AutoAdaptiveStack(self):\n size_increment = 5\n max_size = 2\n max_trials = 3\n autoAdaptiveStack = AutoAdaptiveStack(max_trials, size_increment, max_size)\n\n # test de pop() sans élément\n with self.assertRaises(ValueError):\n autoAdaptiveStack.pop()\n self.assertTrue(autoAdaptiveStack.isEmpty())\n\n # test de push() sans élément\n item = 1\n autoAdaptiveStack.push(item)\n self.assertEqual(autoAdaptiveStack.size(), 1)\n self.assertEqual(autoAdaptiveStack.check(), item)\n\n # test de push() avec un élément\n item2 = 2\n autoAdaptiveStack.push(item2)\n self.assertEqual(autoAdaptiveStack.size(), max_size)\n self.assertEqual(autoAdaptiveStack.check(), item2)\n self.assertEqual(autoAdaptiveStack.liste[1], item)\n\n # test de push() au max de la capacité\n item3 = 3\n autoAdaptiveStack.push(item3)\n self.assertEqual(autoAdaptiveStack.size(), max_size)\n self.assertEqual(autoAdaptiveStack.trials, 1) # incrémente trial de 1\n self.assertEqual(autoAdaptiveStack.waiting_list, [item3]) # ajoute l'élément à la waiting list\n\n # test de pop() au max de la capacité\n autoAdaptiveStack.pop()\n self.assertEqual(autoAdaptiveStack.size(), max_size)\n self.assertEqual(autoAdaptiveStack.trials, 1) # ne touche pas au trial\n self.assertEqual(autoAdaptiveStack.check(), item3) # 1er élément dans la waiting list ajouté à la queue\n self.assertEqual(autoAdaptiveStack.waiting_list, []) # waiting list vide\n\n # test de push() au max de la capacité\n item4 = 4\n autoAdaptiveStack.push(item4)\n self.assertEqual(autoAdaptiveStack.size(), max_size)\n self.assertEqual(autoAdaptiveStack.trials, 2)\n self.assertEqual(autoAdaptiveStack.waiting_list, [item4])\n\n # test de push() au max de la capacité de la liste et de la waiting list au max trial\n item5 = 5\n autoAdaptiveStack.push(item5)\n self.assertEqual(autoAdaptiveStack.size(), 3)\n self.assertEqual(autoAdaptiveStack.trials, 0) # trial réinitialisé\n self.assertEqual(autoAdaptiveStack.waiting_list, []) # waiting liste vidée\n self.assertEqual(autoAdaptiveStack.liste[0], item4) # élément de la waiting list a été ajouté automatiquement\n self.assertEqual(autoAdaptiveStack.liste[1], item3) # item5 pas ajouté car plus de place dans la waiting list\n self.assertEqual(autoAdaptiveStack.max_size, max_size + size_increment) # max size augmenté de size increment\n\n def test_AutoAdaptiveQueue(self):\n size_increment = 2\n max_size = 2\n max_trials = 3\n autoAdaptiveQueue = AutoAdaptiveQueue(max_trials, size_increment, max_size)\n\n # test de pop() sans élément\n with self.assertRaises(ValueError):\n autoAdaptiveQueue.dequeue()\n self.assertTrue(autoAdaptiveQueue.isEmpty())\n\n # test de enqueue() sans élément\n item = 1\n autoAdaptiveQueue.enqueue(item)\n self.assertEqual(autoAdaptiveQueue.size(), 1)\n self.assertEqual(autoAdaptiveQueue.check(), item)\n\n # test de enqueue() avec un élément\n item2 = 2\n autoAdaptiveQueue.enqueue(item2)\n self.assertEqual(autoAdaptiveQueue.size(), max_size)\n self.assertEqual(autoAdaptiveQueue.liste[1], item2)\n\n # test de enqueue() au max de la capacité\n item3 = 3\n autoAdaptiveQueue.enqueue(item3)\n self.assertEqual(autoAdaptiveQueue.size(), max_size)\n self.assertEqual(autoAdaptiveQueue.trials, 1)\n self.assertEqual(autoAdaptiveQueue.waiting_list, [item3])\n\n # test de dequeue() au max de la capacité\n autoAdaptiveQueue.dequeue()\n self.assertEqual(autoAdaptiveQueue.size(), max_size)\n self.assertEqual(autoAdaptiveQueue.trials, 1)\n self.assertEqual(autoAdaptiveQueue.liste[1], item3)\n self.assertEqual(autoAdaptiveQueue.waiting_list, [])\n\n # test de enqueue() au max de la capacité\n item4 = 4\n autoAdaptiveQueue.enqueue(item4)\n self.assertEqual(autoAdaptiveQueue.size(), max_size)\n self.assertEqual(autoAdaptiveQueue.trials, 2)\n self.assertEqual(autoAdaptiveQueue.waiting_list, [item4])\n\n # test de enqueue() au max de la capacité de la liste et de la waiting list au max trial\n item5 = 5\n autoAdaptiveQueue.enqueue(item5)\n self.assertEqual(autoAdaptiveQueue.size(), 3)\n self.assertEqual(autoAdaptiveQueue.trials, 0)\n self.assertEqual(autoAdaptiveQueue.liste[0], item2)\n self.assertEqual(autoAdaptiveQueue.liste[1], item3)\n self.assertEqual(autoAdaptiveQueue.liste[2], item4)\n self.assertEqual(autoAdaptiveQueue.max_size, max_size + size_increment)\n\n def test_ScreenPrinter(self):\n name = \"My printer\"\n printer = ScreenPrinter(name)\n\n stack = Stack(5)\n stack.push(\"S1\")\n stack.push(\"S2\")\n stack.push(\"S3\")\n\n queue = Queue(5)\n queue.enqueue(\"Q1\")\n queue.enqueue(\"Q2\")\n queue.enqueue(\"Q3\")\n queue.enqueue(\"Q4\")\n queue.enqueue(\"Q5\")\n\n liste = List()\n liste.append(\"L1\")\n liste.append(\"L2\")\n liste.append(\"L3\")\n liste.append(\"L4\")\n\n # Test de screen printer avec une stack\n printer.visit(stack)\n\n # Test de screen printer avec une queue\n printer.visit(queue)\n\n # Test de screen printer avec une liste\n printer.visit(liste)\n\n def test_FilePrinter(self):\n file_path = \"E:/Cours/A3/Tests & validations/TP/TP6/MyFile.txt\"\n printer = FilePrinter(file_path, name=\"My name\")\n\n stack = Stack(5)\n stack.push(\"S1\")\n stack.push(\"S2\")\n stack.push(\"S3\")\n\n queue = Queue(5)\n queue.enqueue(\"Q1\")\n queue.enqueue(\"Q2\")\n queue.enqueue(\"Q3\")\n queue.enqueue(\"Q4\")\n queue.enqueue(\"Q5\")\n\n liste = List()\n liste.append(\"L1\")\n liste.append(\"L2\")\n liste.append(\"L3\")\n liste.append(\"L4\")\n\n # Test de file printer avec une stack\n printer.visit(stack)\n\n # Test de file printer avec une queue\n printer.visit(queue)\n\n # Test de file printer avec une liste\n printer.visit(liste)\n\n def test_Calculator(self):\n queue1 = Queue(2)\n queue1.enqueue('Q1')\n queue1.enqueue('Q2')\n queue2 = Queue(5)\n queue2.enqueue('Q3')\n queue2.enqueue('Q4')\n queue2.enqueue('Q5')\n queue3 = Queue(1)\n\n stack1 = Stack(3)\n stack1.push('S1')\n stack1.push('S2')\n stack1.push('S3')\n stack2 = Stack(4)\n stack2.push('S4')\n stack2.push('S5')\n stack2.push('S6')\n stack2.push('S7')\n stack3 = Stack(3)\n\n liste1 = List()\n liste1.append('L1')\n liste1.append('L2')\n liste2 = List()\n liste2.append('L3')\n liste2.append('L4')\n liste2.append('L5')\n liste2.append('L6')\n liste2.append('L7')\n liste2.append('L8')\n\n liste3 = List()\n liste3.append('L1')\n liste3.append('L2')\n liste3.append('L3')\n liste3.append('L4')\n liste3.append('L5')\n liste3.append('L6')\n liste4 = List()\n liste4.append('L7')\n liste4.append('L8')\n\n # Test de calculator avec deux queues dont la première non vide\n mergedQueue1 = Calculator.union(queue1, queue2)\n self.assertEqual(mergedQueue1.max_size, queue1.max_size + queue2.max_size)\n self.assertEqual(mergedQueue1.size(), 5)\n\n # Test de calculator avec deux queues dont la première vide\n mergedQueue2 = Calculator.union(queue3, queue2)\n self.assertEqual(mergedQueue2.max_size, queue3.max_size + queue2.max_size)\n self.assertEqual(mergedQueue2.size(), 3)\n\n # Test de calculator avec deux stacks dont la première non vide\n mergedStack1 = Calculator.union(stack1, stack2)\n self.assertEqual(mergedStack1.max_size, stack1.max_size + stack2.max_size)\n self.assertEqual(mergedStack1.size(), 7)\n\n # Test de calculator avec deux stacks dont la première vide\n mergedStack2 = Calculator.union(stack3, stack2)\n self.assertEqual(mergedStack2.max_size, stack3.max_size + stack2.max_size)\n self.assertEqual(mergedStack2.size(), 4)\n\n # Test de calculator avec deux listes (1ere plus grande pour passer dans la deuxième boucle)\n mergedListe1 = Calculator.union(liste1, liste2)\n self.assertEqual(mergedListe1.size(), 8)\n\n # Test de calculator avec deux listes (2nd plus grande pour passer dans la troisième boucle)\n mergedListe2 = Calculator.union(liste3, liste4)\n self.assertEqual(mergedListe2.size(), 8)\n\n # Test de calculator avec deux listes de type différents\n with self.assertRaises(ValueError):\n Calculator.union(liste1, stack1)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"TP6/Test_app.py","file_name":"Test_app.py","file_ext":"py","file_size_in_byte":12095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"97215488","text":"'''\r\n@author: Jan\r\n'''\r\n\r\nimport numpy as np\r\nfrom scipy.sparse import lil_matrix\r\nfrom scipy.special import polygamma\r\nfrom scipy.special import digamma as Digamma\r\nfrom scipy.special import gamma as Gamma\r\nfrom numpy.random import dirichlet as Dir\r\nfrom numpy.random import choice as Categorical\r\nimport sys\r\nfrom numpy.random import beta as Beta\r\nfrom numpy.linalg import inv\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import f1_score\r\n\r\nimport time\r\n\r\nLAST_UPDATE_TIME = time.time()\r\nUPDATE_TIME_GAP = 0.3\r\n\r\ndef printPercentage(curr, total):\r\n global LAST_UPDATE_TIME\r\n \r\n curr_time = time.time()\r\n if curr_time - LAST_UPDATE_TIME >= UPDATE_TIME_GAP:\r\n LAST_UPDATE_TIME = curr_time\r\n print(\"%s/%s sample rounds completed\" %(curr+1, total), flush = True, end = \"\\r\", file=sys.stdout)\r\n\r\nMIN_PARAM, MAX_PARAM = 0.0001, 1000\r\nUPDATE_GAP = 0.0001\r\n\r\ndef parseTruths(xt_map, currTruth, tasks):\r\n truths = []\r\n for task in tasks:\r\n taskTruth = currTruth[xt_map == task]\r\n if len(np.unique(taskTruth)) != 1:\r\n truths.append(-1)\r\n print(\"Wrong dataset, not identical truth for task %s\" %task)\r\n else:\r\n truths.append(np.unique(taskTruth)[0])\r\n \r\n return truths\r\n\r\ndef DDigamma(x): return polygamma(1, x)\r\n\r\ndef oneVec(k):\r\n return np.transpose(np.matrix([1] * k))\r\n\r\ndef oneVecT(k):\r\n return np.matrix([1] * k)\r\n\r\nclass GibbsEM():\r\n def __init__(self, K, L, s_alpha = 1, s_beta = 1):\r\n self.K, self.L = K, L\r\n self.s_alpha = s_alpha\r\n self.s_beta = s_beta\r\n self.alpha = np.array([s_alpha/K] * K)\r\n self.beta = np.array([s_beta/L] * L)\r\n \r\n \r\n \r\n def initvar(self, data):\r\n \r\n \r\n self.xLen = len(data)\r\n self.X = np.equal(data[:, 2], data[:, 3])\r\n \r\n self.tMap = data[:, 0].astype(int)\r\n self.tasks = np.unique(self.tMap).astype(int)\r\n self.tLen = len(self.tasks)\r\n self.tIndex = np.zeros(np.max(self.tasks) + 1, dtype = int)\r\n for tId in self.tasks:\r\n self.tIndex[tId] = np.where(self.tasks == tId)[0][0]\r\n \r\n self.uMap = data[:, 1].astype(int)\r\n self.workers = np.unique(self.uMap).astype(int)\r\n self.uLen = len(self.workers)\r\n self.uIndex = np.zeros(np.max(self.workers) + 1, dtype = int)\r\n for uId in self.workers:\r\n self.uIndex[uId] = np.where(self.workers == uId)[0][0]\r\n \r\n# self.tSlice = lil_matrix((self.tLen, self.xLen), dtype = bool)\r\n# for t in self.tasks:\r\n# self.tSlice[self.tIndex[t]] = (self.tMap == t)\r\n \r\n \r\n# self.uSlice = lil_matrix((self.uLen, self.xLen), dtype = bool)\r\n# for u in self.workers:\r\n# self.uSlice[self.uIndex[u]] = (self.uMap == u)\r\n \r\n self.ntk = np.zeros((self.tLen, self.K))\r\n self.nul = np.zeros((self.uLen, self.L))\r\n self.nklp = np.zeros((self.K, self.L, 2))\r\n \r\n self.Z = np.zeros(self.xLen, dtype = int)\r\n self.C = np.zeros(self.xLen, dtype = int)\r\n self.phi = Dir(self.alpha, self.tLen)\r\n self.theta = Dir(self.beta, self.uLen)\r\n self.psi = np.zeros((self.K, self.L))\r\n for task in self.tasks:\r\n currIndex = self.tIndex[task]\r\n currSlice = self.tMap == task\r\n zs = Categorical(self.K, len(self.Z[currSlice]), p = self.phi[currIndex])\r\n self.Z[currSlice] = zs\r\n \r\n self.ntk[currIndex, :np.max(zs) + 1] = np.bincount(zs)\r\n \r\n for worker in self.workers:\r\n currIndex = self.uIndex[worker]\r\n currSlice = self.uMap == worker\r\n cs = Categorical(self.L, len(self.C[currSlice]), p = self.theta[currIndex])\r\n self.C[currSlice] = cs\r\n \r\n self.nul[currIndex, : np.max(cs) + 1] = np.bincount(cs)\r\n \r\n for k in range(self.K):\r\n kSlice = self.Z == k\r\n for l in range(self.L):\r\n lSlice = self.C == l\r\n \r\n klSlice = np.bitwise_and(kSlice, lSlice)\r\n \r\n self.nklp[k, l] = np.bincount(self.X[klSlice])\r\n \r\n self.psi[k, l] = (self.nklp[k, l, 1] + 1) / (self.nklp[k, l, 0] + self.nklp[k, l, 1] + 2)\r\n \r\n \r\n def sample(self, allRounds, burninRounds):\r\n R = allRounds - burninRounds\r\n ntk_record = np.zeros((R, self.tLen, self.K))\r\n nul_record = np.zeros((R, self.uLen, self.L))\r\n nklp_record = np.zeros((R, self.K, self.L, 2))\r\n \r\n for curr_round in range(allRounds):\r\n# print(\"%s/%s\"%(curr_round, allRounds))\r\n printPercentage(curr_round, allRounds)\r\n \r\n r = curr_round - burninRounds\r\n for i in range(self.xLen):\r\n # update z_i\r\n curr_z, curr_c, curr_x = self.Z[i], self.C[i], int(self.X[i])\r\n curr_t, curr_u = self.tIndex[self.tMap[i]], self.uIndex[self.uMap[i]] \r\n \r\n self.ntk[curr_t, curr_z] -= 1\r\n self.nul[curr_u, curr_c] -= 1\r\n self.nklp[curr_z, curr_c, curr_x] -= 1\r\n \r\n a = (self.ntk[curr_t] + self.alpha) * np.eye(self.K)\r\n b = (self.nul[curr_u] + self.beta) * np.eye(self.L)\r\n \r\n if curr_x == 1:\r\n p = np.dot(np.dot(a, self.psi), b).flatten()\r\n if curr_x == 0:\r\n p = np.dot(np.dot(a, 1-self.psi), b).flatten()\r\n \r\n p /= np.sum(p)\r\n sampleKL = Categorical(self.K * self.L, 1, p = p)[0]\r\n \r\n next_z, next_c = int(sampleKL / self.L), sampleKL % self.L\r\n \r\n self.Z[i], self.C[i] = next_z, next_c\r\n self.ntk[curr_t, next_z] += 1\r\n self.nul[curr_u, next_c] += 1\r\n self.nklp[next_z, next_c, curr_x] += 1\r\n \r\n if r >= 0:\r\n ntk_record[r, :, :] = self.ntk \r\n nul_record[r, :, :] = self.nul\r\n nklp_record[r, :, :, :] = self.nklp\r\n \r\n curr_round += 1\r\n \r\n# f.write(\"%s %s\\n\" %(self.z, self.c))\r\n \r\n return ntk_record, nul_record, nklp_record\r\n \r\n def updateAlpha(self, ntk_record):\r\n R = len(ntk_record)\r\n def galpha(k):\r\n entry = [[ (Digamma(self.s_alpha) - Digamma(np.sum(ntk_record[r, t, :]) + self.s_alpha) \r\n + Digamma(ntk_record[r, t, k] + self.alpha[k]) - Digamma(self.alpha[k])) \r\n for t in range(self.tLen)] \r\n for r in range(R)]\r\n return np.sum(entry)\r\n \r\n \r\n flag = False\r\n preAlpha = None\r\n while True:\r\n if flag == True and np.mean(((preAlpha - self.alpha) / preAlpha)**2) <= UPDATE_GAP : break\r\n# if flag == True and (np.sum(self.alpha - MIN_PARAM) == 0 or np.sum(self.alpha - MAX_PARAM) == 0) : \r\n# self.alpha = np.array([MIN_PARAM] * self.K)\r\n# break\r\n# if count >= self.maxloop:\r\n# self.alpha = modifyParam(self.alpha)\r\n# self.s_alpha = np.sum(self.alpha)\r\n# break\r\n# else:\r\n# count += 1 \r\n flag = True\r\n preAlpha = self.alpha.copy()\r\n # updating alpha\r\n \r\n g = np.transpose(np.matrix([ galpha(k) for k in range(self.K)]))\r\n Q = np.zeros((self.K, self.K))\r\n for k in range(self.K):\r\n Q[k, k] = np.sum([[(DDigamma(ntk_record[r, t, k] + self.alpha[k]) - DDigamma(self.alpha[k])) \r\n for t in range(self.tLen)] \r\n for r in range(R)])\r\n z = np.sum([(DDigamma(self.s_alpha) - DDigamma(np.sum(ntk_record[r, t, :]) + self.s_alpha)) for r in range(R) for t in range(self.tLen)])\r\n H = np.matrix(Q) + oneVec(self.K) * oneVecT(self.K) * z\r\n \r\n breakFlag = False\r\n try:\r\n delta = np.array(np.transpose(inv(H)*g))[0, :]\r\n if len(delta[delta > 0.5*self.alpha]) > 0 or len(delta[delta < -1 *self.alpha]) > 0:\r\n delta[delta > 0.5*self.alpha] = 0.5 * self.alpha[delta > 0.5*self.alpha]\r\n delta[delta < -1 *self.alpha] = -1 * self.alpha[delta < -1 *self.alpha]\r\n breakFlag = True\r\n \r\n newAlpha = np.array(self.alpha - delta)\r\n if np.min(newAlpha) >= MIN_PARAM and np.max(newAlpha) <= MAX_PARAM:\r\n print(\"update Alpha: %s\" %newAlpha)\r\n self.alpha = newAlpha\r\n self.s_alpha = np.sum(self.alpha)\r\n except:\r\n breakFlag = True\r\n \r\n \r\n if breakFlag: break\r\n \r\n def updateBeta(self, nul_record):\r\n R = len(nul_record)\r\n def gbeta(l):\r\n entry = [[ (Digamma(self.s_beta) - Digamma(np.sum(nul_record[r, u, :]) + self.s_beta)\r\n + Digamma(nul_record[r, u, l] + self.beta[l]) - Digamma(self.beta[l]))\r\n for u in range(self.uLen)] \r\n for r in range(R)]\r\n return np.sum(entry)\r\n \r\n \r\n flag = False\r\n preBeta = None\r\n while True:\r\n if flag == True and np.mean(((preBeta - self.beta) / preBeta)**2) <= UPDATE_GAP : break\r\n# if flag == True and (np.sum(self.beta - MIN_PARAM) == 0 or np.sum(self.beta - MAX_PARAM) == 0) : \r\n# self.beta = np.array([MIN_PARAM] * self.L)\r\n# break\r\n# if count >= self.maxloop:\r\n# self.beta = modifyParam(self.beta)\r\n# self.s_beta = np.sum(self.beta)\r\n# break\r\n# else:\r\n# count += 1\r\n flag = True \r\n preBeta = self.beta.copy()\r\n # updating beta\r\n \r\n g = np.transpose(np.matrix([ gbeta(l) for l in range(self.L)]))\r\n Q = np.zeros((self.L, self.L))\r\n for l in range(self.L):\r\n Q[l, l] = np.sum([[(DDigamma(nul_record[r, u, l] + self.beta[l]) - DDigamma(self.beta[l])) \r\n for u in range(self.uLen)] \r\n for r in range(R)])\r\n z = np.sum([(DDigamma(self.s_beta) - DDigamma(np.sum(nul_record[r, u, :]) + self.s_beta)) for r in range(R) for u in range(self.uLen)])\r\n H = np.matrix(Q) + oneVec(self.L) * oneVecT(self.L) * z\r\n \r\n breakFlag = False\r\n try:\r\n delta = np.array(np.transpose(inv(H)*g))[0, :]\r\n if len(delta[delta > 0.5*self.beta]) > 0 or len(delta[delta < -1 *self.beta]) > 0:\r\n delta[delta > 0.5*self.beta] = 0.5 * self.beta[delta > 0.5*self.beta]\r\n delta[delta < -1 *self.beta] = -1 * self.beta[delta < -1 *self.beta]\r\n breakFlag = True\r\n newBeta = np.array(self.beta - delta)\r\n if np.min(newBeta) >= MIN_PARAM and np.max(newBeta) <= MAX_PARAM:\r\n print(\"update Beta: %s\" %newBeta)\r\n self.beta = newBeta\r\n self.s_beta = np.sum(self.beta)\r\n except:\r\n breakFlag = True\r\n \r\n if breakFlag: break\r\n \r\n def updatePsi(self, nklp_record):\r\n \r\n meanNklp = np.zeros((self.K, self.L, 2))\r\n for k in range(self.K):\r\n for l in range(self.L):\r\n meanNklp[k, l, 0] = np.mean(nklp_record[:, k, l, 0])\r\n meanNklp[k, l, 1] = np.mean(nklp_record[:, k, l, 1])\r\n self.psi[k, l] = (meanNklp[k, l, 1] + 1) / (meanNklp[k, l, 0] + meanNklp[k, l, 1] + 2)\r\n \r\n print(\"Current Psi: \\n%s\" %self.psi)\r\n \r\n BIC_psi = 0 \r\n logNegPsi = np.log(1-self.psi)\r\n logPsi = np.log(self.psi)\r\n for k in range(self.K):\r\n for l in range(self.L):\r\n BIC_psi += meanNklp[k, l, 0] * logNegPsi[k, l] + meanNklp[k, l, 1] * logPsi[k, l]\r\n \r\n return BIC_psi\r\n \r\n \r\n def computeBIC(self):\r\n loglikehood = 0\r\n for i in range(self.xLen):\r\n curr_t = self.tIndex[self.tMap[i]]\r\n curr_u = self.uIndex[self.uMap[i]]\r\n curr_x = self.X[i]\r\n \r\n pxi = 0\r\n for k in range(self.K):\r\n for l in range(self.L):\r\n pxi += self.phi[curr_t, k] * self.theta[curr_u, l] * self.psi[k, l]**curr_x * (1-self.psi[k, l])**(1-curr_x)\r\n loglikehood += np.log(pxi)\r\n \r\n# loglikehood *= self.tLen * self.uLen / self.xLen\r\n# return np.log(self.xLen) * (self.K * (self.tLen + 1) + self.L * (self.uLen + 1) + self.K * self.L) - 2 * looglikehood\r\n# return np.log(self.tLen)*(self.K * self.uLen) + np.log(self.uLen) *(self.L * self.tLen) - 2 * looglikehood\r\n return np.log(self.xLen)*(self.K * self.L) + np.log(self.tLen) * self.K *self.L + np.log(self.uLen) * self.K * self.L - 2 * loglikehood\r\n \r\n# return np.log(self.tLen * self.uLen)*(self.K * self.L) + np.log(self.tLen) * self.K + np.log(self.uLen) * self.L - 2 * loglikehood\r\n# return np.log(self.tLen)*(self.uLen * self.K) + np.log(self.uLen) * (self.tLen * self.L) - 2 * loglikehood\r\n \r\n# return np.log(2) * self.K * self.L + np.log(self.tLen) * self.K + np.log(self.uLen) * self.L - 2 * looglikehood\r\n \r\n #trainData -- (X, 4); testData -- (X, 3)\r\n def fit(self, data, allRounds, burninRounds):\r\n \r\n self.initvar(data)\r\n \r\n previousBIC = None\r\n currentBIC = None\r\n \r\n max_round = 40\r\n min_round = 1\r\n curr_round = 0\r\n \r\n while True:\r\n curr_round += 1\r\n# \r\n ntk_record, nul_record, nklp_record = self.sample(allRounds, burninRounds)\r\n \r\n pre_phi, pre_theta, pre_psi = self.phi.copy(), self.theta.copy(), self.psi.copy()\r\n pre_alpha, pre_beta = self.alpha.copy(), self.beta.copy()\r\n \r\n if self.K != 1:\r\n self.updateAlpha(ntk_record)\r\n \r\n if self.L != 1:\r\n self.updateBeta(nul_record)\r\n \r\n for t in range(self.tLen):\r\n for k in range(self.K):\r\n self.phi[t, k] = (np.mean(ntk_record[:, t, k]) + self.alpha[k]) / (np.mean(np.sum(ntk_record[:, t, :], axis = 1)) + self.s_alpha)\r\n \r\n for u in range(self.uLen):\r\n for l in range(self.L):\r\n self.theta[u, l] = (np.mean(nul_record[:, u, l]) + self.beta[l]) / (np.mean(np.sum(nul_record[:, u, :], axis = 1)) + self.s_beta)\r\n \r\n self.updatePsi(nklp_record)\r\n \r\n \r\n currentBIC = self.computeBIC()\r\n \r\n# if previousBIC != None and (previousBIC - BIC) < 0.1:\r\n# break\r\n# else:\r\n# previousBIC = BIC \r\n print(\"Current BIC: %s\" %currentBIC)\r\n if curr_round > min_round and previousBIC != None and currentBIC >= previousBIC:\r\n self.alpha, self.beta = pre_alpha, pre_beta\r\n self.phi, self.theta, self.psi = pre_phi, pre_theta, pre_psi\r\n return previousBIC\r\n if curr_round >= max_round: break\r\n \r\n previousBIC = currentBIC\r\n \r\n return currentBIC\r\n \r\n\r\n def generateDataset(self, outputFile, taskNum = 20):\r\n outFile = open(outputFile, \"w\")\r\n \r\n taskNumbase = np.max(self.tasks) + 1\r\n for i in range(taskNum):\r\n phi = Dir(self.alpha, self.tLen)[0]\r\n for worker in self.workers:\r\n currIndex = self.uIndex[worker]\r\n tc = Categorical(self.K, 1, p = phi)[0]\r\n uc = Categorical(self.L, 1, p = self.theta[currIndex])[0]\r\n \r\n corr = Categorical(2, 1, p = [1-self.psi[tc, uc], self.psi[tc, uc]])[0]\r\n \r\n outFile.write(\"%s %s %s\\n\" %(taskNumbase + i, worker, corr))\r\n \r\n outFile.close()\r\n \r\n\r\nif __name__ == \"__main__\":\r\n np.set_printoptions(suppress=True)\r\n np.set_printoptions(precision=3)\r\n \r\n #for bluebird\r\n fileName = \"temp\"\r\n file = \"../data/dataset/parsed/%s\" %fileName\r\n# file = \"../data/dataset/parsed/bluebird\"\r\n \r\n data = np.loadtxt(file, dtype = int)\r\n \r\n \r\n minK, maxK = 1, 2\r\n minL, maxL = 2, 3\r\n bics = np.zeros((maxK - minK + 1, maxL - minL + 1))\r\n \r\n bicRuntimes = 1\r\n \r\n fitRounds, fitBurnin = 50, 30\r\n genRounds, genBurnin = 500, 300\r\n minScore = None\r\n bestParamkl = (1,3)\r\n bestParamAlpha = [0.1/3]*3\r\n bestParamBeta = [0.1/4]*4\r\n bestParamPsi = None\r\n for k in range(minK, maxK + 1):\r\n for l in range(minL, maxL + 1):\r\n bic = 0\r\n for i in range(bicRuntimes):\r\n model = GibbsEM(k,l)\r\n roundBic = model.fit(data, fitRounds, fitBurnin )\r\n bic += roundBic / bicRuntimes\r\n print(\"round %s, bic %s\" %(i, roundBic))\r\n \r\n bics[k - minK, l - minL] = bic\r\n \r\n if minScore == None or minScore > bic:\r\n minScore = bic\r\n bestParamkl = (k, l)\r\n bestParamAlpha = model.alpha.copy()\r\n bestParamBeta = model.beta.copy()\r\n bestParamPsi = model.psi.copy()\r\n print(\"============================================================\")\r\n print(\"current minimum bic: %s; (k, l)=%s\" %(minScore, bestParamkl))\r\n print(\"best alpha: %s\" %bestParamAlpha)\r\n print(\"best beta: %s\" %bestParamBeta)\r\n print(\"best psi: \\n%s\" %bestParamPsi)\r\n print(\"current bics:\\n%s\" %bics)\r\n print(\"============================================================\")\r\n \r\n print(\"============================================================\")\r\n print(\"all bics:\\n%s\" %bics)\r\n print(\"============================================================\")\r\n# \r\n bestK, bestL = bestParamkl\r\n paramFile = open(\"../data/dataset/evaluation/%s-param\" %fileName, \"w\")\r\n print(\"best kl: %s, %s\" %(bestK, bestL), file = paramFile)\r\n print(\"best alpha: %s\" %bestParamAlpha, file = paramFile)\r\n print(\"best beta: %s\" %bestParamBeta, file = paramFile)\r\n print(\"best psi:\\n%s\" %bestParamPsi, file = paramFile)\r\n print(\"all bics:\\n%s\" %bics, file = paramFile)\r\n paramFile.close()\r\n \r\n \r\n model = GibbsEM(*bestParamkl)\r\n model.fit(data, genRounds, genBurnin)\r\n for i in range(10):\r\n model.generateDataset(\"../data/dataset/evaluation/%s@20-%s\" %(fileName, i), 20)\r\n model.generateDataset(\"../data/dataset/evaluation/%s@40-%s\" %(fileName, i), 40)\r\n model.generateDataset(\"../data/dataset/evaluation/%s@60-%s\" %(fileName, i), 60)\r\n \r\n \r\n# #for bluebird\r\n# file = \"../data/dataset/bluebird@20.test\"\r\n# \r\n# data = np.loadtxt(file, dtype = int)\r\n# \r\n# minScore = None\r\n# bestParam = (3,4)\r\n# for k in range(2, 5):\r\n# for l in range(2, 5):\r\n# model = GibbsEM(k,l)\r\n# bic = model.fit(data, 50, 30)\r\n# if minScore == None or minScore > bic:\r\n# minScore = bic\r\n# bestParam = (k, l)\r\n# \r\n# print(\"minimum bic: %s; (k, l)=%s\" %(minScore, bestParam))\r\n# \r\n# model = GibbsEM(*bestParam)\r\n# model.fit(data, 200, 100)\r\n# model.generateDataset(\"../data/dataset/bluebird@20.train\", 20)\r\n# model.generateDataset(\"../data/dataset/bluebird@40.train\", 40)\r\n ","sub_path":"CoClus/GibbsEMBootstrap.py","file_name":"GibbsEMBootstrap.py","file_ext":"py","file_size_in_byte":20292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"251313923","text":"import random\r\n\r\nclass Kvadrat(object):\r\n\r\n def __init__(self, broj = 0):\r\n self.__broj = broj\r\n self.__otkriven = False\r\n self.__oznaka = False\r\n\r\n def otkrij(self):\r\n if self.__otkriven == False and self.__oznaka == False:\r\n self.__otkriven = True\r\n\r\n def oznaci(self):\r\n if self.__oznaka == False :\r\n self.__oznaka = True\r\n else:\r\n self.__oznaka = False\r\n\r\n @property\r\n def jeMina(self):\r\n if self.__broj == -1:\r\n return True\r\n else:\r\n return False\r\n\r\n @property\r\n def jeBroj(self):\r\n if self.__broj != 0 and self.__broj !=-1:\r\n return True\r\n else:\r\n return False\r\n\r\n @property\r\n def jePrazan(self):\r\n if self.__broj ==0:\r\n return True\r\n else:\r\n return False\r\n\r\n def __str__(self):\r\n if self.__oznaka == True:\r\n return \"?\"\r\n if self.__otkriven == False:\r\n return \".\"\r\n else:\r\n if self.jeMina == True:\r\n return \"x\"\r\n if self.jeBroj == True:\r\n return \"%d\" % self.__broj\r\n if self.jePrazan == True:\r\n return \" \"\r\n\r\nclass Polje(object):\r\n\r\n def __init__(self, velicina, broj_mina):\r\n self.__velicina = velicina\r\n self.__broj_mina = broj_mina\r\n self.__kvadrati = [[Kvadrat() for j in range(velicina)] for i in range(velicina)]\r\n\r\n for mine in range(broj_mina):\r\n random_num = random.randrange(velicina ** 2)\r\n j = random_num // velicina\r\n i = random_num % velicina\r\n\r\n self.__kvadrati[j][i] = Kvadrat(-1)\r\n\r\n for j in range(velicina):\r\n for i in range(velicina):\r\n if self.__kvadrati[j][i].jeMina:\r\n continue\r\n\r\n br_mina = 0\r\n\r\n for brojac in [-1, 0, 1]:\r\n red1 = self.provjeriMine(j - 1, i + brojac)\r\n red2 = self.provjeriMine(j, i + brojac)\r\n red3 = self.provjeriMine(j + 1, i + brojac)\r\n\r\n if (red1 == -1):\r\n br_mina += 1\r\n if (red2 == -1):\r\n br_mina += 1\r\n if (red3 == -1):\r\n br_mina += 1\r\n\r\n self.__kvadrati[j][i] = Kvadrat(br_mina)\r\n\r\n def provjeriMine(self, x, y):\r\n if x >= 0 and y >= 0 and x < self.__velicina and y < self.__velicina:\r\n if self.__kvadrati[x][y].jeMina:\r\n return -1\r\n else:\r\n return 0\r\n\r\n def __str__(self):\r\n output = \" 1 2 3 4 5\\n -----------\"\r\n for j in range(self.__velicina):\r\n output += \"\\n\" + str(j + 1) + \"| \"\r\n for i in range(self.__velicina):\r\n output += str(self.__kvadrati[j][i]) + \" \"\r\n output +=\"|\"\r\n\r\n output += \"\\n ----------\"\r\n\r\n return output\r\n\r\n\r\nprint('*** test 1 ***')\r\nprint('*** rezultat varira zbog slucajnog izbora mina koristenjem random modula ***')\r\np = Polje(5,2)\r\nfor red in p._Polje__kvadrati:\r\n for k in red:\r\n k.otkrij()\r\n print(k, end = '|')\r\n print()\r\n\r\nprint('*** test 2 ***')\r\nprint('*** rezultat varira zbog slucajnog izbora mina koristenjem random modula ***')\r\np = Polje(5,2)\r\nfor red in p._Polje__kvadrati:\r\n for k in red:\r\n k.otkrij()\r\nprint(p)","sub_path":"zada9-master/zada9-master/Mine.py","file_name":"Mine.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"617817189","text":"import io\r\n\r\n__author__ = 'Amaia Eskisabel'\r\n\r\nimport urllib.request\r\nimport json\r\n\r\n# moduleFileManagement.py\r\n\r\nclass FileManagement:\r\n\r\n def readFile (self, promptFile):\r\n file = promptFile\r\n return file\r\n\r\n def parseFileJSON (self, f):\r\n try:\r\n file = open(f, \"r\")\r\n except IOError as err:\r\n print(\"Cannot open file\", file)\r\n else:\r\n strJSON = json.load(file)\r\n file.close()\r\n return strJSON\r\n\r\n def parseUrlJSON (self, url):\r\n response = urllib.request.urlopen(url);\r\n da = response.read()\r\n data = json.loads(da.decode())\r\n return data\r\n\r\n def getDataFiles(self,needle, fileManifest):\r\n file = []\r\n for item in fileManifest[\"tests\"]:\r\n url = self.parseUrlJSON(item[\"quizz\"])\r\n file.append(url)\r\n return file\r\n\r\n def createFile (self, results):\r\n f1 = open(\"files/Scores.json\", \"r+\")\r\n f1.write(json.dumps(results,sort_keys=True))\r\n f1.close()","sub_path":"src/FileManagement.py","file_name":"FileManagement.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"98404210","text":"import json\nimport threading\nimport socket\nimport time\ntry:\n import Common.MyEnum as MyEnum\n import Common.MyParser as MyParser\n import Apply.Coordinator.ParseCor as ParseCor\nexcept ImportError:\n import MyEnum\n import MyParser\n import ParseCor\n\nDEBUG = True\nCONSTAN_EPS = 1\nNON_CONSTAN_EPS = 0\n\nMODE_EPS = NON_CONSTAN_EPS\neps = 0 # epsilon\next = str('')\n# init arguments\nDELTA_K = 3\nk = 4 + DELTA_K # number elements in top\nh1 = 1 # Coefficient of the 1st element in integrative function\nh2 = 1 # Coefficient of the 2nd element in integrative function\nh3 = 1 # Coefficient of the 3rd element in integrative function\nsession = 0 # the number of session\nband = 30 # limit bandwidth\n\ncurrentBand = 0\ncurrentK = 0\nnetIn = 0\nnetOut = 0\n\n#value and name of top elements\ntopK = []\nnameTop = []\n\nlstSock = []\nlstName = []\n\n#to check whether an user connnects to\nbUserConnect = False\n\nIP_SERVER = 'localhost'\nPORT_NODE = 9407\nPORT_USER = 7021\nMAX_NUMBER_NODE = 50\nDELTA_BAND = int(band / 10)\nDELTA_EPS = 1\nFILE_MON_NET = 'data/NetWorkLoad_'+ ext+'.dat'\nFILE_MON_TOP = 'data/Top_' + ext + '.dat'\n\nNUM_MONITOR = 120\n\n#interval to update network load\nTIME_CAL_NETWORK = 3.0\n\n################################################################################\ndef addNetworkIn(value:int):\n global netIn\n global lockNetIn\n lockNetIn.acquire()\n netIn += value\n lockNetIn.release()\n\ndef addNetworkOut(value:int):\n global netOut\n global lockNetOut\n lockNetOut.acquire()\n netOut += value\n lockNetOut.release()\n\ndef sendEPS(value:int):\n global DEBUG\n printTop()\n if (DEBUG):\n print('eps = %d' %(value))\n global lockLst\n data = createMessage('', {'-type': MyEnum.MonNode.SERVER_SET_ARG.value})\n data = createMessage(data, {'-eps': value})\n for s in lstSock:\n try:\n s.sendall(bytes(data.encode()))\n addNetworkOut(len(data))\n except socket.error:\n pass\n\ndef saveNetworkLoad(currentBand, eps):\n global lockTop\n tmp = eps\n if (tmp <= DELTA_EPS):\n tmp = 0\n\n with open(FILE_MON_TOP, 'a') as f1:\n lockTop.acquire()\n i = 0\n for i in range(k - DELTA_K - 1, -1, -1):\n if (topK[i] != 0):\n break\n if (i >= 0 and topK[i] != 0):\n f1.write(str(topK[i]) + ' ')\n for j in range(0, i + 1):\n f1.write(nameTop[j] + ' ')\n f1.write('\\n')\n lockTop.release()\n\n with open(FILE_MON_NET, 'a') as f:\n f.write(str(currentBand) + ' ' + str(tmp) + '\\n')\n\ndef monNetwork():\n global lockNetIn\n global lockNetOut\n global netIn\n global netOut\n global eps\n global countNode, DEBUG, MODE_EPS\n countTime = 0\n BOUND_RESTART = 3\n\n oldEps = 0\n countCir = 0 # count the number circle that total of network is greater than the bandwidth limit\n while 1:\n time.sleep(TIME_CAL_NETWORK)\n lockNetIn.acquire()\n nIn = netIn / TIME_CAL_NETWORK\n netIn = 0\n lockNetIn.release()\n\n lockNetOut.acquire()\n nOut = netOut / TIME_CAL_NETWORK\n netOut = 0\n lockNetOut.release()\n\n if DEBUG:\n print('netIn = %.2f _________ netOut = %.2f_____eps = %d' %(nIn, nOut, eps) )\n\n if (countNode > 0):\n countTime += 1\n print('CountTime = %d' %(countTime))\n if (countTime <= NUM_MONITOR):\n saveNetworkLoad(int(nIn) + int(nOut), eps)\n\n if (MODE_EPS != CONSTAN_EPS):\n if (eps < DELTA_EPS):\n eps = DELTA_EPS\n if (nIn + nOut < band - DELTA_BAND):\n countCir += 1\n if (countCir >= BOUND_RESTART):\n countCir = 0\n if (eps <= DELTA_EPS):\n eps = DELTA_EPS\n oldEps = 0\n countCir = 0\n continue\n if (eps - oldEps <= DELTA_EPS):\n oldEps = eps\n eps = int(eps / 2)\n if (eps < DELTA_EPS):\n eps = DELTA_EPS\n sendEPS(0)\n else:\n sendEPS(eps)\n continue\n eps = int ((eps + oldEps) / 2)\n sendEPS(eps)\n\n elif (nIn + nOut > band + DELTA_BAND):\n countCir -= 1\n if (countCir < -BOUND_RESTART):\n countCir = 0\n oldEps = eps\n eps *= 2\n sendEPS(eps)\n else:\n if (countCir < 0):\n countCir += 1\n elif (countCir > 0):\n countCir -= 1\n\n################################################################################\ndef swap(i:int, j:int):\n tmp = topK[i]\n topK[i] = topK[j]\n topK[j] = tmp\n\n tmp = nameTop[i]\n nameTop[i] = nameTop[j]\n nameTop[j] = tmp\n\ndef createMessage(strRoot = '', arg = {}):\n strResult = str(strRoot)\n for k, v in arg.items():\n strResult = strResult + ' ' + str(k) + ' ' + str(v)\n\n return strResult\n\n#return index of node in topK list if the node is in the list, else, return -1\ndef findNodeInTop(strname : str):\n global lockTop\n iRet = -1\n lockTop.acquire()\n for i in range(len(topK)):\n if (nameTop[i] == strname):\n iRet = i\n break\n lockTop.release()\n return iRet\n\ndef sendAllNode(data: str):\n global lockLst\n for s in lstSock:\n try:\n s.sendall(bytes(data.encode()))\n addNetworkOut(len(data))\n except socket.error:\n pass\n\ndef forceGetData(bound:int):\n global eps\n if (eps <= DELTA_EPS):\n return\n data = createMessage('', {'-type':MyEnum.MonNode.SERVER_GET_DATA.value})\n data = createMessage(data, {'-bound':bound})\n sendAllNode(data)\n\ndef readConfig(fName : str):\n global DEBUG, MODE_EPS, eps, DELTA_K, k, h1, h2, h3, band, IP_SERVER, PORT_NODE, FILE_MON_TOP\n global PORT_USER, MAX_NUMBER_NODE, DELTA_BAND, DELTA_EPS, FILE_MON_NET, NUM_MONITOR, TIME_CAL_NETWORK\n\n arg = ParseCor.readConfig(fName)\n if (arg == None):\n return\n\n DEBUG = arg.DEBUG\n MODE_EPS = arg.MODE_EPS\n eps = arg.eps\n ext = arg.ext\n DELTA_K = arg.DELTA_K\n k = arg.k + DELTA_K\n h1 = arg.h1\n h2 = arg.h2\n h3 = arg.h3\n band = arg.band\n IP_SERVER = arg.IP_SERVER\n MAX_NUMBER_NODE = arg.MAX_NUMBER_NODE\n DELTA_BAND = int(band / 10)\n DELTA_EPS = arg.DELTA_EPS\n FILE_MON_NET = 'data/NetWorkLoad_'+ ext+'.dat'\n FILE_MON_TOP = 'data/Top_' + ext + '.dat'\n NUM_MONITOR = arg.NUM_MONITOR\n TIME_CAL_NETWORK = arg.TIME_CAL_NETWORK\n\ndef init():\n global serverForNode, serverForUser\n global lockCount, lockLst, lockTop, lockNetIn, lockNetOut\n global parser, k\n\n try:\n readConfig('config/corConfig.cfg')\n except Exception:\n pass\n\n for i in range(k):\n topK.append(0)\n nameTop.append(\"\")\n\n #init server to listen monitor node\n serverForNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serverForNode.bind((IP_SERVER, PORT_NODE))\n serverForNode.listen(MAX_NUMBER_NODE)\n\n #init server to listen user node\n serverForUser = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serverForUser.bind((IP_SERVER, PORT_USER))\n serverForUser.listen(1)\n\n #init synchronize variable\n lockCount = threading.Lock()\n lockLst = threading.Lock()\n lockTop = threading.Lock()\n lockNetIn = threading.Lock()\n lockNetOut = threading.Lock()\n\n #init argument parser\n parser = MyParser.createParser()\n\n #delete old file\n f = open(FILE_MON_NET, 'w')\n f.close()\n f = open(FILE_MON_TOP, 'w')\n f.close()\n\ndef printTop():\n global userSock, eps, lockTop, DEBUG, DELTA_K, k\n epsTmp = eps\n if (epsTmp <= DELTA_EPS):\n epsTmp = 0\n rTop = []\n rName = []\n\n lockTop.acquire()\n\n for i in range(k - DELTA_K):\n if (nameTop[i] == ''):\n break\n rTop.append(topK[i])\n rName.append(nameTop[i])\n\n lockTop.release()\n\n data = json.dumps([rTop, rName, epsTmp])\n if (DEBUG):\n print(data)\n\n try:\n userSock.sendall(data.encode())\n except Exception:\n return\n\n################################################################################\n#add new element in top\ndef addToTopK(value: int, name: str):\n global lockTop, currentK, k\n d = 0\n c = currentK - 1\n g = int((d + c) /2)\n\n lockTop.acquire()\n while (d <= c):\n if (topK[g] > value):\n d = g + 1\n elif (topK[g] < value):\n c = g - 1\n else:\n break\n g = int((d + c) / 2)\n\n g = d\n for i in range(k-1, g, -1):\n topK[i] = topK[i-1]\n nameTop[i] = nameTop[i-1]\n\n topK[g] = value\n nameTop[g] = name\n lockTop.release()\n if (currentK < k):\n currentK += 1\n\n printTop()\n\n#change the order of the element in top\ndef changeOrderInTop(value : int, iNodeInTop: int) :\n global lockTop\n global countNode, currentK, DELTA_K, k\n if (value > topK[iNodeInTop]):\n # pull up\n lockTop.acquire()\n topK[iNodeInTop] = value\n while (iNodeInTop > 0 and value > topK[iNodeInTop - 1]):\n iNodeInTop -= 1\n swap(iNodeInTop, iNodeInTop + 1)\n lockTop.release()\n printTop()\n return\n\n if (value < topK[iNodeInTop]):\n #pull down\n lockTop.acquire()\n topK[iNodeInTop] = value\n while (iNodeInTop < k -1 and value < topK[iNodeInTop + 1]):\n iNodeInTop += 1\n swap(iNodeInTop, iNodeInTop - 1)\n\n # call all node to get lastest data if the value k-th element decreases\n if (iNodeInTop == currentK - 1 and countNode > currentK):\n if (currentK <= k - DELTA_K ):\n lockTop.release()\n forceGetData(0)\n else:\n topK[iNodeInTop] = 0\n nameTop[iNodeInTop] = ''\n currentK -= 1\n lockTop.release()\n else:\n lockTop.release()\n\n printTop()\n return\n\ndef updateTopK(value:int, name : str):\n nameNode = name\n iNodeInTop = findNodeInTop(nameNode)\n # this change doesn't effect to top\n if (iNodeInTop == -1 and value < topK[k-1]):\n return\n\n #an element out Top goes in Top\n if (iNodeInTop == -1 and value > topK[k - 1]):\n addToTopK(value, name)\n return\n\n changeOrderInTop(value, iNodeInTop)\n\n#remove the node that is disconnected\ndef removeInTop(strName:str):\n global lockTop, currentK, DELTA_K, k\n\n iIndex = findNodeInTop(strName)\n if (iIndex == -1):\n return\n lockTop.acquire()\n for i in range(iIndex, k-1):\n swap(i, i+ 1)\n topK[k-1] = 0\n nameTop[k-1] = ''\n currentK -= 1\n lockTop.release()\n if (currentK < k - DELTA_K - 1):\n forceGetData(0)\n printTop()\n pass\n\ndef updateArg(arg):\n global h1, h2, h3, band, k, lockTop, session, DELTA_BAND, DELTA_K, currentK\n dataSend = ''\n\n if (arg.h1 != None):\n h1 = arg.h1[0]\n dataSend = createMessage(dataSend, {'-h1':h1})\n\n if (arg.h2 != None):\n h2 = arg.h2[0]\n dataSend = createMessage(dataSend, {'-h2': h2})\n\n if (arg.h3 != None):\n h3 = arg.h3[0]\n dataSend = createMessage(dataSend, {'-h3': h3})\n\n if (arg.band != None):\n band = arg.band[0]\n DELTA_BAND = int(band / 10)\n\n if (arg.k != None):\n newK = arg.k[0]\n newK += DELTA_K\n if (newK < k):\n lockTop.acquire()\n for i in range(k - newK):\n topK.pop(newK)\n nameTop.pop(newK)\n k = newK\n if (currentK > k):\n currentK = k\n lockTop.release()\n if (newK > k):\n lockTop.acquire()\n for i in range(newK - k):\n topK.append(0)\n nameTop.append('')\n k = newK\n lockTop.release()\n if (dataSend == ''):\n forceGetData(0)\n return\n\n if (dataSend != ''):\n session += 1\n dataSend = createMessage(dataSend, {'-ses' : session})\n dataSend = createMessage(dataSend, {'-type': MyEnum.MonNode.SERVER_SET_ARG.value})\n sendAllNode(dataSend)\n\n################################################################################\ndef workWithNode(s : socket.socket, address):\n global countNode\n global lockCount\n global lockLst, eps\n\n try:\n #receive name\n dataRecv = s.recv(1024).decode()\n addNetworkIn(len(dataRecv))\n try:\n if (dataRecv != ''):\n arg = parser.parse_args(dataRecv.lstrip().split(' '))\n nameNode = arg.name[0]\n nameNode = str(address).replace(' ', '') + nameNode\n except socket.error:\n return\n except Exception:\n pass\n\n lockLst.acquire()\n lstSock.append(s)\n lstName.append(nameNode)\n lockLst.release()\n\n #send coefficient, lower bound, epsilon\n dataSend = createMessage('', {'-h1':h1})\n dataSend = createMessage(dataSend, {'-h2': h2})\n dataSend = createMessage(dataSend, {'-h3': h3})\n dataSend = createMessage(dataSend, {'-bound': topK[k - 1]})\n tmp = eps\n if (eps <= DELTA_EPS):\n tmp = 0\n dataSend = createMessage(dataSend, {'-eps': tmp})\n dataSend = createMessage(dataSend, {'-ses': session})\n dataSend = createMessage(dataSend, {'-type': MyEnum.MonNode.SERVER_SET_ARG.value})\n s.sendall(bytes(dataSend.encode('utf-8')))\n addNetworkOut(len(dataSend))\n\n #receive current value\n while 1:\n try:\n dataRecv = s.recv(1024).decode()\n addNetworkIn(len(dataRecv))\n if (dataRecv != ''):\n arg = parser.parse_args(dataRecv.lstrip().split(' '))\n nodeSession = arg.session[0]\n nodeValue = arg.value[0]\n if (nodeSession == session):\n updateTopK(nodeValue, nameNode)\n else:\n return\n\n except socket.error:\n return\n except Exception:\n continue\n\n except socket.error:\n pass\n\n finally:\n s.close()\n lockLst.acquire()\n lstSock.remove(s)\n lstName.remove(nameNode)\n removeInTop(nameNode)\n lockLst.release()\n\n lockCount.acquire()\n countNode -= 1\n lockCount.release()\n\ndef acceptNode(server):\n global countNode\n global lockCount\n countNode = 0\n while (1):\n print('%d\\n' %(countNode))\n if (countNode >= MAX_NUMBER_NODE):\n time.sleep(1)\n continue\n\n (nodeSock, addNode) = server.accept()\n\n lockCount.acquire()\n countNode += 1\n lockCount.release()\n\n threading.Thread(target=workWithNode, args=(nodeSock, addNode,)).start()\n################################################################################\ndef acceptUser(server : socket.socket):\n global userSock\n while (1):\n (userSock, addressUser) = server.accept()\n workWithUser(userSock)\n\ndef workWithUser(s : socket.socket):\n global parser\n global bUserConnect\n bUserConnect = True\n printTop()\n try:\n while 1:\n dataRecv = s.recv(1024).decode()\n if (dataRecv == ''):\n return\n arg = parser.parse_args(dataRecv.lstrip().split(' '))\n type = arg.type[0]\n if (type == MyEnum.User.USER_SET_ARG.value):\n updateArg(arg)\n except socket.error:\n return\n finally:\n bUserConnect = False\n s.close()\n\n################################################################################\n################################################################################\n\ninit()\n\n# create thread for each server\nthNode = threading.Thread(target=acceptNode, args=(serverForNode,))\nthNode.start()\n\nthMon = threading.Thread(target=monNetwork, args=())\nthMon.start()\n\nthUser = threading.Thread(target=acceptUser, args=(serverForUser,))\nthUser.start()\n\ntry:\n #wait for all thread terminate\n thNode.join()\n thMon.join()\n\n thUser.join()\nexcept KeyboardInterrupt:\n serverForNode.close()\n serverForUser.close()","sub_path":"Apply/Coordinator/Coordinator.py","file_name":"Coordinator.py","file_ext":"py","file_size_in_byte":16593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"166260835","text":"\n\n#calss header\nclass _INDENTATION():\n\tdef __init__(self,): \n\t\tself.name = \"INDENTATION\"\n\t\tself.definitions = [u'a hole or mark on the surface of something: ', u'a space left at the edge of a line of writing, or the process of leaving such a space']\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/_indentation.py","file_name":"_indentation.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"510115466","text":"#!/usr/bin/env python3\n\n\nimport xml.etree.ElementTree as ET\nimport json\n\ntree = ET.parse('doc.kml')\nroot = tree.getroot()\n\nplacemarks = root.findall('.//Folder/Placemark')\n\nplacemark_data = []\n\nfor i, placemark in enumerate(placemarks):\n data = {\n 'title': placemark.find('name').text,\n }\n coordinates = placemark.find('Point/coordinates').text\n lng, lat, _ = coordinates.split(',')\n position = {\n 'lng': float(lng),\n 'lat': float(lat),\n }\n data['position'] = position\n placemark_data.append(data)\n\nprint(\"var wwtps = \")\nprint(json.dumps(placemark_data, sort_keys=True, indent=2))\n","sub_path":"placemark_to_js.py","file_name":"placemark_to_js.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"48468900","text":"#!/usr/bin/env python\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport time\nimport requests\nimport MySQLdb as my\nimport json\nimport sys\n\ndb = my.connect(host=\"127.0.0.1\",\n user=\"saurabh\",\n passwd=\"saurabh\",\n db=\"rental\"\n )\n\nstart = time.time()\nsource1 = '99_acres'\n\ndata = []\n\n\ndef insert_bangalore_locality():\n city1 = 'Bangalore'\n bangalore_region = ['central-ffid', 'east-ffid', 'west-ffid', 'north-ffid', 'south-ffid']\n base_url = \"https://www.99acres.com/rent-property-in-bangalore-\"\n\n for num in range(0, bangalore_region.__len__()):\n new_url = str(base_url) + str(bangalore_region[num])\n page = requests.get(new_url)\n print(page.status_code)\n time.sleep(30)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n locality = []\n id = []\n city = []\n region = []\n exp = soup.find_all('input', attrs={\"id\": \"filter_data\"})\n abc = exp[0].get('value') # len(exp) = 1\n result = json.loads(str(abc))\n # get Top_Results_Array\n for i in range(0, (result['Locality']['Top_Results_Array'].__len__())):\n city.append(city1)\n region.append(bangalore_region[num].replace(\"-ffid\", \"\"))\n id.append((result['Locality']['Top_Results_Array'][str(i)]['ID']))\n locality.append((result['Locality']['Top_Results_Array'][str(i)]['LABEL']))\n\n # get More_Locality_Array\n for j in range(0, (result['Locality']['More_Locality_Array'].__len__())):\n city.append(city1)\n region.append(bangalore_region[num].replace(\"-ffid\", \"\"))\n id.append((result['Locality']['More_Locality_Array'][str(j)]['ID']))\n locality.append((result['Locality']['More_Locality_Array'][str(j)]['LABEL']))\n\n for i in range(0, id.__len__()):\n data.append([id[i], locality[i], region[i], city[i]])\n print(data)\n\n cursor = db.cursor()\n sql1 = \"insert into locality(id,name,region,city) values (%s, %s,%s,%s)\"\n\n number_of_rows = cursor.executemany(sql1, data)\n db.commit()\n\n db.close()\n\n\nsearch_loc = ''\n\n\ndef get_region(col1_value):\n cursor2 = db.cursor()\n cursor2.execute(\"\"\"SELECT distinct region FROM locality WHERE name = %s\"\"\", (col1_value,))\n # Fetch all the rows in a list of lists.\n results = cursor2.fetchall()\n for row in results:\n region1 = row[0]\n return region1\n\ndef get_url(search_loc):\n region = get_region(search_loc)\n url = str('https://www.99acres.com/rent-property-in-' + search_loc + str('-bangalore-') + region + '-ffid').replace(\n \" \", \"-\")\n print(url)\n page = requests.get(url)\n print(page.status_code)\n soup = BeautifulSoup(page.content, 'html.parser')\n # getting last page number\n max_array = soup.find_all('a', class_='pgsel').__len__() - 1\n page_count = soup.find_all('a', class_='pgsel')[max_array]\n pge_cnt=page_count.get('value')\n return (pge_cnt,url)\n\ndef get_property_details(pge_cnt,url):\n\n print(\"Total number of Pages - \" + str(pge_cnt))\n time.sleep(10)\n for num in range(1, int(pge_cnt) + 1):\n new_url = str(url) + '-page-' + str(num)\n print(new_url)\n page = requests.get(new_url)\n print(page.status_code)\n soup = BeautifulSoup(page.content, 'html.parser')\n # scrape offline site\n # f = open(\"D:\\\\Setup\\\\NEW SOFTWARE\\\\Python\\\\Programs\\\\rental_search\\\\99_acres\\\\Webpages\\\\Property for rent in Bangalore South - Rental properties in Bangalore South.html\")\n # soup = BeautifulSoup(f, 'html.parser')\n all = soup.find_all(\"div\", class_='srpWrap')\n time.sleep(20)\n # print(all)\n for item in all:\n try:\n a = all.find(\"div\", {\"class\": \"srpDataWrap\"})\n print(a)\n except:\n pass\n l = []\n source = []\n price = []\n heading = []\n super_buildup = []\n society = []\n property_age = []\n property_type = []\n floor_info = []\n features = []\n locaton = []\n map1 = []\n description = []\n posted_date = []\n property_detail_link = []\n owner_dealer_name = []\n owner_dealer = []\n for item in all:\n\n try:\n source.append(source1)\n except:\n source.append('')\n\n try:\n price.append(item.find(\"b\", itemprop=\"price\").next.replace(\",\", \"\")\n .replace(\",\", \"\").replace(\".\", \"\").replace(\" Lac\", \"0000\").replace('Call for Price',\n '9999999')) # cleaning , . alphabets etc.\n\n except:\n price.append('')\n\n try:\n heading.append(item.find(\"div\", class_=\"wrapttl\").find(\"a\").text)\n except:\n heading.append('')\n try:\n super_buildup.append(item.find(\"div\", class_=\"srpDataWrap\").find(\"b\").text)\n except:\n super_buildup.append('')\n try:\n society.append(item.find(\"span\", class_=\"doElip\").find(\"b\").text.replace(\" \", \"\").replace(\"\\n\", \"\"))\n except:\n society.append('')\n try:\n property_age.append(\n item.find(\"div\", class_='srpDataWrap').contents[9].contents[2].text.replace(\"/\", \"\").replace(\" \",\n \"\").strip())\n except:\n property_age.append('')\n try:\n property_type.append(\n item.find(\"div\", class_='srpDataWrap').contents[9].contents[3].text.replace(\"/\", \"\").replace(\" \",\n \"\").strip())\n except:\n property_type.append('')\n try:\n floor_info.append(\n item.find(\"div\", class_='srpDataWrap').contents[9].contents[4].text.replace(\"/\", \"\").strip())\n except:\n floor_info.append('')\n try:\n features.append(item.find(\"div\", class_='iconDiv fc_icons fcInit').contents[1].attrs.get('value'))\n except:\n features.append('')\n a = item.find(\"div\", class_='lf f13 hm10 mb5').text.replace(\"\\n\", \"\").replace(\" \", \"\")\n p, q, r = a.split(':')\n z, x = q.split()\n try:\n owner_dealer.append(p)\n except:\n owner_dealer.append('')\n\n try:\n owner_dealer_name.append(z)\n except:\n owner_dealer_name.append('')\n\n try:\n date_object = datetime.strptime(r, '%b%d,%Y')\n posted_date.append(date_object.strftime('%Y-%m-%d'))\n except:\n posted_date.append('')\n\n try:\n description.append(item.find(\"span\", class_='srpDes').text.replace(\"\\n\", \"\")).replace(\"'\", \"\")\n except:\n description.append('')\n\n try:\n property_detail_link.append(\n str(\"https://www.99acres.com/\") +\n item.find(\"div\", class_=\"wrapttl\").find(\"a\", itemprop=\"url\").attrs[\n 'href'])\n except:\n property_detail_link.append('')\n\n try:\n map1.append(item.find(\"div\", class_=\"wrapttl\").find(\"i\", class_=\"uline\").attrs['data-maplatlngzm'])\n except:\n map1.append('')\n\n try:\n locaton.append(search_loc)\n except:\n locaton.append('')\n # print(price)\n # print(heading)\n # print(super_buildup)\n # print(society)\n # print(property_age)\n # print(property_type)\n # print(floor_info)\n # print(features)\n # print(locaton)\n # print(map1)\n # print(description)\n # print(posted_date)\n # print(owner_dealer_name)\n # print(owner_dealer)\n list = []\n for i in range(0, heading.__len__()):\n list.append(\n [source[i], heading[i], locaton[i], super_buildup[i], price[i], society[i], features[i],\n floor_info[i], property_age[i], property_type[i], owner_dealer[i], owner_dealer_name[i],\n posted_date[i], map1[i], property_detail_link[i]])\n # print(list.__len__())\n # print(list)\n # insert_property_details(list)\n cursor = db.cursor()\n try:\n sql = \"insert into property_detail(SOURCE, HEADING, LOCATION, SUPER_BUILDUP, PRICE,SOCIETY, FEATURES, FLOOR_INFO, PROPERTY_AGE, PROPERTY_TYPE, OWNER_DEALER, OWNER_DEALER_NAME, POSTED_DATE, MAP,PROPERTY_DETAIL_URL)values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\n number_of_rows = cursor.executemany(sql, list)\n db.commit()\n print(str(number_of_rows) + \" rows inserted successfully\")\n except:\n print(cursor._last_executed)\n print(\"Error while inserting data\")\n # finally:\n # db.close()\n\n\n# insert_bangalore_locality()\n\n#search_loc = \"Electronic City\"\n# search_loc = 'Kadubeesanahalli'\nsearch_loc = 'panathur'\n# search_loc = 'Bellandur' #UnicodeEncodeError: 'latin-1' codec can't encode character '\\u2013' page number 5 due to description column\n# search_loc = \"Marathahalli\" # UnicodeEncodeError: 'latin-1' codec can't encode character '\\u2022' in position 91 page 13 due to description column\n#search_loc = sys.argv[1]\npage_count,url=get_url(search_loc)\nget_property_details(page_count,url)\nelapsed = (time.time() - start)\nprint(elapsed, \" seconds\")\n","sub_path":"archive/version 1(all pages data)/python/99_acres.py","file_name":"99_acres.py","file_ext":"py","file_size_in_byte":10002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"369210339","text":"# -*- coding: UTF-8 -*-\nimport psycopg2\n\nDBNAME = 'news'\n\ndef get_pop_article():\n\n \"\"\"Return most popular articles from db.\"\"\"\n db = psycopg2.connect(database=DBNAME)\n c = db.cursor()\n c.execute(\"\"\"SELECT articles.title, count(log.path) FROM log\n INNER JOIN articles ON articles.slug = substr(log.path,10)\n GROUP BY articles.title order by count desc limit 3\"\"\")\n return c.fetchall()\n db.close()\n\ndef get_pop_author():\n db = psycopg2.connect(database=DBNAME)\n c = db.cursor()\n c.execute(\"\"\"SELECT authors.name, count(log.path) FROM log\n INNER JOIN articles ON articles.slug = substr(log.path,10)\n INNER JOIN authors ON authors.id = articles.author\n GROUP BY articles.title, authors.name order by count desc\"\"\")\n return c.fetchall()\n db.close()\n\n\ndef get_errors():\n db = psycopg2.connect(database=DBNAME)\n c = db.cursor()\n c.execute(\"\"\"SELECT * FROM (SELECT acesso.dia,\n ROUND(CAST((100*erros.cont)\n AS NUMERIC) / CAST(acesso.cont AS NUMERIC), 2)\n AS PERCENT FROM\n (SELECT date(time)\n AS dia, count(*) AS cont FROM log GROUP BY dia) AS acesso\n INNER JOIN\n (SELECT date(time) AS dia, COUNT(*) AS cont FROM log\n WHERE status != '200 OK' GROUP BY dia) AS erros\n ON acesso.dia = erros.dia)\n AS total WHERE PERCENT >= 1.0;\"\"\")\n return c.fetchall()\n db.close()\n\ndadosart = get_pop_article()\ndadosauthor = get_pop_author()\ndadoerro = get_errors()\n\nprint(\"Os tres artigos mais populares são:\")\nfor row in dadosart:\n print(\"Title = \", row[0], )\n print(\"Views = \", row[1], \"\\n\")\n\nprint(\"Os autores mais populares são:\")\nfor row in dadosauthor:\n print(\"Author = \", row[0], )\n print(\"Views = \", row[1], \"\\n\")\n\nprint(\"Os dias com mais de 1%:\")\nfor row in dadoerro:\n print(\"Dia = \", row[0], )\n print(\"Porcentagem = \", row[1], \"%\", \"\\n\")\n","sub_path":"projetoal.py","file_name":"projetoal.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"411984017","text":"import torchvision\nfrom torch.nn import *\nfrom torchvision.datasets import ImageFolder, CIFAR10\nfrom torchvision.transforms import *\nfrom torch.optim import *\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\nfrom torch.utils.data import random_split\n# from adabound import AdaBound\n\nfrom nntoolbox.vision.components import *\nfrom nntoolbox.vision.learner import SupervisedImageLearner\nfrom nntoolbox.utils import load_model, LRFinder, get_first_batch, get_device\nfrom nntoolbox.callbacks import *\nfrom nntoolbox.metrics import Accuracy, Loss\nfrom nntoolbox.vision.transforms import Cutout\nfrom nntoolbox.vision.models import ImageClassifier, EnsembleImageClassifier\nfrom nntoolbox.losses import SmoothedCrossEntropy\nfrom nntoolbox.init import lsuv_init\nimport math\n\nfrom functools import partial\n\nfrom sklearn.metrics import accuracy_score\nfrom .prog_bar import progress_bar_test\n\n\ndef run_classifier_test():\n print(\"Starting classifier test\")\n # progress_bar_test()\n torch.backends.cudnn.benchmark = True\n\n # data = CIFAR10('data/', train=True, download=True, transform=ToTensor())\n # train_size = int(0.8 * len(data))\n # val_size = len(data) - train_size\n # train_dataset, val_dataset = torch.utils.data.random_split(data, [train_size, val_size])\n # train_dataset.dataset.transform = Compose(\n # [\n # RandomHorizontalFlip(),\n # RandomResizedCrop(size=32, scale=(0.95, 1.0)),\n # # Cutout(length=16, n_holes=1),\n # ToTensor()\n # ]\n # )\n #\n # test_dataset = torchvision.datasets.CIFAR10('data/', train=False, download=True, transform=ToTensor())\n # kernel = partial(PolynomialKernel, dp=3, cp=2.0)\n\n\n train_val_dataset = ImageFolder(\n 'data/imagenette-160/train',\n transform=Compose([\n Resize((128, 128)),\n ToTensor()\n ])\n )\n\n test_dataset = ImageFolder(\n 'data/imagenette-160/val',\n transform=Compose([\n Resize((128, 128)),\n ToTensor()\n ])\n )\n\n train_size = int(0.8 * len(train_val_dataset))\n val_size = len(train_val_dataset) - train_size\n\n train_dataset, val_dataset = random_split(train_val_dataset, [train_size, val_size])\n\n train_dataset.dataset.transform = Compose(\n [\n RandomHorizontalFlip(),\n RandomResizedCrop(size=(128, 128), scale=(0.95, 1.0)),\n # Cutout(length=16, n_holes=1),\n ToTensor()\n ]\n )\n train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=128, shuffle=True)\n val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=128, shuffle=False)\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=128, shuffle=False)\n\n class SEResNeXtShakeShake(ResNeXtBlock):\n def __init__(self, in_channels, reduction_ratio=16, cardinality=2, activation=nn.ReLU,\n normalization=nn.BatchNorm2d):\n super(SEResNeXtShakeShake, self).__init__(\n branches=nn.ModuleList(\n [\n nn.Sequential(\n ConvolutionalLayer(\n in_channels, in_channels // 4, kernel_size=1, padding=0,\n activation=activation, normalization=normalization\n ),\n ConvolutionalLayer(\n in_channels // 4, in_channels, kernel_size=3, padding=1,\n activation=activation, normalization=normalization\n ),\n # ConvolutionalLayer(\n # in_channels // 4, in_channels, kernel_size=1, padding=0,\n # activation=activation, normalization=normalization\n # ),\n SEBlock(in_channels, reduction_ratio)\n ) for _ in range(cardinality)\n ]\n ),\n use_shake_shake=True\n )\n\n class StandAloneMultiheadAttentionLayer(nn.Sequential):\n def __init__(\n self, num_heads, in_channels, out_channels, kernel_size, stride=1, padding=3,\n activation=nn.ReLU, normalization=nn.BatchNorm2d\n ):\n layers = [\n StandAloneMultiheadAttention(\n num_heads=num_heads,\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n bias=False\n ),\n activation(),\n normalization(num_features=out_channels),\n ]\n super(StandAloneMultiheadAttentionLayer, self).__init__(*layers)\n\n class SEResNeXtShakeShakeAttention(ResNeXtBlock):\n def __init__(self, num_heads, in_channels, reduction_ratio=16, cardinality=2, activation=nn.ReLU,\n normalization=nn.BatchNorm2d):\n super(SEResNeXtShakeShakeAttention, self).__init__(\n branches=nn.ModuleList(\n [\n nn.Sequential(\n ConvolutionalLayer(\n in_channels=in_channels,\n out_channels=in_channels // 2,\n kernel_size=1,\n activation=activation,\n normalization=normalization\n ),\n StandAloneMultiheadAttentionLayer(\n num_heads=num_heads,\n in_channels=in_channels // 2,\n out_channels=in_channels // 2,\n kernel_size=3,\n activation=activation,\n normalization=normalization\n ),\n ConvolutionalLayer(\n in_channels=in_channels // 2,\n out_channels=in_channels,\n kernel_size=1,\n activation=activation,\n normalization=normalization\n ),\n SEBlock(in_channels, reduction_ratio)\n ) for _ in range(cardinality)\n ]\n ),\n use_shake_shake=True\n )\n\n # layer_1 = ManifoldMixupModule(ConvolutionalLayer(in_channels=3, out_channels=16, kernel_size=3, activation=nn.ReLU))\n # block_1 = ManifoldMixupModule(SEResNeXtShakeShake(in_channels=16, activation=nn.ReLU))\n\n model = Sequential(\n ConvolutionalLayer(in_channels=3, out_channels=16, kernel_size=3, activation=nn.ReLU),\n SEResNeXtShakeShake(in_channels=16, activation=nn.ReLU),\n # layer_1,\n # block_1,\n ConvolutionalLayer(\n in_channels=16, out_channels=32,\n activation=nn.ReLU,\n kernel_size=2, stride=2\n ),\n SEResNeXtShakeShake(in_channels=32),\n ConvolutionalLayer(\n in_channels=32, out_channels=64,\n kernel_size=2, stride=2\n ),\n SEResNeXtShakeShake(in_channels=64),\n ConvolutionalLayer(\n in_channels=64, out_channels=128,\n kernel_size=2, stride=2\n ),\n SEResNeXtShakeShake(in_channels=128),\n ConvolutionalLayer(\n in_channels=128, out_channels=256,\n kernel_size=2, stride=2\n ),\n SEResNeXtShakeShake(in_channels=256),\n ConvolutionalLayer(\n in_channels=256, out_channels=512,\n kernel_size=2, stride=2\n ),\n SEResNeXtShakeShake(in_channels=512),\n # SEResNeXtShakeShakeAttention(num_heads=8, in_channels=512),\n FeedforwardBlock(\n in_channels=512,\n out_features=10,\n pool_output_size=2,\n hidden_layer_sizes=(256, 128)\n )\n ).to(get_device())\n\n # lsuv_init(module=model, input=get_first_batch(train_loader, callbacks = [ToDeviceCallback()])[0])\n\n # print(count_trainable_parameters(model)) # 14437816 3075928\n\n optimizer = SGD(model.parameters(), weight_decay=0.0001, lr=0.30, momentum=0.9)\n learner = SupervisedImageLearner(\n train_data=train_loader,\n val_data=val_loader,\n model=model,\n criterion=SmoothedCrossEntropy().to(get_device()),\n optimizer=optimizer,\n mixup=True\n )\n\n # lr_finder = LRFinder(\n # model=model,\n # train_data=train_loader,\n # criterion=SmoothedCrossEntropy(),\n # optimizer=partial(SGD, lr=0.074, weight_decay=0.0001, momentum=0.9),\n # device=get_device()\n # )\n # lr_finder.find_lr(warmup=100, callbacks=[ToDeviceCallback()])\n\n swa = StochasticWeightAveraging(learner, average_after=5025, update_every=670)\n callbacks = [\n # ManifoldMixupCallback(learner=learner, modules=[layer_1, block_1]),\n ToDeviceCallback(),\n InputProgressiveResizing(initial_size=80, max_size=160, upscale_every=10, upscale_factor=math.sqrt(2)),\n # MixedPrecisionV2(),\n Tensorboard(),\n NaNWarner(),\n # ReduceLROnPlateauCB(optimizer, monitor='accuracy', mode='max', patience=10),\n LRSchedulerCB(CosineAnnealingLR(optimizer, eta_min=0.10, T_max=335)),\n swa,\n LossLogger(),\n ModelCheckpoint(learner=learner, filepath=\"weights/model.pt\", monitor='accuracy', mode='max'),\n ProgressBarCB()\n ]\n\n metrics = {\n \"accuracy\": Accuracy(),\n \"loss\": Loss()\n }\n\n final = learner.learn(\n n_epoch=500,\n callbacks=callbacks,\n metrics=metrics,\n final_metric='accuracy'\n )\n\n print(final)\n load_model(model=model, path=\"weights/model.pt\")\n classifier = ImageClassifier(model, tta_transform=Compose([\n ToPILImage(),\n RandomHorizontalFlip(),\n RandomResizedCrop(size=(128, 128), scale=(0.95, 1.0)),\n ToTensor()\n ]))\n print(classifier.evaluate(test_loader))\n\n print(\"Test SWA:\")\n model = swa.get_averaged_model()\n classifier = ImageClassifier(model, tta_transform=Compose([\n ToPILImage(),\n RandomHorizontalFlip(),\n RandomResizedCrop(size=(128, 128), scale=(0.95, 1.0)),\n ToTensor()\n ]))\n print(classifier.evaluate(test_loader))\n","sub_path":"nntoolbox/test/test_classifier.py","file_name":"test_classifier.py","file_ext":"py","file_size_in_byte":10582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"63508788","text":"try:\n import sys, os, glob, pytz\nexcept ImportError:\n sys = None\n os = None\n glob = None\n pytz = None\n\n#importamos las clases\nfrom include.user import User\nfrom include.history import History\nfrom include.bcolor import Bcolors\n\n#funciones\ndef clear(): \n #windows \n if __name__ == \"nt\": \n _ = os.system(\"cls\") \n #mac and linux\n else: \n _ = os.system(\"clear\")\n\nif __name__ == \"__main__\":\n clear()\n \n #creamos una instancia de la clase User()\n player = User()\n\n #setiamos el nombre y apellido del usuario\n player.setUserName(input(\"Hola, ingresa tu nombre: \"))\n player.setUserSername(input(f\"Muy bien {player.getUserName()}, ahora ingresa tu apellido: \"))\n print(f\"{Bcolors.OKGREEN}Ahora sí, es un gusto tenerte aquí {player.getUserName()} {player.getUserSername()}.\")\n print(player.getUserLogin())\n\n history = History()\n print(history.getHistory())\n\n #filePath = input(\"Ingrese la ruta: \")\n #fileName = input(\"Ingrese el nombre del archivo y su extensión: \")\n \n #if os.path.exists(\"content/history.txt\"):\n #pass\n\n\n\n #Si no existe historia, comenzar una\n\n #Si ya existe una historia, debo seguirla\n #Traer las últimas palabras con un máximo de 20 palabras\n #Continuar la historia usando hasta 20 palabras máximo.\n #Guardarla\n #Si sos la última persona te muestro la historia completa\n\n #Si quedan fragmento por completar, imprimo indicación de reenviar este programa.\n\n #Si la historia ya está terminada porque participaron 7 persona, la imprimo completa.\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"142258947","text":"import sys\nimport argparse\nimport utils\n\n\ndef main():\n # parse args\n parser = argparse.ArgumentParser(description='Patch given app Info.plist')\n parser.add_argument('path', help='Path to application')\n args = parser.parse_args()\n\n utils.patch_app(args.path)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"conf/patch_app.py","file_name":"patch_app.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"271647033","text":"\"\"\"\nField extrapolation methods for computing 3D vector magnetic fields from LOS magnetograms\n\"\"\"\nimport numpy as np\nfrom scipy.interpolate import griddata\nimport astropy.units as u\nimport numba\nfrom astropy.utils.console import ProgressBar\n\nfrom synthesizAR.util import SpatialPair\nfrom synthesizAR.visualize import plot_fieldlines\nfrom .helpers import from_local, to_local, magnetic_field_to_yt_dataset\nfrom .fieldlines import trace_fieldlines\n\n__all__ = ['PotentialField']\n\n\nclass PotentialField(object):\n \"\"\"\n Local (~1 AR) potential field extrapolation class\n\n Using the oblique Schmidt method as described in [1]_, compute a potential magnetic vector field\n from an observed LOS magnetogram. Note that this method is only valid for spatial scales\n :math:`\\lesssim 1` active region.\n\n Parameters\n ----------\n magnetogram : `~sunpy.map.Map`\n width_z : `~astropy.units.Quantity`\n shape_z : `~astropy.units.Quantity`\n\n References\n ----------\n .. [1] Sakurai, T., 1981, SoPh, `76, 301 `_\n \"\"\"\n\n @u.quantity_input\n def __init__(self, magnetogram, width_z: u.cm, shape_z: u.pixel):\n self.magnetogram = magnetogram\n self.shape = SpatialPair(x=magnetogram.dimensions.x, y=magnetogram.dimensions.y, z=shape_z)\n range_x, range_y = self._calculate_range(magnetogram)\n range_z = u.Quantity([0*u.cm, width_z])\n self.range = SpatialPair(x=range_x.to(u.cm), y=range_y.to(u.cm), z=range_z.to(u.cm))\n width_x = np.diff(range_x)[0]\n width_y = np.diff(range_y)[0]\n self.width = SpatialPair(x=width_x.to(u.cm), y=width_y.to(u.cm), z=width_z.to(u.cm))\n self.delta = SpatialPair(x=self.width.x/self.shape.x,\n y=self.width.y/self.shape.y,\n z=self.width.z/self.shape.z)\n\n @u.quantity_input\n def as_yt(self, B_field):\n \"\"\"\n Wrapper around `~synthesizAR.extrapolate.magnetic_field_to_yt_dataset`\n \"\"\"\n return magnetic_field_to_yt_dataset(B_field.x, B_field.y, B_field.z,\n self.range.x, self.range.y, self.range.z)\n\n @u.quantity_input\n def trace_fieldlines(self, B_field, number_fieldlines, **kwargs):\n \"\"\"\n Trace field lines through vector magnetic field.\n\n This is a wrapper around `~synthesizAR.extrapolate.trace_fieldlines` and\n accepts all of the same keyword arguments. Note that here the field lines are\n automatically converted to the HEEQ coordinate system.\n\n Parameters\n ----------\n B_field : `~synthesizAR.util.SpatialPair`\n number_fieldlines : `int`\n\n Returns\n -------\n coordinates : `list`\n `~astropy.coordinates.SkyCoord` objects giving coordinates for all field lines\n field_strengths : `list`\n `~astropy.units.Quantity` for magnitude of :math:`B(s)` for each field line\n \"\"\"\n ds = self.as_yt(B_field)\n lower_boundary = self.project_boundary(self.range.x, self.range.y).value\n lines = trace_fieldlines(ds, number_fieldlines, lower_boundary=lower_boundary, **kwargs)\n coordinates, field_strengths = [], []\n with ProgressBar(len(lines), ipython_widget=kwargs.get('notebook', True)) as progress:\n for l, b in lines:\n l = u.Quantity(l, self.range.x.unit)\n l_heeq = from_local(l[:, 0], l[:, 1], l[:, 2], self.magnetogram.center)\n coordinates.append(l_heeq)\n field_strengths.append(u.Quantity(b, str(ds.r['Bz'].units)))\n if kwargs.get('verbose', True): # Optionally suppress progress bar for tests\n progress.update()\n\n return coordinates, field_strengths\n\n def _calculate_range(self, magnetogram):\n left_corner = to_local(magnetogram.bottom_left_coord, magnetogram.center)\n right_corner = to_local(magnetogram.top_right_coord, magnetogram.center)\n range_x = u.Quantity([left_corner[0][0], right_corner[0][0]])\n range_y = u.Quantity([left_corner[1][0], right_corner[1][0]])\n return range_x, range_y\n \n def project_boundary(self, range_x, range_y):\n \"\"\"\n Project the magnetogram onto a plane defined by the surface normal at the center of the\n magnetogram.\n \"\"\"\n # Get all points in local, rotated coordinate system\n p_y, p_x = np.indices((int(self.shape.x.value), int(self.shape.y.value)))\n pixels = u.Quantity([(i_x, i_y) for i_x, i_y in zip(p_x.flatten(), p_y.flatten())], 'pixel')\n world_coords = self.magnetogram.pixel_to_world(pixels[:, 0], pixels[:, 1])\n local_x, local_y, _ = to_local(world_coords, self.magnetogram.center)\n # Flatten\n points = np.stack([local_x.to(u.cm).value, local_y.to(u.cm).value], axis=1)\n values = u.Quantity(self.magnetogram.data, self.magnetogram.meta['bunit']).value.flatten()\n # Interpolate\n x_new = np.linspace(range_x[0], range_x[1], int(self.shape.x.value))\n y_new = np.linspace(range_y[0], range_y[1], int(self.shape.y.value))\n x_grid, y_grid = np.meshgrid(x_new.to(u.cm).value, y_new.to(u.cm).value)\n boundary_interp = griddata(points, values, (x_grid, y_grid), fill_value=0.)\n\n return u.Quantity(boundary_interp, self.magnetogram.meta['bunit'])\n\n @property\n def line_of_sight(self):\n \"\"\"\n LOS vector in the local coordinate system\n \"\"\"\n los = to_local(self.magnetogram.observer_coordinate, self.magnetogram.center)\n return np.squeeze(u.Quantity(los))\n\n def calculate_phi(self):\n \"\"\"\n Calculate potential\n \"\"\"\n # Set up grid\n y_grid, x_grid = np.indices((int(self.shape.x.value), int(self.shape.y.value)))\n x_grid = x_grid*self.delta.x.value\n y_grid = y_grid*self.delta.y.value\n z_depth = -self.delta.z.value/np.sqrt(2.*np.pi)\n # Project lower boundary\n boundary = self.project_boundary(self.range.x, self.range.y).value\n # Normalized LOS vector\n l_hat = (self.line_of_sight/np.sqrt((self.line_of_sight**2).sum())).value\n # Calculate phi\n delta = SpatialPair(x=self.delta.x.value, y=self.delta.y.value, z=self.delta.z.value)\n shape = SpatialPair(x=int(self.shape.x.value),\n y=int(self.shape.y.value),\n z=int(self.shape.z.value))\n phi = np.zeros((shape.x, shape.y, shape.z))\n phi = _calculate_phi_numba(phi, boundary, delta, shape, z_depth, l_hat)\n return phi * u.Unit(self.magnetogram.meta['bunit']) * self.delta.x.unit * (1. * u.pixel)\n\n @u.quantity_input\n def calculate_field(self, phi: u.G * u.cm):\n \"\"\"\n Compute vector magnetic field.\n\n Calculate the vector magnetic field using the current-free approximation,\n\n .. math::\n \\\\vec{B} = -\\\\nabla\\phi\n\n The gradient is computed numerically using a five-point stencil,\n\n .. math::\n \\\\frac{\\partial B}{\\partial x_i} \\\\approx -\\left(\\\\frac{-B_{x_i}(x_i + 2\\Delta x_i) + 8B_{x_i}(x_i + \\Delta x_i) - 8B_{x_i}(x_i - \\Delta x_i) + B_{x_i}(x_i - 2\\Delta x_i)}{12\\Delta x_i}\\\\right)\n\n Parameters\n ----------\n phi : `~astropy.units.Quantity`\n\n Returns\n -------\n B_field : `~synthesizAR.util.SpatialPair`\n x, y, and z components of the vector magnetic field in 3D\n \"\"\"\n Bx = u.Quantity(np.zeros(phi.shape), self.magnetogram.meta['bunit'])\n By = u.Quantity(np.zeros(phi.shape), self.magnetogram.meta['bunit'])\n Bz = u.Quantity(np.zeros(phi.shape), self.magnetogram.meta['bunit'])\n # Take gradient using a five-point stencil\n Bx[2:-2, 2:-2, 2:-2] = -(phi[2:-2, :-4, 2:-2] - 8.*phi[2:-2, 1:-3, 2:-2]\n + 8.*phi[2:-2, 3:-1, 2:-2]\n - phi[2:-2, 4:, 2:-2])/12./(self.delta.x * 1. * u.pixel)\n By[2:-2, 2:-2, 2:-2] = -(phi[:-4, 2:-2, 2:-2] - 8.*phi[1:-3, 2:-2, 2:-2]\n + 8.*phi[3:-1, 2:-2, 2:-2]\n - phi[4:, 2:-2, 2:-2])/12./(self.delta.y * 1. * u.pixel)\n Bz[2:-2, 2:-2, 2:-2] = -(phi[2:-2, 2:-2, :-4] - 8.*phi[2:-2, 2:-2, 1:-3]\n + 8.*phi[2:-2, 2:-2, 3:-1]\n - phi[2:-2, 2:-2, 4:])/12./(self.delta.z * 1. * u.pixel)\n # Set boundary conditions such that the last two cells in either direction in each dimension\n # are the same as the preceding cell.\n for Bfield in (Bx, By, Bz):\n for j in [0, 1]:\n Bfield[j, :, :] = Bfield[2, :, :]\n Bfield[:, j, :] = Bfield[:, 2, :]\n Bfield[:, :, j] = Bfield[:, :, 2]\n for j in [-2, -1]:\n Bfield[j, :, :] = Bfield[-3, :, :]\n Bfield[:, j, :] = Bfield[:, -3, :]\n Bfield[:, :, j] = Bfield[:, :, -3]\n\n return SpatialPair(x=Bx, y=By, z=Bz)\n\n def extrapolate(self):\n phi = self.calculate_phi()\n bfield = self.calculate_field(phi)\n return bfield\n\n def peek(self, fieldlines, **kwargs):\n plot_fieldlines(*fieldlines, magnetogram=self.magnetogram, **kwargs)\n\n\n@numba.jit(nopython=True, fastmath=True, parallel=True)\ndef _calculate_phi_numba(phi, boundary, delta, shape, z_depth, l_hat):\n factor = 1. / (2. * np.pi) * delta.x * delta.y\n for i in numba.prange(shape.x):\n for j in numba.prange(shape.y):\n for k in numba.prange(shape.z):\n Rz = k * delta.z - z_depth\n lzRz = l_hat[2] * Rz\n for i_prime in range(shape.x):\n for j_prime in range(shape.y):\n Rx = delta.x * (i - i_prime)\n Ry = delta.y * (j - j_prime)\n R_mag = np.sqrt(Rx**2 + Ry**2 + Rz**2)\n num = l_hat[2] + Rz / R_mag\n denom = R_mag + lzRz + Rx*l_hat[0] + Ry*l_hat[1]\n green = num / denom\n phi[j, i, k] += boundary[j_prime, i_prime] * green * factor\n\n return phi\n","sub_path":"synthesizAR/extrapolate/extrapolators.py","file_name":"extrapolators.py","file_ext":"py","file_size_in_byte":10268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"240549670","text":"import re\nimport string\nfrom collections import Counter\n\nimport numpy as np\nfrom nltk.util import pad_sequence\nfrom nltk.util import bigrams\nfrom nltk.util import ngrams\nfrom nltk.util import everygrams\nfrom nltk.lm.preprocessing import pad_both_ends\nfrom nltk.lm.preprocessing import flatten\n\ndef read_corpus(filename):\n with open(filename, \"r\",encoding=\"utf8\") as file:\n lines = file.readlines()\n words = []\n for line in lines:\n words += re.findall(r'\\w+', line.lower())\n\n return words\n\nwords = read_corpus(\"./data.csv\")\nprint(f\"There are {len(words)} total words in the corpus\")\n\nvocabs = set(words)\nprint(f\"There are {len(vocabs)} unique words in the vocabulary\")\n\nword_counts = Counter(words)\nprint(word_counts[\"yêu\"])\n\ntotal_word_count = float(sum(word_counts.values()))\nword_probas = {word: word_counts[word] / total_word_count for word in word_counts.keys()}\n\nprint(word_probas[\"yêu\"])\n\ndef split(word):\n return [(word[:i], word[i:]) for i in range(len(word) + 1)]\n\ndef delete(word):\n return [l + r[1:] for l,r in split(word) if r]\n\ndef swap(word):\n return [l + r[1] + r[0] + r[2:] for l, r in split(word) if len(r)>1]\n\ndef replace(word):\n letters = string.ascii_lowercase\n return [l + c + r[1:] for l, r in split(word) if r for c in letters]\n\ndef insert(word):\n letters = string.ascii_lowercase\n return [l + c + r for l, r in split(word) for c in letters]\n\ndef edit1(word):\n return set(delete(word) + swap(word) + replace(word) + insert(word))\n\ndef edit2(word):\n return set(e2 for e1 in edit1(word) for e2 in edit1(e1))\n\n\n\n\n\ndef correct_spelling(word, vocabulary, word_probabilities):\n if word in vocabulary:\n print(f\"{word} is already correctly spelt\")\n return\n\n suggestions = edit1(word) or edit2(word) or [word]\n best_guesses = [w for w in suggestions if w in vocabulary]\n return [(w, word_probabilities[w]) for w in best_guesses]\n\n\nword = \"chnug\"\ncorrections = correct_spelling(word, vocabs, word_probas)\n\nif corrections:\n print(corrections)\n probs = np.array([c[1] for c in corrections])\n best_ix = np.argmax(probs)\n correct = corrections[best_ix][0]\n print(f\"{correct} is suggested for {word}\")\n\nclass SpellChecker(object):\n\n def __init__(self, corpus_file_path):\n with open(corpus_file_path, \"r\",encoding=\"utf8\") as file:\n lines = file.readlines()\n words = []\n for line in lines:\n words += re.findall(r'\\w+', line.lower())\n\n self.vocabs = set(words)\n self.word_counts = Counter(words)\n total_words = float(sum(self.word_counts.values()))\n self.word_probas = {word: self.word_counts[word] / total_words for word in self.vocabs}\n\n def _level_one_edits(self, word):\n letters = string.ascii_lowercase\n splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]\n deletes = [l + r[1:] for l,r in splits if r]\n swaps = [l + r[1] + r[0] + r[2:] for l, r in splits if len(r)>1]\n replaces = [l + c + r[1:] for l, r in splits if r for c in letters]\n inserts = [l + c + r for l, r in splits for c in letters]\n\n return set(deletes + swaps + replaces + inserts)\n\n def _level_two_edits(self, word):\n return set(e2 for e1 in self._level_one_edits(word) for e2 in self._level_one_edits(e1))\n\n def check(self, word):\n candidates = self._level_one_edits(word) or self._level_two_edits(word) or [word]\n valid_candidates = [w for w in candidates if w in self.vocabs]\n return sorted([(c, self.word_probas[c]) for c in valid_candidates], key=lambda tup: tup[1], reverse=True)\n\n\nchecker = SpellChecker(\"./data.csv\")\n\n\n\n\n#Bi-gram\n\ntextdata_biGram = open(\"data.csv\", \"r\",encoding=\"utf8\").read()\n#lop N_gram co thuộc tính word và xác xuất để dễ in ra\nclass N_Gram:\n def __init__(self, word, probability):\n self.word = word\n self.probability = probability\n\n\n\n# hàm đếm số kí tự giống nhau 2 xâu\ndef count(str1, str2):\n c = 0\n for i in str1:\n if re.search(i, str2):\n c = c + 1\n return c\n# tim tu dung\ndef search_Word (data,word,wrong_words) :\n # độ dài từ sai\n length_Of_wrong_word = len(wrong_words)\n #chứa kết quả là mảngg xác xuất + từ\n bigram_word = []\n #số kí tự trùng nhau nhiều nhất\n number_of_duplicate_character_max = 0\n # xác xuất lớn nhất\n w1_max = 0\n #kết quả từ tốt nhất\n solution_word = \"\"\n # chạy từ 1 đến cuối văn bản\n for i in range(len(data)) :\n # nếu từ i bằng từ đứng trước\n if (data[i] == word) :\n # xét xâu : từ đứng trước + từ sau\n one_bigram_word = ' '+ data[i] +' ' + data[i+1]+\" \"\n # đếm xâu\n w1 = textdata_biGram.count(one_bigram_word)\n #đếm từ trước\n w2 = word_counts[data[i]]\n #đếm số kí tự giống nhau giữa từ sai và tự gợi ý\n number_of_duplicate_character = count(wrong_words, data[i + 1])\n\n #chuan hoa du lieu\n if (w1 == 0) :\n w1 = 1\n # độ dài từ gợi ý\n length_word1 = len(data[i + 1])\n # thêm vào mảng kết quả\n biGramp = N_Gram(data[i + 1], w1 / w2)\n bigram_word.append(biGramp)\n # du doan theo so ki tu giong nhau\n # nếu lớn hơn thì cập nhât\n if (number_of_duplicate_character > number_of_duplicate_character_max) :\n w1_max = w1\n solution_word = data[i + 1]\n number_of_duplicate_character_max = number_of_duplicate_character\n\n\n #biGramp = N_Gram(data[i+1], w1 / w2)\n #bigram_word.append(biGramp)\n\n #neu so ki tu bang nhau thi se du doan theo xac xuat\n #nếu bằng thì xét đến độ dài, xác xuất\n if (number_of_duplicate_character == number_of_duplicate_character_max) :\n #biGram = N_Gram(data[i+1] , w1/w2)\n #bigram_word.append(biGram)\n\n #tu du doan phai co do dai lon, be hon so v tu dung la 1\n if (w1 > w1_max):\n solution_word = data[i + 1]\n number_of_duplicate_character_max = number_of_duplicate_character\n w1_max = w1\n\n #sắp xếp mảng kết quả theo xác xuất\n result = sorted(bigram_word,key=lambda x: x.probability, reverse=True)\n\n for i in range(len(result)):\n print(\"( \" + result[i].word + \", \" + str(result[i].probability) + \" )\")\n print(\"Sửa từ: \" + wrong_words + \" trong \" + word + \" \" + wrong_words + \" là : \" + word +\" \" + solution_word)\n\n\n#Test # hoa huệ, kiến trúc , kiến thức, công nghệ ghệu\nprevious_word = \"hoa\"\ntrue_word = \"huệ\"\nfalse_word = \"hệu\"\n\nprint(checker.check(false_word))\nword_errorl_model = \"\"\nif (len(checker.check(false_word)) > 0):\n word_errorl_model = checker.check(false_word)[0][0]\n print(\"Từ học theo errol model : \" + word_errorl_model)\nif not (word_errorl_model == true_word):\n search_Word(words,previous_word,false_word)\n\n\nsentences = \"tôi đi họcc ở trườngg\"\n\n# hàm thêm , t copy bên bi_gram_model.py\ndef divide_bi_gram(sentences):\n words_1 = []\n\n lines = sentences.readlines()\n words_1 += re.findall(r'\\w+')\n list(pad_sequence(words_1[0],\n pad_left=True, left_pad_symbol=\"\",\n pad_right=True, right_pad_symbol=\"\",\n n=2))\n\n padded_sent = list(pad_sequence(words_1[0], pad_left=True, left_pad_symbol=\" \",\n pad_right=True, right_pad_symbol=\" \", n=2))\n return print(list(ngrams(padded_sent, n=2)))\n\n","sub_path":"ErrolModel_BiGram.py","file_name":"ErrolModel_BiGram.py","file_ext":"py","file_size_in_byte":7701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"297849557","text":"import json\nfrom django.core.mail import EmailMessage\nfrom django.http import JsonResponse\n\n\ndef send_email(request):\n if request.method == \"POST\":\n body = json.loads(request.body)\n\n subject = body[\"subject\"]\n message = body[\"message\"]\n email = body[\"email\"]\n\n email = EmailMessage(\n subject=f\"[Robo-One.la] - {subject}\",\n body=f\"{message}\",\n from_email=\"contacto@robo-one.la\",\n to=[\"rquevedo@roboticslab.cl\"],\n reply_to=[email],\n )\n\n email.send(fail_silently=False)\n\n return JsonResponse({\"status\": \"ok\"})","sub_path":"contact/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"360679986","text":"import logging, gzip, pandas as pd, numpy as np, json\nfrom sklearn import model_selection, preprocessing, metrics, svm\nfrom sklearn.svm import LinearSVC, SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom collections import Counter\nfrom imblearn.under_sampling import NearMiss\n\n# Input\ninput_file = '../Data/reviews_Cell_Phones_and_Accessories_5.json.gz'\nlog_file = '../logs/cellphonebase2_bal.log'\n\n# Enable logging\nlogger = logging.getLogger()\nfhandler = logging.FileHandler(filename=log_file, mode='a')\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfhandler.setFormatter(formatter)\nlogger.addHandler(fhandler)\nlogger.setLevel(logging.DEBUG)\n\ndata = []\nwith gzip.open(input_file) as f:\n for l in f: \n data.append(json.loads(l.strip()))\n\ndf = pd.DataFrame.from_dict(data)\n\ntarget = df['overall']\ntext = df['reviewText']\n\nlogging.debug(\"RUN: NearMiss version 2 with balanced training only\")\nlist_test = [0.1, 0.2, 0.3, 0.4, 0.5]\nfor i in list_test:\n # Split dataset into training set and test set\n test_size = i\n train_size = 1 - i\n X_train, X_test, y_train, y_test = train_test_split(text, target, test_size=i,random_state=109) \n\n # label encode the target variable\n encoder = preprocessing.LabelEncoder()\n y_train = encoder.fit_transform(y_train)\n y_test = encoder.fit_transform(y_test)\n logging.debug(\"label encoding done\")\n\n # Feature 01_extraction: Bag of Words with TF-IDF\n tfidf_vect_ngram = TfidfVectorizer(analyzer='word', token_pattern=r'\\w{1,}', ngram_range=(2,3), max_features=5000)\n tfidf_vect_ngram.fit(text)\n logging.debug(\"feature extractiion: n-grams + TF-IDF done\")\n\n # transform the training and validation data using tfidf vectorizer object\n xtrain_tfidf_ngram = tfidf_vect_ngram.transform(X_train)\n xtest_tfidf_ngram = tfidf_vect_ngram.transform(X_test)\n logging.debug(\"transformation into tfidf vectors done\")\n\n # NearMiss 2\n nm2 = NearMiss(version=2)\n X_train_resampled, y_train_resampled = nm2.fit_resample(xtrain_tfidf_ngram, y_train)\n logging.debug(\"Training set:\")\n logging.debug(sorted(Counter(y_train_resampled).items()))\n # X_test_resampled, y_test_resampled = nm2.fit_resample(xtest_tfidf_ngram, y_test)\n logging.debug(\"Test set:\")\n logging.debug(sorted(Counter(y_test).items()))\n\n #Create a Classifier\n clf = SVC(kernel='linear')\n # Train the model using the training sets\n clf.fit(X_train_resampled, y_train_resampled)\n #Predict the response for test dataset\n y_pred = clf.predict(xtest_tfidf_ngram)\n # logging.debug(\"model building, training and prediction done\")\n # logging.debug('Training target statistics: {}'.format(Counter(y_train_resampled)))\n # logging.debug('Testing target statistics: {}'.format(Counter(y_test)))\n\n # Model Accuracy, how often is the classifier correct?\n logging.debug(\"train: \" + str(train_size) + \"/ test: \" + str(test_size))\n accuracy = str(metrics.accuracy_score(y_test, y_pred))\n precision = str(metrics.precision_score(y_test, y_pred, average=\"macro\"))\n f1 = str(metrics.f1_score(y_test, y_pred, average=\"macro\"))\n logging.debug(\"Accuracy:\" + accuracy)\n logging.debug(\"Precision:\" + precision)\n logging.debug(\"F1:\" + f1)\n logging.debug(pd.crosstab(y_test, y_pred))\n","sub_path":"BaselineExperiments/CellPhonesAccessories_base_2_var_balanced_NM2.py","file_name":"CellPhonesAccessories_base_2_var_balanced_NM2.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"629848761","text":"import numpy as np\nimport xarray as xr\nimport torch\nfrom src.train_nn_pytorch import Dataset\nimport time\n\nif torch.cuda.is_available():\n print('using CUDA !')\n device = torch.device(\"cuda\")\n torch.set_default_tensor_type(\"torch.cuda.FloatTensor\")\nelse:\n print(\"CUDA not available\")\n device = torch.device(\"cpu\")\n torch.set_default_tensor_type(\"torch.FloatTensor\")\n\ndatadir = '/gpfs/work/nonnenma/data/forecast_predictability/weatherbench/5_625deg/'\nres_dir = '/gpfs/work/nonnenma/results/forecast_predictability/weatherbench/5_625deg/'\n\nlead_time = 3*24\nbatch_size = 32\n\n\"\"\"\nvar_dict = {'geopotential': ('z', [1, 10, 100, 200, 300, 400, 500, 600, 700, 850, 1000]),\n 'temperature': ('t', [1, 10, 100, 200, 300, 400, 500, 600, 700, 850, 1000]),\n 'u_component_of_wind': ('u', [1, 10, 100, 200, 300, 400, 500, 600, 700, 850, 1000]), \n 'v_component_of_wind': ('v', [1, 10, 100, 200, 300, 400, 500, 600, 700, 850, 1000]),\n 'constants': ['lsm','orography','lat2d']\n }\n\"\"\"\nvar_dict = {'geopotential': ('z', [500]),\n 'temperature': ('t', [850])\n }\n\nx = xr.merge(\n[xr.open_mfdataset(f'{datadir}/{var}/*.nc', combine='by_coords')\n for var in var_dict.keys()],\nfill_value=0 # For the 'tisr' NaNs\n)\nx = x.chunk({'time' : np.sum(x.chunks['time']), 'lat' : x.chunks['lat'], 'lon': x.chunks['lon']})\n\ndg_train = Dataset(x.sel(time=slice('1979', '2015')), var_dict, lead_time, normalize=True, norm_subsample=30000)\ntrain_loader = torch.utils.data.DataLoader(\n dg_train,\n batch_size=batch_size,\n drop_last=True)\n\nn_channels = len(dg_train.data.level.level)\nprint('n_channels', n_channels)\n\n## \n\nimport torch.nn.functional as F\n\nn_epochs, max_patience = 200, 20\nbest_loss, patience = np.inf, max_patience\nbest_state_dict = {}\n\nepoch = 0\nnum_steps, eval_every = 0, 2000\n\nwhile True:\n\n epoch += 1\n if epoch > n_epochs:\n break\n\n t = time.time()\n print(f'epoch #{epoch}')\n # Train for a single epoch.\n for batch in train_loader:\n inputs, targets = batch[0].to(device), batch[1].to(device)\n tmp1 = torch.sum(inputs) + torch.sum(targets) # just some simple computation to ensure data was loaded\n num_steps += 1\n\n # Track convergence on validation set.\n if np.mod(num_steps, eval_every) == 0:\n print(f'epoch #{epoch} || time {time.time() -t}s')\n\n","sub_path":"quick_test_time_IO.py","file_name":"quick_test_time_IO.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"56761555","text":"import os\nimport time\nimport pandas as pd\nfrom functools import reduce\nfrom itertools import combinations\n\nfrom config.config_dirs import FEATUREMAPS_DATA_RAW\nfrom feature_map.mnist.feature import Feature\nfrom feature_map.mnist.utils.feature_map.preprocess import extract_samples_and_stats, extract_samples_and_stats_by_data\nfrom feature_map.mnist.utils.feature_map.visualize import visualize_map\nfrom config.config_featuremaps import NUM_CELLS, MAP_DIMENSIONS\n\ndef main(features_combination, features_extraction_time, samples):\n data, samples = visualize_map(\"featuremap\", features_combination, samples)\n for features_dict in data:\n features_dict.update({'features_extraction': features_extraction_time})\n # Update the current data or create a new dataframe\n if os.path.isfile(FEATUREMAPS_DATA_RAW):\n old_data = pd.read_pickle(FEATUREMAPS_DATA_RAW)\n new_data = pd.DataFrame(data)\n features_df = pd.concat([old_data, new_data]).drop_duplicates(subset=['approach', 'map_size'], keep='last')\n features_df = features_df.reset_index(drop=True)\n else:\n new_data = pd.DataFrame(data)\n features_df = pd.DataFrame(data)\n\n features_df.to_pickle(FEATUREMAPS_DATA_RAW)\n\n return new_data, samples\n\n\ndef generate_featuremap_by_data(train_data, train_labels):\n \n filtered = list(zip(\n train_data,\n train_labels,\n train_labels\n ))\n\n samples, stats = extract_samples_and_stats_by_data(filtered)\n # Get the list of features\n features = [\n Feature(feature_name, feature_stats['min'], feature_stats['max'])\n for feature_name, feature_stats in stats.to_dict().items()\n ]\n\n # Visualize the feature-maps\n data, samples = visualize_map(\"retrain_featuremap\", features, samples)\n\n features_df = pd.DataFrame(data)\n\n # features_df.to_pickle(FEATUREMAPS_DATA_RAW)\n\n return features_df, samples, features\n\n\nif __name__ == \"__main__\":\n main()\n \n","sub_path":"feature_map/mnist/feature_map.py","file_name":"feature_map.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"98452304","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 3 17:15:53 2016\n\n@author: Bradley\n\nProcessing NDBC buoy wave data.\nUse get_ndbc.py to retrieve data.\nUse plot_ndbc_1.py to plot data.\n\n\"\"\"\n\n# import modules\nimport os\nimport sys\nalp = os.path.abspath('../../LiveOcean/alpha')\nif alp not in sys.path:\n sys.path.append(alp)\nimport zfun\nimport pickle\nimport numpy as np\nimport pandas as pd\nfrom warnings import filterwarnings\nfilterwarnings('ignore') # skip some warning messages\n\n# select directory\nwhich_home = os.environ.get(\"HOME\") # Mac version\nif which_home == '/Users/PM5':\n dirname = which_home + 'Documents/tools_data/obs_data/ndbc/'\nelif which_home == '/home/parker':\n dirname = '/data1/parker/tools_data/obs_data/ndbc/'\nelif which_home == '/home/bbartos':\n dirname = which_home + '/tools_data/obs_data/ndbc/'\nelif which_home is None: # Windows version\n which_home = os.path.expanduser(\"~\")\n dirname = (which_home.replace('\\\\', '/') +\n '/Documents/Research Work/Parker/tools_data/obs_data/ndbc/')\nelse:\n print('Trouble filling out environment variables')\n\n# **** USER EDITS ****\n\n# Specify NDBC buoy stations\n\n# Washington and Oregon (from Puget Sound to S. Oregon)\n#sn_list = ['wpow1','sisw1','46088','46087','ttiw1','desw1','46041']\n#sn_list = ['46029','46089','46005','nwpo3','46050','46015','46002']\n\n# For LiveOcean Comparison\nsn_list = ['46088', '46087', '46041', '46029', '46089', '46050']\n\n# Entire West Coast\n#sn_list = ['wpow1', 'sisw1', 'ttiw1', 'desw1', 'nwpo3', 'ptac1', 'ptgc1',\n# '46088', '46087', '46041', '46029', '46089', '46005', '46050',\n# '46015', '46002', '46027', '46022', '46006', '46014', '46013',\n# '46059', '46026', '46012', '46024', '46028', '46011', '46053',\n# '46054', '46069', '46025', '46047', '46086']\n\n# Testing\n#sn_list = ['46088','46041']\n\n# Time filters\n# m = month\n# w = week\n# d = day\ntf_list = ['m', 'w', 'd']\n\n# Load and process NDBC Buoy Data\n\n\"\"\"\nFor desw1, nwpo3, sisw1, ttiw1, wtpo1, 46088, 46087, 46041, 46089, 46005, 46050,\n46015, 46002 the columns are:\n\n1984-1993:\nYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\n\n1994-1995:\nYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\\r\n\n1996-1997:\nYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\n\n1998:\nYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\n98 01 01 00 172 8.2 8.9 99.00 99.00 99.00 999 1011.4 8.7 999.0 6.9 99.0\\r\n\n1999:\nYYYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\n1999 01 01 00 69 4.5 6.1 99.00 99.00 99.00 999 1021.6 7.6 999.0 4.8 99.0\\r\n\n2000-2004:\nYYYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS TIDE\n\n2005-2006:\nYYYY MM DD hh mm WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS TIDE\n\n2007-2015: (but 2008 and 2010 had deg instead of degT for MWD,\n and 2007, 2008, and 2010 had nmi instead of mi for VIS)\n#YY MM DD hh mm WDIR WSPD GST WVHT DPD APD MWD PRES ATMP WTMP DEWP VIS TIDE\n#yr mo dy hr mn degT m/s m/s m sec sec degT hPa degC degC degC mi ft\n\"\"\"\n\"\"\"\nFor 46029 the columns are:\n\n1984-1993:\nYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\n\n1994-1995:\nYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\\r\n\n1996-1997:\nYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\n\n1998:\nYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\n98 01 01 00 172 8.2 8.9 99.00 99.00 99.00 999 1011.4 8.7 999.0 6.9 99.0\\r\n\n1999:\nYYYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS\n1999 01 01 00 69 4.5 6.1 99.00 99.00 99.00 999 1021.6 7.6 999.0 4.8 99.0\\r\n\n2000-2003:\nYYYY MM DD hh WD WSPD GST WVHT DPD APD MWD BAR ATMP WTMP DEWP VIS TIDE\n\n2004-2015: (but 2004, 2005, 2006, 2008 and 2010 had deg instead of degT for MWD, \n and 2007, 2008, and 2010 had nmi instead of mi for VIS)\n#YY MM DD hh mm WDIR WSPD GST WVHT DPD APD MWD PRES ATMP WTMP DEWP VIS TIDE\n#yr mo dy hr mn degT m/s m/s m sec sec deg hPa degC degC degC mi ft\n\"\"\"\n\n\ndef get_data(fn, tf_list, yr):\n# Read the txt file into a Dataframe\n if sn == '46029':\n if yr in range(1984, 1999): # 2-digit year: use %y\n df = pd.read_csv(fn, delim_whitespace=True, index_col='date',\n parse_dates={'date': [0, 1, 2, 3]},\n date_parser=lambda x: pd.datetime.strptime(x,'%y %m %d %H'))\n if yr in range(1999, 2004):\n df = pd.read_csv(fn, delim_whitespace=True, index_col='date',\n parse_dates={'date':[0, 1, 2, 3]},\n date_parser=lambda x: pd.datetime.strptime(x,'%Y %m %d %H'))\n elif yr >= 2004: # add minutes column\n df = pd.read_csv(fn, delim_whitespace=True, index_col='date',\n skiprows=[1],\n parse_dates={'date':[0, 1, 2, 3, 4]},\n date_parser=lambda x: pd.datetime.strptime(x,'%Y %m %d %H %M'))\n else:\n if yr in range(1984, 1999): # 2-digit year: use %y\n df = pd.read_csv(fn, delim_whitespace=True, index_col='date',\n parse_dates={'date':[0, 1, 2, 3]},\n date_parser=lambda x: pd.datetime.strptime(x,'%y %m %d %H'))\n if yr in range(1999, 2005): # switch to 4-digit year: use %Y\n df = pd.read_csv(fn, delim_whitespace=True, index_col='date',\n parse_dates={'date':[0, 1, 2, 3]},\n date_parser=lambda x: pd.datetime.strptime(x,'%Y %m %d %H'))\n elif yr >= 2005: # add minutes column\n df = pd.read_csv(fn, delim_whitespace=True, index_col='date',\n skiprows=[1],\n parse_dates={'date':[0, 1, 2, 3, 4]},\n date_parser=lambda x: pd.datetime.strptime(x,'%Y %m %d %H %M'))\n df = df.rename(columns={'WD': 'WDIR', 'BAR': 'PRES'})\n \n # mask known missing data\n df[df==9999.0] = np.nan\n df[df==999.0] = np.nan\n df[df==99.0] = np.nan\n \n # fix some obviously bad data\n if fn == '46002h2015.txt':\n df[5800:6250] = np.nan\n \n# Create wind time series\n # WSPD is in m/s and WDIR is the compass direction\n # that the wind is coming FROM\n\n # create 10m standard WSPD\n P = 0.11\n z_stnd = 10\n z_meas = 5\n df['WSPD_10'] = df['WSPD'] * (z_stnd/z_meas)**P\n\n # create directional WSPD\n wspd_10 = df.WSPD_10.values\n wdir = df.WDIR.values\n theta = 1.5*np.pi - np.pi*wdir/180.\n U_WSPD = wspd_10 * np.cos(theta)\n V_WSPD = wspd_10 * np.sin(theta)\n df['Uwind'] = U_WSPD; df['Vwind'] = V_WSPD\n\n# Create wind stress\n Cd = 0.0013\n rho_air = 1.22\n tau = Cd * rho_air * wspd_10**2\n taux = tau * np.cos(theta)\n tauy = tau * np.sin(theta)\n df['taux'] = taux\n df['tauy'] = tauy\n\n return df\n\n# Retrieval\nyr_list = range(1984,2016)\nndbc_df_m = dict()\nndbc_df_w = dict()\nndbc_df_d = dict()\nndbc_clim = dict()\nndbc_clim_std = dict()\nfor sn in sn_list:\n id_list = []\n count = 0\n for yr in yr_list: \n id = str(sn) + 'h' + str(yr)\n id_list.append(id)\n fn = ('C:/Users/Bradley/Documents/Research Work/Parker/tools_data/obs_data/ndbc/'\n + sn + '/' + id + '.txt')\n try:\n dff = get_data(fn, tf_list, yr)\n print(fn + ' = success')\n if count == 0:\n DFF = dff\n count += 1\n else:\n DFF = DFF.append(dff)\n except OSError:\n print(fn + ' = fail')\n pass\n\n# Time filters\n # change to hour sampling, filling time gaps\n DFF = DFF.resample('H', how='mean')\n DFF = DFF.reindex(pd.date_range(DFF.index[1], DFF.index[-1], freq='H')) \n day_limit = 2 # fills gaps up to this number of days\n DFF_inter = DFF.interpolate(method='linear', limit=24*day_limit) \n \n # create arrays for filtering\n DFF_array = DFF.as_matrix()\n DFF_header = DFF.columns.values\n \n # godin filter\n filt_array = np.array(DFF_array)\n for j in range(DFF_array.shape[1]):\n filt_array[:,j] = zfun.filt_godin(DFF_array[:,j])\n \n # hanning filter\n for tf in tf_list:\n if tf == 'm':\n filt_m = np.array(DFF_array)\n for j in range(filt_array.shape[1]):\n filt_m[:,j] = zfun.filt_hanning(filt_array[:,j], n=720)\n elif tf == 'w':\n filt_w = np.array(DFF_array)\n for j in range(filt_array.shape[1]):\n filt_w[:,j] = zfun.filt_hanning(filt_array[:,j], n=168)\n elif tf == 'd':\n pass\n \n # reform dataframes\n DFF_m = pd.DataFrame(filt_m, index=DFF.index, columns=DFF_header)\n DFF_w = pd.DataFrame(filt_w, index=DFF.index, columns=DFF_header)\n DFF_d = pd.DataFrame(filt_array, index=DFF.index, columns=DFF_header)\n\n# Climatology with Standard Deviation\n clim_DFF = pd.DataFrame(index = np.arange(1,54), columns = DFF_d.columns)\n clim_std_DFF = pd.DataFrame(index = np.arange(1,54), columns = DFF_d.columns)\n for w in np.arange(1,54):\n DFFmask = DFF_d[DFF_d.index.week == w]\n clim_DFF.ix[w] = np.nanmean(DFFmask, axis=0)\n clim_std_DFF.ix[w] = np.nanstd(DFFmask, axis=0)\n # Dataframes have index of ordinal weeks, convert to date range using\n # clim_DFF.index = pd.date_range(start='', periods=len(clim_DFF),freq='W')\n # with starting year as start, ie. '2014'.\n\n# Save dataframes to dictionaries\n ndbc_df_m[sn] = DFF_m\n ndbc_df_w[sn] = DFF_w\n ndbc_df_d[sn] = DFF_d\n ndbc_clim[sn] = clim_DFF\n ndbc_clim_std[sn] = clim_std_DFF\n\n# Save dictionaries\nfn_m = open(os.path.join(dirname,'ndbc_df_m.txt'),'wb')\npickle.dump(ndbc_df_m, fn_m)\nfn_w = open(os.path.join(dirname,'ndbc_df_w.txt'),'wb')\npickle.dump(ndbc_df_w, fn_w)\nfn_d = open(os.path.join(dirname,'ndbc_df_d.txt'),'wb')\npickle.dump(ndbc_df_d, fn_d)\n\nfn_clim = open(os.path.join(dirname,'ndbc_clim_df.txt'),'wb')\npickle.dump(ndbc_clim, fn_clim)\nfn_clim_std = open(os.path.join(dirname,'ndbc_clim_std_df.txt'),'wb')\npickle.dump(ndbc_clim_std, fn_clim_std)\n\n# Unit dictionary\nheader = pd.read_csv(fn, nrows=1, delim_whitespace=True)\nunit_dict = dict(header.ix[0])\nunit_dict['taux'] = 'Pa'\nunit_dict['tauy'] = 'Pa'\nunit_dict['WSPD_10'] = unit_dict['WSPD']\nunit_dict['Uwind'] = unit_dict['WSPD']\nunit_dict['Vwind'] = unit_dict['WSPD']\n\nfn_head = open(os.path.join(dirname,'ndbc_unit_dict.txt'),'wb')\npickle.dump(unit_dict, fn_head)\n","sub_path":"ndbc/process_ndbc.py","file_name":"process_ndbc.py","file_ext":"py","file_size_in_byte":10777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"61656825","text":"# boto3 implementation of\n# https://gist.github.com/shadiakiki1986/f6e676d1ab5800fcf7899b6a392ab821\n# Docs\n# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudtrail.html#CloudTrail.Client.get_paginator\n#\n# Requirements: pip3 install boto3 tqdm pandas\n# Run: python3 t2.py\n#\n# Edit 2019-09-13: copied file pull_cloudtrail_lookupEvents.py from git-remote-aws into isitfit so as to avoid confusion in download statistics\n#----------------------------------------\n\n# imports\nimport datetime as dt\nfrom dateutil.relativedelta import relativedelta\nimport boto3\nimport json\n\nfrom isitfit.utils import logger\n\n\n#------------------------------\n# utility to serialize date\n#def json_serial(obj):\n# \"\"\"JSON serializer for objects not serializable by default json code\"\"\"\n#\n# if isinstance(obj, (dt.datetime, dt.date)):\n# return obj.isoformat()\n# raise TypeError (\"Type %s not serializable\" % type(obj))\n\n\n#----------------------------------------\n# iterate\n\n# use jmespath like awscli\n# https://stackoverflow.com/a/57018780/4126114\n# Example\n# >>> mydata\n# {'foo': {'bar': [{'name': 'one'}, {'name': 'two'}]}}\n# >>> jmespath.search('foo.bar[?name==`one`]', mydata)\n# [{'name': 'one'}]\n# import jmespath\n\n#----------------------------------------\nclass EventIterator:\n eventName = None\n \n # get paginator\n def iterate_page(self):\n \"\"\"\n eventName - eg 'ModifyInstanceAttribute'\n \"\"\"\n if self.eventName is None:\n raise Exception(\"Derived class should set class member eventName\")\n\n # arguments to lookup-events command\n # From docs: \"Currently the list can contain only one item\"\n LookupAttributes=[\n # {'AttributeKey': 'EventSource', 'AttributeValue': 'ec2.amazonaws.com'},\n {'AttributeKey': 'EventName', 'AttributeValue': self.eventName},\n ]\n\n # go back x time\n # https://stackoverflow.com/a/38795526/4126114\n # StartTime=dt.datetime.now() - relativedelta(years=1)\n # StartTime=dt.datetime.now() - relativedelta(days=90)\n PaginationConfig={\n 'MaxResults': 3000\n }\n\n # edit 2019-11-20 instead of defining this client in Gra... and passing it through several layers,\n # just define it here\n # Note 2019-12-09 Cloudtrail can return a max of 90 days\n # In this class, the start/end dates are not specified so as to fetch the whole 90 days and cache them\n # Not very efficient, but works ATM. This is not a per EC2/Redshift call\n # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudtrail.html#CloudTrail.Client.lookup_events\n # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudtrail.html#CloudTrail.Paginator.LookupEvents\n client = boto3.client('cloudtrail')\n self.region_name = client.meta.region_name\n cp = client.get_paginator(operation_name=\"lookup_events\")\n iterator = cp.paginate(\n LookupAttributes=LookupAttributes, \n #StartTime=StartTime, \n PaginationConfig=PaginationConfig\n )\n return iterator\n\n\n def iterate_event(self):\n iter_wrap = self.iterate_page()\n # Update 2019-11-22 moved this tqdm to the region level since it's already super fast per event\n #iter_wrap = tqdm(iter_wrap, desc=\"Cloudtrail events for %s/%s\"%(self.region_name, self.eventName))\n for response in iter_wrap:\n #with open('t2.json','w') as fh:\n # json.dump(response, fh, default=json_serial)\n\n # print(response.keys())\n for event in response['Events']:\n result = self._handleEvent(event)\n if result is None: continue\n yield result\n\n\n def _handleEvent(self, event):\n # raise Exception(\"Implement by derived classes\")\n return event\n\n\nclass RedshiftCreate(EventIterator):\n eventName = \"CreateCluster\"\n \n def _handleEvent(self, event):\n # logger.debug(\"Cloudtrail event: %s\"%json.dumps(event, default=json_serial))\n\n if 'Resources' not in event:\n logger.debug(\"No 'Resources' key in event. Skipping\")\n return None # ignore this situation\n \n instanceId = [x for x in event['Resources'] if x['ResourceType']=='AWS::Redshift::Cluster']\n if len(instanceId)==0:\n logger.debug(\"No AWS redshift clusters in event. Skipping\")\n return None # ignore this situation\n\n # proceed\n instanceId = instanceId[0]\n\n if 'ResourceName' not in instanceId:\n logger.debug(\"No ResourceName key in event. Skipping\")\n return None # ignore this situation\n \n # proceed\n instanceId = instanceId['ResourceName']\n\n if 'CloudTrailEvent' not in event:\n logger.debug(\"No CloudTrailEvent key in event. Skipping\")\n return None # ignore this situation\n\n ce_dict = json.loads(event['CloudTrailEvent'])\n\n import jmespath\n nodeType = jmespath.search('requestParameters.nodeType', ce_dict)\n numberOfNodes = jmespath.search('requestParameters.numberOfNodes', ce_dict)\n if numberOfNodes is None:\n numberOfNodes = jmespath.search('responseElements.numberOfNodes', ce_dict)\n\n if nodeType is None:\n logger.debug(\"No nodeType key in event['CloudTrailEvent']['requestParameters']. Skipping\")\n return None # ignore this situation\n\n if numberOfNodes is None:\n logger.debug(\"No numberOfNodes key in event['CloudTrailEvent']['requestParameters']. Skipping\")\n return None # ignore this situation\n\n if 'EventTime' not in event:\n logger.debug(\"No EventTime key in event. Skipping\")\n return None # ignore this situation\n\n ts_obj = event['EventTime']\n # ts_obj = dt.datetime.utcfromtimestamp(ts_int)\n # ts_str = ts_obj.strftime('%Y-%m-%d %H:%M:%S')\n\n result = {\n 'ServiceName': 'Redshift', # bugfix: was using Ec2 instead of Redshift\n 'EventName': self.eventName,\n 'EventTime': ts_obj, # ts_str,\n 'ResourceName': instanceId,\n 'ResourceSize1': nodeType,\n 'ResourceSize2': numberOfNodes,\n }\n\n return result\n\n \n \nclass Ec2Run(EventIterator):\n eventName = \"RunInstances\"\n \n def _handleEvent(self, event):\n # logger.debug(\"Cloudtrail event: %s\"%json.dumps(event, default=json_serial))\n\n if 'Resources' not in event:\n logger.debug(\"No 'Resources' key in event. Skipping\")\n return None # ignore this situation\n \n instanceId = [x for x in event['Resources'] if x['ResourceType']=='AWS::EC2::Instance']\n if len(instanceId)==0:\n logger.debug(\"No AWS EC2 instances in event. Skipping\")\n return None # ignore this situation\n\n # proceed\n instanceId = instanceId[0]\n\n if 'ResourceName' not in instanceId:\n logger.debug(\"No ResourceName key in event. Skipping\")\n return None # ignore this situation\n \n # proceed\n instanceId = instanceId['ResourceName']\n\n if 'CloudTrailEvent' not in event:\n logger.debug(\"No CloudTrailEvent key in event. Skipping\")\n return None # ignore this situation\n\n ce_dict = json.loads(event['CloudTrailEvent'])\n\n if 'requestParameters' not in ce_dict:\n logger.debug(\"No requestParameters key in event['CloudTrailEvent']. Skipping\")\n return None # ignore this situation\n\n if 'instanceType' not in ce_dict['requestParameters']:\n logger.debug(\"No instanceType key in event['CloudTrailEvent']['requestParameters']. Skipping\")\n return None # ignore this situation\n\n newType = ce_dict['requestParameters']['instanceType']\n\n if 'EventTime' not in event:\n logger.debug(\"No EventTime key in event. Skipping\")\n return None # ignore this situation\n\n ts_obj = event['EventTime']\n # ts_obj = dt.datetime.utcfromtimestamp(ts_int)\n # ts_str = ts_obj.strftime('%Y-%m-%d %H:%M:%S')\n\n result = {\n 'ServiceName': 'EC2',\n 'EventName': self.eventName,\n 'EventTime': ts_obj, # ts_str,\n 'ResourceName': instanceId,\n 'ResourceSize1': newType,\n 'ResourceSize2': None\n }\n\n return result\n \n \nclass Ec2Modify(EventIterator):\n eventName = \"ModifyInstanceAttribute\"\n \n def _handleEvent(self, event):\n if 'CloudTrailEvent' not in event:\n logger.debug(\"No CloudTrailEvent key in event. Skipping\")\n return None # ignore this situation\n\n ce_dict = json.loads(event['CloudTrailEvent'])\n\n if 'requestParameters' not in ce_dict:\n logger.debug(\"No requestParameters key in event['CloudTrailEvent']. Skipping\")\n return None # ignore this situation\n\n rp_dict = ce_dict['requestParameters']\n newType = None\n\n #newType = jmespath.search('instanceType', rp_dict)\n #if newType is None:\n # newType = jmespath.search('attributeName==`instanceType`', rp_dict)\n\n if 'instanceType' in rp_dict:\n # logging.error(json.dumps(rp_dict))\n newType = rp_dict['instanceType']['value']\n\n if 'attribute' in rp_dict:\n if rp_dict['attribute']=='instanceType':\n newType = rp_dict['value']\n\n if newType is None:\n return None\n\n ts_obj = event['EventTime']\n # ts_obj = dt.datetime.utcfromtimestamp(ts_int)\n # ts_str = ts_obj.strftime('%Y-%m-%d %H:%M:%S')\n\n if 'instanceId' not in rp_dict:\n logger.debug(\"No instanceId key in requestParameters. Skipping\")\n return None # ignore this situation\n\n result = {\n 'ServiceName': 'EC2',\n 'EventName': self.eventName,\n 'EventTime': ts_obj, # ts_str,\n 'ResourceName': rp_dict['instanceId'],\n 'ResourceSize1': newType,\n 'ResourceSize2': None\n }\n\n return result\n\n\nclass RedshiftResize(EventIterator):\n eventName = \"ResizeCluster\"\n \n def _handleEvent(self, event):\n if 'CloudTrailEvent' not in event:\n logger.debug(\"No CloudTrailEvent key in event. Skipping\")\n return None # ignore this situation\n\n ce_dict = json.loads(event['CloudTrailEvent'])\n\n if 'requestParameters' not in ce_dict:\n logger.debug(\"No requestParameters key in event['CloudTrailEvent']. Skipping\")\n return None # ignore this situation\n\n rp_dict = ce_dict['requestParameters']\n\n import jmespath\n nodeType = jmespath.search('instanceType', rp_dict)\n numberOfNodes = jmespath.search('numberOfNodes', rp_dict)\n\n ts_obj = event['EventTime']\n # ts_obj = dt.datetime.utcfromtimestamp(ts_int)\n # ts_str = ts_obj.strftime('%Y-%m-%d %H:%M:%S')\n\n result = {\n 'ServiceName': 'Redshift',\n 'ResourceName': rp_dict['clusterIdentifier'],\n 'EventTime': ts_obj, # ts_str,\n\n 'EventName': self.eventName,\n 'ResourceSize1': nodeType,\n 'ResourceSize2': numberOfNodes,\n\n }\n\n return result\n\n\nimport pandas as pd\n\nclass EventAggregatorOneRegion:\n def get(self):\n from termcolor import colored\n import botocore\n import sys\n\n def run_iterator(man2_i):\n try:\n r_i = list(man2_i.iterate_event())\n except botocore.exceptions.ClientError as e:\n # display error message without the frightening traceback\n from isitfit.cli.click_descendents import IsitfitCliError\n raise IsitfitCliError(str(e))\n\n return r_i\n\n man2_ec2run = Ec2Run()\n r_ec2run = run_iterator(man2_ec2run)\n \n man2_ec2mod = Ec2Modify()\n r_ec2mod = run_iterator(man2_ec2mod)\n \n man2_rscre = RedshiftCreate()\n r_rscre = run_iterator(man2_rscre)\n\n man2_rsmod = RedshiftResize()\n r_rsmod = run_iterator(man2_rsmod)\n\n # split on instance ID and gather\n r_all = r_ec2run + r_ec2mod + r_rscre + r_rsmod\n # logging.error(r_all)\n df = pd.DataFrame(r_all)\n\n if df.shape[0]==0:\n # early return\n return df\n\n df = df.set_index([\"ServiceName\", \"ResourceName\", \"EventTime\"]).sort_index()\n \n return df\n\n\n\nclass EventAggregatorAllRegions(EventAggregatorOneRegion):\n def __init__(self, region_include, tqdmman):\n self.region_include = region_include\n self.tqdmman = tqdmman\n\n def get(self):\n # get cloudtrail ec2 type changes for all instances\n logger.debug(\"Downloading cloudtrail data (from %i regions)\"%len(self.region_include))\n df_2 = []\n import boto3\n\n # add some spaces for aligning the progress bars\n desc=\"Cloudtrail events in all regions\"\n desc = \"%-50s\"%desc\n\n iter_wrap = self.region_include\n iter_wrap = self.tqdmman(iter_wrap, desc=desc, total=len(self.region_include))\n for region_name in iter_wrap:\n boto3.setup_default_session(region_name = region_name)\n df_1 = super().get()\n df_1['Region'] = region_name # bugfix, field name was \"region\" (lower-case)\n df_2.append(df_1.reset_index())\n\n # concatenate\n df_3 = pd.concat(df_2, axis=0, sort=False)\n\n # check if empty\n if df_3.shape[0]==0:\n return df_3\n\n # sort again\n df_3 = df_3.set_index([\"Region\", \"ServiceName\", \"ResourceName\", \"EventTime\"]).sort_index()\n\n return df_3\n\n\n\n\nclass EventAggregatorCached(EventAggregatorAllRegions):\n cache_key = \"cloudtrail_ec2type._fetch\"\n\n def __init__(self, region_include, tqdmman, cache_man):\n super().__init__(region_include, tqdmman)\n self.cache_man = cache_man\n\n\n def get(self):\n # get cloudtrail ec2 type changes for all instances\n\n # if not configured, just return\n if self.cache_man is None:\n df_fresh = super().get()\n return df_fresh\n\n # check cache first\n if self.cache_man.isReady():\n df_cache = self.cache_man.get(self.cache_key)\n if df_cache is not None:\n logger.debug(\"Found cloudtrail data in redis cache\")\n return df_cache\n\n # if no cache, then download\n df_fresh = super().get()\n\n # if caching enabled, store it for later fetching\n # https://stackoverflow.com/a/57986261/4126114\n if self.cache_man.isReady():\n self.cache_man.set(self.cache_key, df_fresh)\n\n # done\n return df_fresh\n\n\n\n\n\ndef dict2service(ec2_dict):\n if 'InstanceId' in ec2_dict: return 'EC2'\n if 'ClusterIdentifier' in ec2_dict: return 'Redshift'\n import json\n raise Exception(\"Unknown service found in %s\"%json.dumps(ec2_dict))\n\n\n\nclass EventAggregatorPostprocessed(EventAggregatorCached):\n def __init__(self, region_include, tqdmman, cache_man, EndTime):\n super().__init__(region_include, tqdmman, cache_man)\n self.EndTime = EndTime\n\n\n def get(self, ec2_instances, n_ec2):\n self.df_cloudtrail = super().get()\n\n # first pass to append ec2 types to cloudtrail based on \"now\"\n self.df_cloudtrail = self.df_cloudtrail.reset_index()\n\n # add some spaces for aligning the progress bars\n desc = \"Pass 1/2 Cloudtrail history (EC2, Redshift)\"\n desc = \"%-50s\"%desc\n\n # Edit 2019-11-12 use initial=0 otherwise if \"=1\" used then the tqdm output would be \"101it\" at conclusion, i.e.\n # First pass through EC2 instances: 101it [00:05, 5.19it/s]\n t_iter = ec2_instances\n t_iter = self.tqdmman(t_iter, total=n_ec2, desc=desc, initial=0)\n for ec2_dict, ec2_id, ec2_launchtime, ec2_obj in t_iter:\n self._appendNow(ec2_dict, ec2_id)\n\n # if still no data, just return\n if self.df_cloudtrail.shape[0]==0:\n return self.df_cloudtrail\n\n # set index again, and sort decreasing this time (not like git-remote-aws default)\n # The descending sort is very important for the mergeTimeseries... function\n self.df_cloudtrail = self.df_cloudtrail.set_index([\"Region\", \"ServiceName\", \"ResourceName\", \"EventTime\"]).sort_index(ascending=False)\n\n # done\n return self.df_cloudtrail\n\n\n def _appendNow(self, ec2_dict, ec2_id):\n # artificially append an entry for \"now\" with the current type\n # This is useful for instance who have no entries in the cloudtrail\n # so that their type still shows up on merge\n\n ec2_dict['ServiceName'] = dict2service(ec2_dict)\n\n size1_key = 'NodeType' if ec2_dict['ServiceName']=='Redshift' else 'InstanceType'\n size2_val = ec2_dict['NumberOfNodes'] if ec2_dict['ServiceName']=='Redshift' else None\n\n df_new = pd.DataFrame([\n {\n 'Region': ec2_dict['Region'],\n 'ServiceName': ec2_dict['ServiceName'],\n 'ResourceName': ec2_id,\n 'EventTime': self.EndTime,\n 'ResourceSize1': ec2_dict[size1_key],\n 'ResourceSize2': size2_val\n }\n ])\n\n self.df_cloudtrail = pd.concat([self.df_cloudtrail, df_new], sort=True)\n\n","sub_path":"isitfit/cost/cloudtrail_iterator.py","file_name":"cloudtrail_iterator.py","file_ext":"py","file_size_in_byte":17616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134280172","text":"from __future__ import absolute_import, division, print_function\n\n\"\"\"\nPython attributes without boilerplate.\n\"\"\"\n\n\n__version__ = \"14.0dev\"\n__author__ = \"Hynek Schlawack\"\n__license__ = \"MIT\"\n__copyright__ = \"Copyright 2014 Hynek Schlawack\"\n\n__all__ = [\n \"Attribute\",\n \"NOTHING\",\n \"attributes\",\n \"with_cmp\",\n \"with_init\",\n \"with_repr\",\n]\n\n\nclass _Nothing(object):\n \"\"\"\n Sentinel class to indicate the lack of a value when ``None`` is ambiguous.\n\n .. versionadded:: 14.0\n \"\"\"\n def __repr__(self):\n return \"NOTHING\"\n\n\nNOTHING = _Nothing()\n\"\"\"\nSentinel to indicate the lack of a value when ``None`` is ambiguous.\n\n.. versionadded:: 14.0\n\"\"\"\n\n\nclass Attribute(object):\n \"\"\"\n A representation of an attribute.\n\n In the simplest case, it only consists of a name but more advanced\n properties like default values are possible too.\n\n :param name: Name of the attribute.\n :type name: str\n\n :param default_value: A value that is used whenever this attribute isn't\n passed as an keyword argument to a class that is decorated using\n :func:`with_init` (or :func:`attributes` with ``create_init=True``).\n\n Therefore, setting this makes an attribute *optional*.\n\n Since a default value of `None` would be ambiguous, a special sentinel\n :data:`NOTHING` is used. Passing it means the lack of a default value.\n :param default_factory: A factory that is used for generating default\n values whenever this attribute isn't passed as an keyword\n argument to a class that is decorated using :func:`with_init` (or\n :func:`attributes` with ``create_init=True``).\n\n Therefore, setting this makes an attribute *optional*.\n :type default_factory: callable\n\n :raises ValueError: If both ``default_value`` and ``default_factory`` have\n been passed.\n\n .. versionadded:: 14.0\n \"\"\"\n __slots__ = [\"name\", \"_default\", \"_default_factory\"]\n\n def __init__(self, name, default_value=NOTHING, default_factory=None):\n if (\n default_value is not NOTHING\n and default_factory is not None\n ):\n raise ValueError(\n \"Passing both default_value and default_factory is \"\n \"ambiguous.\"\n )\n\n self.name = name\n if default_value is not NOTHING:\n self._default = default_value\n elif default_factory is not None:\n self._default_factory = default_factory\n else:\n self._default = NOTHING\n\n def __getattr__(self, name):\n \"\"\"\n If no value has been set to _default, we need to call a factory.\n \"\"\"\n if name == \"_default\" and self._default_factory:\n return self._default_factory()\n else:\n raise AttributeError\n\n\ndef _ensure_attributes(attrs):\n \"\"\"\n Return a list of :class:`Attribute` generated by creating new instances for\n all non-Attributes.\n \"\"\"\n return [\n Attribute(a) if not isinstance(a, Attribute) else a\n for a in attrs\n ]\n\n\ndef with_cmp(attrs):\n \"\"\"\n A class decorator that adds comparison methods based on *attrs*.\n\n For that, each class is treated like a ``tuple`` of the values of *attrs*.\n But only instances of *identical* classes are compared!\n\n :param attrs: Attributes to work with.\n :type attrs: :class:`list` of :class:`str` or :class:`Attribute`\\ s.\n \"\"\"\n def attrs_to_tuple(obj):\n \"\"\"\n Create a tuple of all values of *obj*'s *attrs*.\n \"\"\"\n return tuple(getattr(obj, a.name) for a in attrs)\n\n def eq(self, other):\n \"\"\"\n Automatically created by characteristic.\n \"\"\"\n if other.__class__ is self.__class__:\n return attrs_to_tuple(self) == attrs_to_tuple(other)\n else:\n return NotImplemented\n\n def ne(self, other):\n \"\"\"\n Automatically created by characteristic.\n \"\"\"\n result = eq(self, other)\n if result is NotImplemented:\n return NotImplemented\n else:\n return not result\n\n def lt(self, other):\n \"\"\"\n Automatically created by characteristic.\n \"\"\"\n if other.__class__ is self.__class__:\n return attrs_to_tuple(self) < attrs_to_tuple(other)\n else:\n return NotImplemented\n\n def le(self, other):\n \"\"\"\n Automatically created by characteristic.\n \"\"\"\n if other.__class__ is self.__class__:\n return attrs_to_tuple(self) <= attrs_to_tuple(other)\n else:\n return NotImplemented\n\n def gt(self, other):\n \"\"\"\n Automatically created by characteristic.\n \"\"\"\n if other.__class__ is self.__class__:\n return attrs_to_tuple(self) > attrs_to_tuple(other)\n else:\n return NotImplemented\n\n def ge(self, other):\n \"\"\"\n Automatically created by characteristic.\n \"\"\"\n if other.__class__ is self.__class__:\n return attrs_to_tuple(self) >= attrs_to_tuple(other)\n else:\n return NotImplemented\n\n def hash_(self):\n \"\"\"\n Automatically created by characteristic.\n \"\"\"\n return hash(attrs_to_tuple(self))\n\n def wrap(cl):\n cl.__eq__ = eq\n cl.__ne__ = ne\n cl.__lt__ = lt\n cl.__le__ = le\n cl.__gt__ = gt\n cl.__ge__ = ge\n cl.__hash__ = hash_\n\n return cl\n\n attrs = _ensure_attributes(attrs)\n return wrap\n\n\ndef with_repr(attrs):\n \"\"\"\n A class decorator that adds a human readable ``__repr__`` method to your\n class using *attrs*.\n\n :param attrs: Attributes to work with.\n :type attrs: ``list`` of :class:`str` or :class:`Attribute`\\ s.\n \"\"\"\n def repr_(self):\n \"\"\"\n Automatically created by characteristic.\n \"\"\"\n return \"<{0}({1})>\".format(\n self.__class__.__name__,\n \", \".join(a.name + \"=\" + repr(getattr(self, a.name))\n for a in attrs)\n )\n\n def wrap(cl):\n cl.__repr__ = repr_\n return cl\n\n attrs = _ensure_attributes(attrs)\n return wrap\n\n\ndef with_init(attrs, defaults=None):\n \"\"\"\n A class decorator that wraps the ``__init__`` method of a class and sets\n *attrs* using passed *keyword arguments* before calling the original\n ``__init__``.\n\n Those keyword arguments that are used, are removed from the `kwargs` that\n is passed into your original ``__init__``. Optionally, a dictionary of\n default values for some of *attrs* can be passed too.\n\n :param attrs: Attributes to work with.\n :type attrs: ``list`` of :class:`str` or :class:`Attribute`\\ s.\n\n :raises ValueError: If the value for a non-optional attribute hasn't been\n passed as a keyword argument.\n :raises ValueError: If both *defaults* and an instance of\n :class:`Attribute` has been passed.\n\n .. deprecated:: 14.0\n Use :class:`Attribute` instead of ``defaults``.\n\n :param defaults: Default values if attributes are omitted on instantiation.\n :type defaults: ``dict`` or ``None``\n \"\"\"\n if defaults is None:\n defaults = {}\n\n def init(self, *args, **kw):\n \"\"\"\n Attribute initializer automatically created by characteristic.\n\n The original `__init__` method is renamed to `__original_init__` and\n is called at the end with the initialized attributes removed from the\n keyword arguments.\n \"\"\"\n for a in attrs:\n v = kw.pop(a.name, NOTHING)\n if v is NOTHING:\n # Since ``a._default`` could be a property that calls\n # a factory, we make this a separate step.\n v = a._default\n if v is NOTHING:\n raise ValueError(\n \"Missing keyword value for '{0}'.\".format(a.name)\n )\n setattr(self, a.name, v)\n self.__original_init__(*args, **kw)\n\n def wrap(cl):\n cl.__original_init__ = cl.__init__\n cl.__init__ = init\n return cl\n\n new_attrs = []\n for a in attrs:\n if isinstance(a, Attribute):\n if defaults != {}:\n raise ValueError(\n \"Mixing of the 'defaults' keyword argument and passing \"\n \"instances of Attribute for 'attrs' is prohibited. \"\n \"Please don't use 'defaults' anymore, it has been \"\n \"deprecated in 14.0.\"\n )\n new_attrs.append(a)\n else:\n default_value = defaults.get(a)\n if default_value:\n new_attrs.append(\n Attribute(a, default_value=default_value)\n )\n else:\n new_attrs.append(Attribute(a))\n\n attrs = new_attrs\n return wrap\n\n\ndef attributes(attrs, defaults=None, create_init=True):\n \"\"\"\n A convenience class decorator that combines :func:`with_cmp`,\n :func:`with_repr`, and optionally :func:`with_init` to avoid code\n duplication.\n\n :param attrs: Attributes to work with.\n :type attrs: ``list`` of :class:`str` or :class:`Attribute`\\ s.\n\n :param create_init: Also apply :func:`with_init` (default: ``True``)\n :type create_init: ``bool``\n\n :raises ValueError: If the value for a non-optional attribute hasn't been\n passed as a keyword argument.\n :raises ValueError: If both *defaults* and an instance of\n :class:`Attribute` has been passed.\n\n .. versionadded:: 14.0\n Added possibility to pass instances of :class:`Attribute` in ``attrs``.\n\n .. deprecated:: 14.0\n Use :class:`Attribute` instead of ``defaults``.\n\n :param defaults: Default values if attributes are omitted on instantiation.\n :type defaults: ``dict`` or ``None``\n \"\"\"\n def wrap(cl):\n cl = with_cmp(attrs)(with_repr(attrs)(cl))\n if create_init is True:\n return with_init(attrs, defaults=defaults)(cl)\n else:\n return cl\n return wrap\n","sub_path":"characteristic.py","file_name":"characteristic.py","file_ext":"py","file_size_in_byte":10070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"25399602","text":"'''LC1499: Max Value of Equation\nhttps://leetcode.com/problems/max-value-of-equation/\nGiven an array points containing the coordinates of\npoints on a 2D plane, sorted by the x-values,\nwhere points[i] = [xi, yi] such that xi < xj for\nall 1 <= i < j <= points.length. You are also given an integer k.\n\nFind the maximum value of the equation yi + yj + |xi - xj|\nwhere |xi - xj| <= k and 1 <= i < j <= points.length.\nIt is guaranteed that there exists at least one pair\nof points that satisfy the constraint |xi - xj| <= k.\n\nExample 1:\nInput: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1\nOutput: 4\nExplanation: The first two points satisfy the condition\n|xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4.\nThird and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.\nNo other pairs satisfy the condition, so we return the max of 4 and 1.\nExample 2:\nInput: points = [[0,0],[3,0],[9,2]], k = 3\nOutput: 3\nExplanation: Only the first two points have an absolute\ndifference of 3 or less in the x-values, and give the\nvalue of 0 + 0 + |0 - 3| = 3.'''\nclass Sln(object):\n def findMaxValueOfEquation(self, A, k):\n q = collections.deque()\n res = -float('inf')\n for x, y in A:\n while q and q[0][1] < x - k:\n q.popleft()\n if q: res = max(res, q[0][0] + y + x)\n while q and q[-1][0] <= y - x:\n q.pop()\n q.append([y - x, x])\n return res\n\n","sub_path":"src/Interview_exp/goog/max_val_eqns/MaValEqns.py","file_name":"MaValEqns.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"62893534","text":"# -*- coding: utf-8 -*-\nimport gevent\nfrom gevent.lock import Semaphore\nfrom gevent.event import AsyncResult\n\nfrom ethereum import slogging\n\nfrom raiden.exceptions import DuplicatedChannelError\nfrom raiden.api.python import RaidenAPI\nfrom raiden.utils import pex\nfrom raiden.transfer.state import (\n CHANNEL_STATE_OPENED,\n CHANNEL_STATE_CLOSED,\n CHANNEL_STATE_SETTLED,\n)\nfrom raiden.exceptions import (\n AddressWithoutCode,\n TransactionThrew,\n)\n\nlog = slogging.get_logger(__name__) # pylint: disable=invalid-name\n\n\nclass ConnectionManager(object):\n \"\"\"The ConnectionManager provides a high level abstraction for connecting to a\n Token network.\n\n Note:\n It is initialized with 0 funds; a connection to the token network\n will be only established _after_ calling `connect(funds)`\n \"\"\"\n # XXX Hack: for bootstrapping, the first node on a network opens a channel\n # with this address to become visible.\n BOOTSTRAP_ADDR_HEX = '2' * 40\n BOOTSTRAP_ADDR = BOOTSTRAP_ADDR_HEX.decode('hex')\n\n def __init__(\n self,\n raiden,\n token_address,\n channelgraph):\n self.lock = Semaphore()\n self.raiden = raiden\n self.api = RaidenAPI(raiden)\n self.channelgraph = channelgraph\n self.token_address = token_address\n self.funds = 0\n self.initial_channel_target = 0\n self.joinable_funds_target = 0\n\n def connect(\n self,\n funds,\n initial_channel_target=3,\n joinable_funds_target=.4):\n \"\"\"Connect to the network.\n Use this to establish a connection with the token network.\n\n Subsequent calls to `connect` are allowed, but will only affect the spendable\n funds and the connection strategy parameters for the future. `connect` will not\n close any channels.\n\n Note: the ConnectionManager does not discriminate manually opened channels from\n automatically opened ones. If the user manually opened channels, those deposit\n amounts will affect the funding per channel and the number of new channels opened.\n\n Args:\n funds (int): the amount of tokens spendable for this\n ConnectionManager.\n initial_channel_target (int): number of channels to open immediately\n joinable_funds_target (float): amount of funds not initially assigned\n \"\"\"\n if funds <= 0:\n raise ValueError('connecting needs a positive value for `funds`')\n\n if self.token_address in self.raiden.message_handler.blocked_tokens:\n self.raiden.message_handler.blocked_tokens.pop(self.token_address)\n\n self.initial_channel_target = initial_channel_target\n self.joinable_funds_target = joinable_funds_target\n\n open_channels = self.open_channels\n # there are already channels open\n if len(open_channels):\n log.debug(\n 'connect() called on an already joined token network',\n token_address=pex(self.token_address),\n open_channels=len(open_channels),\n sum_deposits=self.sum_deposits,\n funds=funds,\n )\n\n if len(self.channelgraph.graph.nodes()) == 0:\n with self.lock:\n log.debug('bootstrapping token network.')\n # make ourselves visible\n self.api.open(\n self.token_address,\n ConnectionManager.BOOTSTRAP_ADDR\n )\n\n with self.lock:\n # set our available funds\n self.funds = funds\n # try to fullfill our connection goal\n self._add_new_partners()\n\n def leave_async(self):\n \"\"\" Async version of `leave()`\n \"\"\"\n leave_result = AsyncResult()\n gevent.spawn(self.leave).link(leave_result)\n return leave_result\n\n def leave(self, only_receiving=True):\n \"\"\" Leave the token network.\n This implies closing all channels and waiting for all channels to be settled.\n \"\"\"\n # set leaving state\n if self.token_address not in self.raiden.message_handler.blocked_tokens:\n self.raiden.message_handler.blocked_tokens.append(self.token_address)\n if self.initial_channel_target > 0:\n self.initial_channel_target = 0\n\n closed_channels = self.close_all(only_receiving)\n self.wait_for_settle(closed_channels)\n return closed_channels\n\n def close_all(self, only_receiving=True):\n \"\"\" Close all channels in the token network.\n Note: By default we're just discarding all channels we haven't received anything.\n This potentially leaves deposits locked in channels after `closing`. This is \"safe\"\n from an accounting point of view (deposits can not be lost), but may still be\n undesirable from a liquidity point of view (deposits will only be freed after\n manually closing or after the partner closed the channel).\n\n If only_receiving is False then we close and settle all channels irrespective of them\n having received transfers or not.\n \"\"\"\n with self.lock:\n self.initial_channel_target = 0\n channels_to_close = (\n self.receiving_channels[:] if only_receiving else self.open_channels[:]\n )\n for channel in channels_to_close:\n # FIXME: race condition, this can fail if channel was closed externally\n self.api.close(self.token_address, channel.partner_address)\n return channels_to_close\n\n def wait_for_settle(self, closed_channels):\n \"\"\"Wait for all closed channels of the token network to settle.\n Note, that this does not time out.\n \"\"\"\n not_settled_channels = [\n channel for channel in closed_channels\n if not channel.state != CHANNEL_STATE_SETTLED\n ]\n while any(c.state != CHANNEL_STATE_SETTLED for c in not_settled_channels):\n # wait for events to propagate\n gevent.sleep(self.raiden.alarm.wait_time)\n return True\n\n def join_channel(self, partner_address, partner_deposit):\n \"\"\"Will be called, when we were selected as channel partner by another\n node. It will fund the channel with up to the partner's deposit, but\n not more than remaining funds or the initial funding per channel.\n\n If the connection manager has no funds, this is a noop.\n \"\"\"\n # not initialized\n if self.funds <= 0:\n return\n # in leaving state\n if self.leaving_state:\n return\n with self.lock:\n remaining = self.funds_remaining\n initial = self.initial_funding_per_partner\n joining_funds = min(\n partner_deposit,\n remaining,\n initial\n )\n if joining_funds <= 0:\n return\n\n self.api.deposit(\n self.token_address,\n partner_address,\n joining_funds\n )\n log.debug(\n 'joined a channel!',\n funds=joining_funds,\n me=pex(self.raiden.address),\n partner=pex(partner_address)\n )\n\n def retry_connect(self):\n \"\"\"Will be called when new channels in the token network are detected.\n If the minimum number of channels was not yet established, it will try\n to open new channels.\n\n If the connection manager has no funds, this is a noop.\n \"\"\"\n # not initialized\n if self.funds <= 0:\n return\n # in leaving state\n if self.leaving_state:\n return\n with self.lock:\n if self.funds_remaining <= 0:\n return\n if len(self.open_channels) >= self.initial_channel_target:\n return\n\n # try to fullfill our connection goal\n self._add_new_partners()\n\n def _add_new_partners(self):\n \"\"\" This opens channels with a number of new partners according to the\n connection strategy parameter `self.initial_channel_target`.\n Each new channel will receive `self.initial_funding_per_partner` funding. \"\"\"\n # this could be a subsequent call, or some channels already open\n new_partner_count = max(\n 0,\n self.initial_channel_target - len(self.open_channels)\n )\n for partner in self.find_new_partners(new_partner_count):\n self._open_and_deposit(partner, self.initial_funding_per_partner)\n\n def _open_and_deposit(self, partner, funding_amount):\n \"\"\" Open a channel with `partner` and deposit `funding_amount` tokens.\n\n If the channel was already opened (a known race condition),\n this skips the opening and only deposits.\n \"\"\"\n try:\n self.api.open(\n self.token_address,\n partner\n )\n # this can fail because of a race condition, where the channel partner opens first\n except DuplicatedChannelError:\n log.info('partner opened channel first')\n\n channelgraph = self.raiden.token_to_channelgraph[self.token_address]\n if partner not in channelgraph.partneraddress_to_channel:\n self.raiden.poll_blockchain_events()\n\n if partner not in channelgraph.partneraddress_to_channel:\n log.error(\n 'Opening new channel failed; channel already opened, '\n 'but partner not in channelgraph',\n partner=pex(partner),\n token_address=pex(self.token_address),\n )\n else:\n try:\n self.api.deposit(\n self.token_address,\n partner,\n funding_amount,\n )\n except AddressWithoutCode:\n log.warn('connection manager: channel closed just after it was created')\n except TransactionThrew:\n log.exception('connection manager: deposit failed')\n\n def find_new_partners(self, number):\n \"\"\"Search the token network for potential channel partners.\n\n Args:\n number (int): number of partners to return\n \"\"\"\n known = set(c.partner_address for c in self.open_channels)\n known = known.union({self.__class__.BOOTSTRAP_ADDR})\n known = known.union({self.raiden.address})\n available = set(self.channelgraph.graph.nodes()) - known\n\n available = self._select_best_partners(available)\n log.debug('found {} partners'.format(len(available)))\n return available[:number]\n\n def _select_best_partners(self, partners):\n # FIXME: use a proper selection strategy\n # https://github.com/raiden-network/raiden/issues/576\n return list(partners)\n\n @property\n def initial_funding_per_partner(self):\n \"\"\"The calculated funding per partner depending on configuration and\n overall funding of the ConnectionManager.\n \"\"\"\n if self.initial_channel_target:\n return int(\n self.funds * (1 - self.joinable_funds_target) /\n self.initial_channel_target\n )\n else:\n return 0\n\n @property\n def wants_more_channels(self):\n \"\"\"True, if funds available and the `initial_channel_target` was not yet\n reached.\n \"\"\"\n if self.token_address in self.raiden.message_handler.blocked_tokens:\n return False\n return (\n self.funds_remaining > 0 and\n len(self.open_channels) < self.initial_channel_target\n )\n\n @property\n def funds_remaining(self):\n \"\"\"The remaining funds after subtracting the already deposited amounts.\n \"\"\"\n if self.funds > 0:\n remaining = self.funds - self.sum_deposits\n assert isinstance(remaining, int)\n return remaining\n return 0\n\n @property\n def open_channels(self):\n \"\"\"Shorthand for getting our open channels in this token network.\n \"\"\"\n return [\n channel for channel in\n self.api.get_channel_list(token_address=self.token_address)\n if channel.state == CHANNEL_STATE_OPENED\n ]\n\n @property\n def sum_deposits(self):\n \"\"\"Shorthand for getting sum of all open channels deposited funds\"\"\"\n return sum(channel.contract_balance for channel in self.open_channels)\n\n @property\n def receiving_channels(self):\n \"\"\"Shorthand for getting channels that had received any transfers in this token network.\n \"\"\"\n return [\n channel for channel in self.open_channels\n if len(channel.received_transfers)\n ]\n\n @property\n def min_settle_blocks(self):\n \"\"\"Returns the minimum necessary waiting time to settle all channels.\n \"\"\"\n channels = self.receiving_channels\n timeouts = [0]\n current_block = self.raiden.get_block_number()\n for channel in channels:\n if channel.state == CHANNEL_STATE_CLOSED:\n since_closed = current_block - channel.external_state._closed_block\n elif channel.state == CHANNEL_STATE_OPENED:\n # it will at least take one more block to call close\n since_closed = -1\n else:\n since_closed = 0\n timeouts.append(channel.settle_timeout - since_closed)\n\n return max(timeouts)\n\n @property\n def leaving_state(self):\n return (\n self.token_address in self.raiden.message_handler.blocked_tokens or\n self.initial_channel_target < 1\n )\n","sub_path":"raiden/connection_manager.py","file_name":"connection_manager.py","file_ext":"py","file_size_in_byte":13790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"283677556","text":"# -*- coding: utf-8 -*-\n#\n# MSULogWindowController.py\n# MunkiStatus\n#\n# Created by Greg Neagle on 4/18/16.\n# Copyright (c) 2017 Munki Project. All rights reserved.\n#\n# Much code borrowed from https://github.com/MagerValp/LoginLog\n# with the blessing of MagerValp\n#\n\nfrom objc import YES, NO, IBAction, IBOutlet\n# pylint: disable=wildcard-import\n# pylint: disable=unused-wildcard-import\n# pylint: disable=redefined-builtin\nfrom Foundation import *\nfrom AppKit import *\n# pylint: enable=redefined-builtin\n# pylint: enable=wildcard-import\n\nimport munki\nimport os\n\n# lots of camelCase names, following Cocoa convention\n# pylint: disable=invalid-name\n\n\nclass MSULogViewDataSource(NSObject):\n \"\"\"Data source for an NSTableView that displays an array of text lines.\n Line breaks are assumed to be LF, and partial lines from incremental\n reading is handled.\"\"\"\n\n # since this subclasses NSObject,\n # it doesn't have a Python __init__method\n # pylint: disable=no-init\n\n logFileData = NSMutableArray.alloc().init()\n filteredData = logFileData\n\n lastLineIsPartial = False\n filterText = ''\n\n def tableView_writeRowsWithIndexes_toPasteboard_(\n self, aTableView, rowIndexes, pasteboard):\n '''Implements drag-n-drop of text rows to external apps'''\n text_to_copy = ''\n index_set = aTableView.selectedRowIndexes()\n index = index_set.firstIndex()\n while index != NSNotFound:\n line = self.filteredData.objectAtIndex_(index)\n text_to_copy += line + '\\n'\n index = index_set.indexGreaterThanIndex_(index)\n #changeCount = pasteboard.clearContents()\n result = pasteboard.writeObjects_([text_to_copy])\n return YES\n\n def applyFilterToData(self):\n '''Filter our log data'''\n if len(self.filterText):\n filterPredicate = NSPredicate.predicateWithFormat_(\n 'self CONTAINS[cd] %@', self.filterText)\n self.filteredData = (\n self.logFileData.filteredArrayUsingPredicate_(filterPredicate))\n else:\n self.filteredData = self.logFileData\n\n def addLine_partial_(self, line, isPartial):\n '''Add a line to our datasource'''\n if self.lastLineIsPartial:\n joinedLine = self.logFileData.lastObject() + line\n self.logFileData.removeLastObject()\n self.logFileData.addObject_(joinedLine)\n else:\n self.logFileData.addObject_(line)\n self.lastLineIsPartial = isPartial\n self.applyFilterToData()\n\n def removeAllLines(self):\n '''Remove all data from our datasource'''\n self.logFileData.removeAllObjects()\n\n def lineCount(self):\n '''Return the number of lines in our filtered data'''\n return self.filteredData.count()\n\n def numberOfRowsInTableView_(self, tableView):\n '''Required datasource method'''\n return self.lineCount()\n\n def tableView_objectValueForTableColumn_row_(self, tableView, column, row):\n '''Required datasource method -- returns the text data for the\n given row and column'''\n if column.identifier() == 'data':\n return self.filteredData.objectAtIndex_(row)\n else:\n return ''\n\n\nclass MSULogWindowController(NSObject):\n '''Controller object for our log window'''\n\n # since this subclasses NSObject,\n # it doesn't have a Python __init__method\n # pylint: disable=no-init\n\n window = IBOutlet()\n logView = IBOutlet()\n searchField = IBOutlet()\n pathControl = IBOutlet()\n\n logFileData = MSULogViewDataSource.alloc().init()\n\n fileHandle = None\n updateTimer = None\n\n def copy_(self, sender):\n '''Implements copy operation so we can copy data from table view'''\n text_to_copy = ''\n index_set = self.logView.selectedRowIndexes()\n index = index_set.firstIndex()\n while index != NSNotFound:\n line = self.logFileData.filteredData.objectAtIndex_(index)\n text_to_copy += line + '\\n'\n index = index_set.indexGreaterThanIndex_(index)\n pasteboard = NSPasteboard.generalPasteboard()\n changeCount = pasteboard.clearContents()\n result = pasteboard.writeObjects_([text_to_copy])\n\n @IBAction\n def searchFilterChanged_(self, sender):\n '''User changed the search field'''\n filterString = self.searchField.stringValue().lower()\n self.logFileData.filterText = filterString\n self.logFileData.applyFilterToData()\n self.logView.reloadData()\n\n def getWindowLevel(self):\n '''Gets our NSWindowLevel. Works around issues with the loginwindow\n PolicyBanner in 10.11+ Some code based on earlier work by Pepijn\n Bruienne'''\n window_level = NSScreenSaverWindowLevel - 1\n # Get our Darwin major version\n darwin_vers = int(os.uname()[2].split('.')[0])\n have_policy_banner = False\n for test_file in ['/Library/Security/PolicyBanner.txt',\n '/Library/Security/PolicyBanner.rtf',\n '/Library/Security/PolicyBanner.rtfd']:\n if os.path.exists(test_file):\n have_policy_banner = True\n break\n # bump our NSWindowLevel if we have a PolicyBanner in ElCap+\n if have_policy_banner and darwin_vers > 14:\n window_level = NSScreenSaverWindowLevel\n return window_level\n\n @IBAction\n def showLogWindow_(self, notification):\n '''Show the log window.'''\n\n if self.window.isVisible():\n # It's already open, just move it to front\n self.window.makeKeyAndOrderFront_(self)\n return\n\n consoleuser = munki.getconsoleuser()\n if consoleuser == None or consoleuser == u\"loginwindow\":\n self.window.setCanBecomeVisibleWithoutLogin_(True)\n self.window.setLevel_(self.getWindowLevel())\n\n screenRect = NSScreen.mainScreen().frame()\n windowRect = screenRect.copy()\n windowRect.origin.x = 100.0\n windowRect.origin.y = 200.0\n windowRect.size.width -= 200.0\n windowRect.size.height -= 300.0\n\n logfile = munki.pref('LogFile')\n self.pathControl.setURL_(NSURL.fileURLWithPath_(logfile))\n self.window.setTitle_(os.path.basename(logfile))\n self.window.setFrame_display_(windowRect, NO)\n self.window.makeKeyAndOrderFront_(self)\n self.watchLogFile_(logfile)\n\n # allow dragging from table view to outside of the app\n self.logView.setDraggingSourceOperationMask_forLocal_(\n NSDragOperationAll, NO)\n\n def watchLogFile_(self, logFile):\n '''Display and continuously update a log file in the main window.'''\n self.stopWatching()\n self.logFileData.removeAllLines()\n self.logView.setDataSource_(self.logFileData)\n self.logView.reloadData()\n self.fileHandle = NSFileHandle.fileHandleForReadingAtPath_(logFile)\n self.refreshLog()\n # Kick off a timer that updates the log view periodically.\n self.updateTimer = (\n NSTimer.\n scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(\n 0.25, self, self.refreshLog, None, YES))\n\n def stopWatching(self):\n '''Release the file handle and stop the update timer.'''\n if self.fileHandle is not None:\n self.fileHandle.closeFile()\n self.fileHandle = None\n if self.updateTimer is not None:\n self.updateTimer.invalidate()\n self.updateTimer = None\n\n def refreshLog(self):\n '''Check for new available data, read it, and scroll to the bottom.'''\n data = self.fileHandle.availableData()\n if data.length():\n utf8string = NSString.alloc().initWithData_encoding_(\n data, NSUTF8StringEncoding)\n for line in utf8string.splitlines(True):\n if line.endswith(u\"\\n\"):\n self.logFileData.addLine_partial_(line.rstrip(u\"\\n\"), False)\n else:\n self.logFileData.addLine_partial_(line, True)\n self.logView.reloadData()\n self.logView.scrollRowToVisible_(self.logFileData.lineCount() - 1)\n\n def windowWillClose_(self, notification):\n '''NSWindow delegate method -- if our window is closing,\n stop watching the log file.'''\n self.stopWatching()\n","sub_path":"code/apps/MunkiStatus/MunkiStatus/MSULogWindowController.py","file_name":"MSULogWindowController.py","file_ext":"py","file_size_in_byte":8433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"480436706","text":"\"\"\"\nLocalBox API Implementation module. This module holds the implementation of the\nAPI call handlers as well as directly related support functions\n\"\"\"\nfrom base64 import b64decode\nfrom json import dumps\nfrom json import loads\nfrom logging import getLogger\nfrom os import makedirs\nfrom os import remove\nfrom os import walk\nfrom os.path import basename\nfrom os.path import exists\nfrom os.path import isdir\nfrom os.path import isfile\nfrom os.path import islink\nfrom os.path import join\nfrom os.path import lexists\nfrom re import compile as regex_compile\nfrom shutil import copyfile\nfrom shutil import move\nfrom shutil import rmtree\n\nimport localbox.utils\nfrom localbox import defaults\nfrom localbox.utils import get_bindpoint\n\ntry:\n from urllib import unquote_plus # pylint: disable=F0401,E0611\n from Cookie import SimpleCookie # pylint: disable=F0401,E0611\nexcept ImportError:\n from http.cookies import SimpleCookie # pylint: disable=F0401,E0611\n from urllib.parse import unquote_plus # pylint: disable=F0401,E0611\n\ntry:\n from os import symlink\nexcept ImportError:\n # python26/windows fix for symlinking:\n # Origined from http://stackoverflow.com/questions/6260149/os-symlink-support-in-windows\n # As reported by Erik Renes, with minor changes\n def symlink(source, link_name):\n import os\n os_symlink = getattr(os, \"symlink\", None)\n if callable(os_symlink):\n os_symlink(source, link_name)\n else:\n import ctypes\n csl = ctypes.windll.kernel32.CreateSymbolicLinkW\n csl.argtypes = (\n ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)\n csl.restype = ctypes.c_ubyte\n flags = 1 if os.path.isdir(source) else 0\n if csl(link_name, source, flags) == 0:\n raise ctypes.WinError()\n\nfrom localbox.database import get_key_and_iv\nfrom .database import database_execute\nfrom localbox.files import get_filesystem_path\nfrom localbox.files import get_key_path\nfrom .files import stat_reader\nfrom .files import SymlinkCache\nfrom .shares import Share, ShareItem, Invitation\nfrom .shares import list_share_items\nfrom .shares import get_share_by_id\nfrom .shares import get_database_invitations\nfrom .encoding import localbox_path_decoder\nfrom .shares import toggle_invite_state\nfrom loxcommon.config import ConfigSingleton\n\n\ndef ready_cookie(request_handler):\n \"\"\"\n Readies a PHP-like cookie - not to be part of the final codebase\n \"\"\"\n host = request_handler.headers.get('Host')\n cookie = SimpleCookie()\n cookie['PHPSESSID'] = \"21345\"\n cookie['PHPSESSID']['Domain'] = host\n cookie['PHPSESSID']['path'] = \"/\"\n cookie['PHPSESSID']['version'] = \"1\"\n request_handler.new_headers.append(('Set-Cookie',\n cookie.output(header=''),))\n\n\ndef prepare_string(string, encoding=\"UTF-8\"):\n \"\"\"\n Prepares a string to be sent over the wire. Python3 requires 'string's to\n be encoded as bytes accoding to an encoding (e.g. UTF8) before sending them\n through a socket. Within python2, 'bytes' more or less are strings, and the\n bytes' constructor only accepts one argument. Hence, this function will\n return the right type of object for sending over the network.\n\n :param string: string to be encoded.\n :param encoding: optional encoding in case it should not by UTF8 encoded.\n :returns: the string as a socket write prepared bytes type.\n \"\"\"\n try:\n return bytes(string, encoding)\n except TypeError:\n return string\n\n\ndef get_body_json(request_handler):\n \"\"\"\n Reads the request handlers bode and parses it as a JSON object.\n\n :param request_handler: the object which has the body to extract as json\n :returns: json-parsed version of the requests' body.\n \"\"\"\n return loads(request_handler.old_body)\n\n\ndef exec_leave_share(request_handler):\n \"\"\"\n Handle the leave_share call. Removes the share with the specified path for\n the current user. Returns 200 if succesful, 404 on failure. Called via the\n routing list.\n\n :param request_handler: object holding the path of the share to leave\n \"\"\"\n pathstart = request_handler.path.replace('/lox_api/shares/', '', 1)\n path = pathstart.replace('/leave', '', 1)\n\n bindpoint = get_bindpoint()\n linkpath = join(bindpoint, request_handler.user, path)\n if islink(linkpath):\n remove(linkpath)\n request_handler.status = 200\n else:\n request_handler.status = 404\n\n\ndef exec_remove_shares(request_handler):\n \"\"\"\n Removes a share from being shared. Everyones access to this share, except\n for that of the owner, is irrevokably removed by this call. Called via the\n routing list.\n\n :param request_handler: the object which contains the path to remove\n \"\"\"\n share_start = request_handler.path.replace(\n '/lox_api/shares/', '', 1)\n shareid = int(share_start.replace('/revoke', '', 1))\n sql = 'remove from shares where id = ?'\n database_execute(sql, (shareid))\n request_handler.status = 200\n\n\ndef exec_shares_delete(request_handler):\n share_start = request_handler.path.replace(\n '/lox_api/shares/', '', 1)\n shareid = int(share_start.replace('/delete', '', 1))\n sql = 'delete from shares where id = ?'\n database_execute(sql, (shareid,))\n request_handler.status = 200\n\n\ndef exec_edit_shares(request_handler):\n \"\"\"\n Edits the list of people who can access a certain share object. A list of\n json encoded identities is in the body to represent the new list of people\n with access to said share. Called via the routing list\n\n :param request_handler: the object which contains the share id in its path\n and list of users json-encoded in its body.\n \"\"\"\n share_start = request_handler.path.replace(\n '/lox_api/shares/', '', 1)\n shareid = share_start.replace('/edit', '', 1)\n share = get_share_by_id(shareid)\n json = get_body_json(request_handler)\n symlinks = SymlinkCache()\n path = share.item.path\n links = symlinks.get(path)\n\n bindpoint = get_bindpoint()\n newlinks = []\n for entry in json:\n to_file = join(bindpoint, entry.title, basename(entry.path))\n newlinks.append(to_file)\n symlink(path, to_file)\n for link in links:\n if link not in newlinks:\n remove(link)\n symlinks.remove(link)\n\n\ndef exec_shares(request_handler):\n \"\"\"\n Handle share information for a path given in the request. Returns a list\n of shares containing the provided path. Called via the routing list.\n\n :param request_handler: the object with the path encoded in its path\n \"\"\"\n path2 = request_handler.path.replace('/lox_api/shares/', '', 1)\n data = list_share_items(path2)\n request_handler.body = data\n request_handler.status = 200\n if data == \"{}\":\n request_handler.status = 404\n request_handler.body = None\n\n\ndef exec_shares_list(request_handler):\n user = unquote_plus(request_handler.path.replace('/lox_api/shares/user/', '', 1))\n data = list_share_items(user=user)\n request_handler.body = data\n request_handler.status = 200\n if data == \"{}\":\n request_handler.status = 404\n request_handler.body = None\n\n\ndef exec_invitations(request_handler):\n \"\"\"\n Returns a list of all (pending) invitations for an user. Called via the\n routing list\n\n :param request_handler: object though which to return the values\n \"\"\"\n request_handler.status = 200\n request_handler.body = get_database_invitations(\n request_handler.user)\n\n\ndef exec_invite_accept(request_handler):\n \"\"\"\n Accepts/reopens an invitation to filesharing. called from the routing list.\n\n :param request_handler: the object containing invite identifier in its path\n \"\"\"\n result = toggle_invite_state(request_handler, 'accepted')\n if result:\n request_handler.status = 200\n else:\n request_handler.status = 404\n\n\ndef exec_invite_reject(request_handler):\n \"\"\"\n Rejects/cancels an invitation to filesharing. Called from the routing list\n\n :param request_handler: object with the invite identifier in its path\n \"\"\"\n result = toggle_invite_state(request_handler, 'rejected')\n if result:\n request_handler.status = 200\n else:\n request_handler.status = 404\n\n\ndef exec_files_path(request_handler):\n \"\"\"\n Allows for the up- and downloading of (encrypted) files to and from the\n localbox server. called from the routing list\n\n :param request_handler: the object which contains the files path in its path\n \"\"\"\n path = request_handler.path.replace('/lox_api/files/', '', 1)\n if path != '':\n path = localbox_path_decoder(path)\n try:\n filepath = get_filesystem_path(path, request_handler.user)\n except ValueError as e:\n request_handler.status = 404\n request_handler.body = e.message\n return\n\n # getLogger(__name__).debug('body %s' % (request_handler.old_body),\n # extra=logging_utils.get_logging_extra(request_handler))\n\n contents = None\n if request_handler.old_body is not None:\n try:\n json_body = loads(request_handler.old_body)\n path = unquote_plus(json_body['path'])\n filepath = get_filesystem_path(path, request_handler.user)\n if json_body.has_key('contents'):\n contents = b64decode(json_body['contents'])\n except ValueError:\n contents = request_handler.old_body\n\n if request_handler.command == \"POST\" and contents is not None:\n request_handler.status = 200\n try:\n filedescriptor = open(filepath, 'wb')\n filedescriptor.write(contents)\n except IOError:\n getLogger('api').error('Could not write to file %s' % path,\n extra=localbox.utils.get_logging_extra(request_handler))\n request_handler.status = 500\n\n if request_handler.command == \"GET\" or (request_handler.command == \"POST\" and contents is None):\n if isdir(filepath):\n # Not really looping but we need the first set of values\n for path, directories, files in walk(filepath):\n if files is None or directories is None:\n getLogger(__name__).info(\"filesystem related problems\",\n extra=localbox.utils.get_logging_extra(request_handler))\n return\n # path, directories, files = walk(filepath).next()\n dirdict = stat_reader(path, request_handler.user)\n dirdict['children'] = []\n for child in directories + files:\n user = request_handler.user\n childpath = join(filepath, child)\n dirdict['children'].append(\n stat_reader(childpath, user))\n request_handler.body = dumps(dirdict)\n break\n elif exists(filepath):\n filedescriptor = open(filepath, 'rb')\n request_handler.body = filedescriptor.read()\n request_handler.status = 200\n else:\n request_handler.status = 404\n\n\ndef exec_operations_create_folder(request_handler):\n \"\"\"\n Creates a new folder in the localbox directory structure. Called from the\n routing list\n\n :param request_handler: the object which has the path url-encoded in its\n body\n \"\"\"\n request_handler.status = 200\n path = unquote_plus(request_handler.old_body).replace(\"path=/\", \"\", 1)\n getLogger(__name__).info(\"creating folder %s\" % path, extra=localbox.utils.get_logging_extra(request_handler))\n bindpoint = get_bindpoint()\n filepath = join(bindpoint, request_handler.user, path)\n if lexists(filepath):\n getLogger(__name__).error(\"%s already exists\" % path, extra=localbox.utils.get_logging_extra(request_handler))\n request_handler.status = 409 # Http conflict\n request_handler.body = \"Error: Something already exits at path\"\n return\n makedirs(filepath)\n getLogger('api').info(\"created directory \" + filepath,\n extra=request_handler.get_log_dict())\n request_handler.body = dumps(\n stat_reader(filepath, request_handler.user))\n\n\ndef exec_operations_delete(request_handler):\n \"\"\"\n Removes a file or folder from the localbox directory structure. called from\n the routing list\n\n :param request_handler: the object which has the file path json-encoded in\n its body\n \"\"\"\n request_handler.status = 200\n user = request_handler.user\n pathstring = unquote_plus(\n request_handler.old_body).replace(\"path=/\", \"\", 1)\n bindpoint = get_bindpoint()\n filepath = join(bindpoint, user, pathstring)\n\n getLogger(__name__).debug('deleting %s' % filepath,\n extra=request_handler.get_log_dict())\n\n if not exists(filepath):\n request_handler.status = 404\n request_handler.body = \"Error: No file exits at path\"\n getLogger('api').error(\"failed to delete %s\" % filepath,\n extra=request_handler.get_log_dict())\n\n return\n if isdir(filepath):\n rmtree(filepath)\n else:\n remove(filepath)\n\n # remove keys\n sql = 'delete from keys where user = ? and path = ?'\n database_execute(sql, (user, get_key_path(user, localbox_path=pathstring)))\n\n SymlinkCache().remove(filepath)\n\n\ndef exec_operations_move(request_handler):\n \"\"\"\n Moves a file within the localbox directory structure. Called from the\n routing list\n\n :param request_handler: the object which has the to_path and from_path\n json-encoded in its body\n \"\"\"\n json_object = loads(request_handler.old_body)\n bindpoint = get_bindpoint()\n move_from = join(\n bindpoint, request_handler.user, json_object['from_path'])\n move_to = join(\n bindpoint, request_handler.user, json_object['to_path'])\n if not isfile(move_from):\n request_handler.status = 404\n request_handler.body = \"Error: No file exits at from_path\"\n return\n if lexists(move_to):\n request_handler.status = 404\n request_handler.body = \"Error: A file already exists at to_path\"\n return\n move(move_from, move_to)\n\n\ndef exec_operations_copy(request_handler):\n \"\"\"\n copies a file within the localbox filesystem. Called from the routing list\n\n :param request_handler: object with to_path and from_path json-encoded in\n its body\n \"\"\"\n json_object = loads(request_handler.old_body)\n bindpoint = get_bindpoint()\n copy_from = join(\n bindpoint, request_handler.user, json_object['from_path'])\n copy_to = join(\n bindpoint, request_handler.user, json_object['to_path'])\n if not exists(copy_from):\n request_handler.status = 404\n request_handler.body = \"Error: No file exits at from_path\"\n return\n if lexists(copy_to):\n request_handler.status = 404\n request_handler.body = \"Error: A file already exists at to_path\"\n return\n copyfile(copy_from, copy_to)\n\n request_handler.status = 200\n\n\ndef exec_user(request_handler):\n \"\"\"\n returns public- and private key information about the current user. Called\n from the routing list\n\n :param request_handler: object holding the user for which to return data\n \"\"\"\n getLogger(__name__).info(\"running exec user\", extra=request_handler.get_log_dict())\n if request_handler.command == \"GET\":\n sql = \"select public_key, private_key from users where name = ?\"\n result = database_execute(sql, (request_handler.user,))\n try:\n result_dictionary = {'user': request_handler.user, 'public_key': result[0][0],\n 'private_key': result[0][1]}\n except IndexError:\n result_dictionary = {'user': request_handler.user}\n request_handler.body = dumps(result_dictionary)\n else:\n json_object = loads(request_handler.old_body)\n privkey = json_object['private_key']\n pubkey = json_object['public_key']\n sql = 'insert into users (public_key, private_key, name) values (?, ?, ?)'\n result = database_execute(\n sql, (pubkey, privkey, request_handler.user,))\n request_handler.body = dumps(\n {'name': request_handler.user, 'publib_key': pubkey, 'private_key': privkey})\n request_handler.status = 200\n\n\ndef exec_user_username(request_handler):\n \"\"\"\n returns information about a certain user as specified in the url. Also\n return private key data if this is that user making the request\n\n :param request_handler: object containing the user for which to return data\n \"\"\"\n username = request_handler.path.replace('/lox_api/user/', '', 1)\n if username == request_handler.user:\n sql = 'select public_key, private_key from users where name = ?;'\n else:\n sql = 'select public_key from users where name = ?;'\n\n result = database_execute(sql, (username,))\n if result == []:\n request_handler.status = 404\n request_handler.body = \"Unknown user\"\n return\n else:\n request_handler.status = 200\n\n info = {'name': username, 'public_key': result[0]}\n if username == request_handler.user:\n info['private_key'] = result[1]\n request_handler.body = dumps(info)\n\n\ndef exec_create_share(request_handler):\n \"\"\"\n Creates a 'share' within localbox. Comes down to creating a symlink next\n to a few database records to give the share an identifier.\n\n :param request_handler: object with the share filepath encoded in its path\n \"\"\"\n body = request_handler.old_body\n json_list = loads(body)\n getLogger(__name__).debug('request data: %s' % json_list, extra=request_handler.get_log_dict())\n path2 = unquote_plus(request_handler.path.replace('/lox_api/share_create/', '', 1))\n bindpoint = get_bindpoint()\n sender = request_handler.user\n from_file = join(bindpoint, sender, path2)\n getLogger(__name__).debug('from_file: %s' % from_file, extra=request_handler.get_log_dict())\n # TODO: something something something group\n share = Share(sender, None, ShareItem(path=path2))\n share.save_to_database()\n request_handler.status = 200\n for json_object in json_list['identities']:\n if json_object['type'] == 'user':\n receiver = json_object['username']\n to_file = join(bindpoint, receiver, path2)\n getLogger(__name__).debug('to_file: %s' % to_file, extra=request_handler.get_log_dict())\n if exists(to_file):\n getLogger(__name__).error(\"destination \" + to_file + \" exists.\", extra=request_handler.get_log_dict())\n request_handler.status = 500\n return\n if not exists(from_file):\n getLogger(__name__).error(\"source \" + from_file + \"does not exist.\",\n extra=request_handler.get_log_dict())\n request_handler.status = 500\n return\n try:\n symlink(from_file, to_file)\n SymlinkCache().add(from_file, to_file)\n except OSError:\n getLogger('api').error(\"Error making symlink from \" + from_file +\n \" to \" + to_file, extra=request_handler.get_log_dict())\n request_handler.status = 500\n invite = Invitation(\n None, 'pending', share, sender, receiver)\n invite.save_to_database()\n\n\ndef exec_key(request_handler):\n \"\"\"\n returns rsa encrypted key and initialization vector for decoding the file\n in the specified path\n\n :param request_handler: object containing the file path encoded in its path\n \"\"\"\n localbox_path = unquote_plus(request_handler.path.replace('/lox_api/key/', '', 1))\n while localbox_path.startswith('/'):\n localbox_path = localbox_path[1:]\n\n if request_handler.command == \"GET\":\n result = get_key_and_iv(localbox_path, request_handler.user)\n if result is not None:\n key, initvector = result # pylint: disable=W0633\n request_handler.body = dumps({'key': key, 'iv': initvector})\n request_handler.status = 200\n else:\n request_handler.status = 404\n elif request_handler.command == \"POST\":\n data = request_handler.old_body\n # TODO: not crash on bull\n json_object = loads(data)\n sql = \"insert into keys (path, user, key, iv) VALUES (?, ?, ?, ?)\"\n database_execute(sql, (localbox_path, json_object['user'], json_object['key'],\n json_object['iv']))\n request_handler.status = 200\n # TODO: recrypt encryped data\n\n\ndef exec_key_revoke(request_handler):\n \"\"\"\n revoke/remove an encrypted key from the database so said user cannot access\n said key anymore.\n\n :param request_handler: object containing the path to the file in its path\n and json encoded name of the user whoes key to\n revoke\n \"\"\"\n path = request_handler.path.replace('/lox_api/key_revoke/', '', 1)\n lengthstring = request_handler.headers.get('content-length')\n if lengthstring is None:\n user = request_handler.user\n else:\n data = request_handler.old_body\n user = loads(data)['username']\n # Let's either not allow users to add a username or not have the\n # restriction that they cannot get the data back next time\n if user != request_handler.user:\n request_handler.status = 403\n sql = 'remove from keys where user = ? and path = ?;'\n database_execute(sql, (user, path))\n\n\ndef exec_meta(request_handler):\n \"\"\"\n returns metadata for a given file/directory\n\n :param request_handler: object with path encoded in its path\n \"\"\"\n if (request_handler.path == '/lox_api/meta') or (request_handler.path == '/lox_api/meta/'):\n path = ''\n else:\n path = unquote_plus(\n request_handler.path.replace('/lox_api/meta/', '', 1))\n\n getLogger(__name__).debug('body %s' % request_handler.old_body,\n extra=localbox.utils.get_logging_extra(request_handler))\n if request_handler.old_body:\n path = unquote_plus(loads(request_handler.old_body)['path'])\n if path == '/':\n path = '.'\n\n try:\n try:\n filepath = get_filesystem_path(path, request_handler.user)\n except ValueError as e:\n request_handler.status = 404\n request_handler.body = e.message\n getLogger(__name__).error(e.message,\n extra=localbox.utils.get_logging_extra(request_handler))\n return\n result = stat_reader(filepath, request_handler.user)\n getLogger(__name__).debug('meta for filepath %s: %s' % (filepath, result),\n extra=localbox.utils.get_logging_extra(request_handler))\n if result is None:\n request_handler.status = 404\n request_handler.body = 'no meta found for %s. maybe the file does not exist' % filepath\n return\n result['children'] = []\n for path, directories, files in walk(filepath):\n for child in directories + files:\n user = request_handler.user\n childpath = join(filepath, child)\n result['children'].append(stat_reader(childpath, user))\n break\n except OSError as err:\n request_handler.status = 404\n getLogger(__name__).exception(err,\n extra=localbox.utils.get_logging_extra(request_handler))\n request_handler.body = dumps(result)\n request_handler.status = 200\n\n\ndef fake_register_app(request_handler):\n \"\"\"\n part of the fake login process, most definitely not part of the final\n codebase\n\n :param request_handler: the object which has the body to extract as json\n \"\"\"\n configparser = ConfigSingleton('localbox')\n hostcrt = configparser.get('httpd', 'certfile')\n\n backurl = configparser.get('oauth', 'direct_back_url', default=defaults.DIRECT_BACK_URL)\n y = open('host.crt').read()\n result = {'baseurl': backurl, 'name': '1.6.0',\n 'user': request_handler.user, 'logourl': 'http://8ch.net/static/logo_33.svg',\n 'BackColor': '#00FF00', 'FontColor': '#0000FF', 'APIKeys':\n [{'Name': 'LocalBox iOS', 'Key': 'keystring',\n 'Secret': 'secretstring'}],\n 'pin_cert': ''.join(y.split('\\n')[1:-2])\n }\n request_handler.status = 200\n request_handler.body = dumps(result)\n\n\ndef fake_oauth(request_handler):\n \"\"\"\n part of the fake login process, not part of the final codebase\n\n :param request_handler: the object which has the body to extract as json\n\n NOTE: this was support for the localbox app and is now most likely depricated. Please remove as fast as possible\n \"\"\"\n if \"token\" in request_handler.path:\n print(\n \"============================================ FAKE OAUTH PART 3\")\n request_handler.status = 200\n result = {\"access_token\": \"2DHJlWJTui9d1pZnDDnkN6IV1p9Qq9\",\n \"token_type\": \"Bearer\", \"expires_in\": 600,\n \"refresh_token\": \"tNXAVVo2QE7c5MKgFCB1mKuAPsu4xL\",\n \"scope\": \"all\"}\n request_handler.body = result\n elif request_handler.command != \"POST\":\n print(\n \"============================================ FAKE OAUTH PART 1\")\n html = '
' \\\n ''\n request_handler.status = 200\n request_handler.new_headers.append(\n ('Content-type', 'text/html',))\n request_handler.body = html\n else:\n print(\n \"============================================ FAKE OAUTH PART 2\")\n request_handler.status = 302\n request_handler.new_headers.append(('Location',\n 'lbox://oauth-return?code=yay'))\n\n\ndef exec_identities(request_handler):\n \"\"\"\n returns a list of all (known) users\n\n :param request_handler: object in which to return the userlist\n \"\"\"\n sql = 'select name, not ((public_key == \"\" or public_key is NULL) and (private_key == \"\" or private_key is NULL)) as haskey,' \\\n 'public_key from users;'\n result = database_execute(sql)\n outputlist = []\n for entry in result:\n outputlist.append({\n 'id': entry[0],\n 'title': entry[0],\n 'username': entry[0],\n 'type': 'user',\n 'has_keys': bool(entry[1]),\n 'public_key': entry[2]\n })\n if outputlist == []:\n request_handler.status = 404\n else:\n request_handler.status = 200\n request_handler.body = dumps(outputlist)\n\n\ndef fake_set_cookies(request_handler):\n \"\"\"\n not part of final codebase\n \"\"\"\n request_handler.status = 404\n\n\n# list with regex: function pairs. The regex is to be matched with the url\n# requested. When the regex matches, the function is called with the\n# request_handler as argument.\nROUTING_LIST = [\n (regex_compile(r\"\\/lox_api\\/files.*\"), exec_files_path),\n (regex_compile(r\"\\/lox_api\\/invitations\"), exec_invitations),\n (regex_compile(r\"\\/lox_api\\/invite/[0-9]+/accept\"), exec_invite_accept),\n (regex_compile(r\"\\/lox_api\\/invite/[0-9]+/revoke\"), exec_invite_reject),\n (regex_compile(r\"\\/lox_api\\/operations\\/copy\"), exec_operations_copy),\n (regex_compile(r\"\\/lox_api\\/operations\\/move\"), exec_operations_move),\n (regex_compile(r\"\\/lox_api\\/operations\\/delete\"), exec_operations_delete),\n (regex_compile(r\"\\/lox_api\\/operations\\/create_folder\"),\n exec_operations_create_folder),\n (regex_compile(r\"\\/lox_api\\/share_create\\/.*\"), exec_create_share),\n (regex_compile(r\"\\/lox_api\\/shares\\/.*\\/edit\"), exec_edit_shares),\n (regex_compile(r\"\\/lox_api\\/shares\\/.*\\/revoke\"), exec_remove_shares),\n (regex_compile(r\"\\/lox_api\\/shares\\/.*\\/delete\"), exec_shares_delete),\n (regex_compile(r\"\\/lox_api\\/shares\\/.*\\/leave\"), exec_leave_share),\n (regex_compile(r\"\\/lox_api\\/shares\\/user/.*\"), exec_shares_list),\n (regex_compile(r\"\\/lox_api\\/shares\\/.*\"), exec_shares),\n (regex_compile(r\"\\/lox_api\\/user\\/.*\"), exec_user_username),\n (regex_compile(r\"\\/lox_api\\/user\"), exec_user),\n (regex_compile(r\"\\/lox_api\\/key\\/.*\"), exec_key),\n (regex_compile(r\"\\/lox_api\\/key_revoke\\/.*\"), exec_key_revoke),\n (regex_compile(r\"\\/lox_api\\/meta.*\"), exec_meta),\n (regex_compile(r\"\\/lox_api\\/identities\"), exec_identities),\n\n (regex_compile(r\"\\/register_app\"), fake_register_app),\n (regex_compile(r\"\\/oauth.*\"), fake_oauth),\n (regex_compile(r\"\\/.*\"), fake_set_cookies),\n]\n","sub_path":"localbox/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":29135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"447929764","text":"import random\n# abfsdfdsf \nmaxnum = int(input('Max number = '))\ntotalask = 0\ntotalcorrect = 0\ntotalwrong = 0\nlasta = 0\nlastb = 0\n\ndef nhan(a, b):\n print('Multiply:')\n print(a,' x ',b,' = ',end='')\n c = int(input())\n if c == 0:\n return 0\n if c == a*b:\n return 1\n else:\n return 2\n\ndef chia(a, b):\n print('Divide:')\n c = a * b\n print(c,' / ',a,' = ',end='')\n d = int(input())\n if d == 0:\n return 0\n if d == b:\n return 1\n else:\n return 2\n\nwhile True:\n a = random.randint(2,maxnum)\n b = random.randint(2,9)\n while True:\n a = random.randint(2,maxnum)\n b = random.randint(2,9)\n if (((a!=lasta) or (b!=lastb)) and ((a!=lastb) or (b!=lasta))):\n break\n nhanorchia = random.randint(1,2)\n if (nhanorchia==1):\n totalask = totalask +1\n ketqua=nhan(a,b)\n else:\n totalask = totalask +1\n ketqua=chia(a,b)\n if (ketqua==0):\n break\n if (ketqua==1):\n totalcorrect = totalcorrect +1\n print('Correct')\n else:\n totalwrong = totalwrong +1\n print('wrong') \n print('Total correct answer ', totalcorrect,'/',totalask)\n print('Total wrong answer ', totalwrong,'/',totalask)\n lasta = a\n lastb = b\n","sub_path":"multidiv.py","file_name":"multidiv.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"134319912","text":"import torch\nfrom torch import nn\nfrom torch.nn import Sequential\n\nfrom hw_asr.base import BaseModel\n\n\nclass Model01(BaseModel):\n def __init__(self, n_feats, n_class, fc_hidden=512, *args, **kwargs):\n super().__init__(n_feats, n_class, *args, **kwargs)\n self.lstm1 = nn.LSTM(input_size=n_feats, hidden_size=128, num_layers=2, batch_first=True, bidirectional=True)\n self.relu1 = nn.ReLU()\n self.lstm2 = nn.LSTM(input_size=256, hidden_size=128, num_layers=2, batch_first=True, bidirectional=True)\n self.relu2 = nn.ReLU()\n self.linear = nn.Linear(in_features=256, out_features=n_class)\n\n def forward(self, spectrogram, *args, **kwargs):\n x, (hn, cn) = self.lstm1(spectrogram)\n x = self.relu1(x)\n x, (hn, cn) = self.lstm2(x)\n x = self.relu2(x)\n return self.linear(x)\n\n def transform_input_lengths(self, input_lengths):\n return input_lengths # we don't reduce time dimension here\n","sub_path":"hw_asr/model/model_01.py","file_name":"model_01.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"572991257","text":"from django.shortcuts import render\nfrom django.views.generic import ListView, DetailView, CreateView\nfrom .models import Entry\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic.edit import DeleteView,UpdateView\nfrom django.contrib import messages\n\n\n\n# Create your views here.\n\nclass HomeView(LoginRequiredMixin, ListView):\n model = Entry\n template_name = 'entries/index.html'\n context_object_name =\"blog_entries\"\n ordering = ['-entry_date']\n paginate_by = 5\n\n\nclass EntryView(LoginRequiredMixin, DetailView):\n model = Entry\n template_name = 'entries/entry_detail.html'\n\nclass CreateEntryView(LoginRequiredMixin, CreateView):\n model = Entry\n template_name = 'entries/create_entry.html'\n fields = ['entry_title', 'entry_text','img']\n \n \n \n def form_valid(self,form):\n form.instance.entry_author = self.request.user\n return super().form_valid(form)\n\nfrom django.urls import reverse_lazy\n\n\n\nclass YDeleteView(LoginRequiredMixin, DeleteView,):\n model = Entry\n success_url = reverse_lazy('blog-home')\n \n def dispatch(self, request, *args, **kwargs):\n \n obj = self.get_object()\n if obj.entry_author != self.request.user:\n messages.error(request, 'Document not deleted.')\n return redirect('blog-home')\n messages.success(request, 'Document deleted.')\n return super(YDeleteView, self).dispatch(request, *args, **kwargs)\n\n\nclass EditPost(LoginRequiredMixin,UpdateView):\n model = Entry\n template_name = 'entries/create_entry.html'\n fields = ['entry_title','entry_text']\n success_url = reverse_lazy('blog-home')\n def dispatch(self, request, *args, **kwargs):\n \n obj = self.get_object()\n if obj.entry_author != self.request.user:\n messages.error(request, 'Document does not belong to you')\n return redirect('blog-home')\n return super(EditPost, self).dispatch(request, *args, **kwargs)\n \n ","sub_path":"entries/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"563897845","text":"#!/usr/bin/env python\n\"\"\"\nA simulator for the PHRINGES phased-array system\n created by Rurik Primiani 03/04/2010\n \n03/09/2010: Added tons of documentation\n\"\"\"\n\n\nimport logging\n\nfrom math import sqrt, pi\nfrom time import time, sleep\nfrom binhex import binascii as b2a\nfrom struct import Struct, pack, unpack, calcsize\n\ntry:\n from numpy.fft import ifft\n from numpy.random import normal\n from numpy import array, arange, ones, mean, sin, cos, concatenate\nexcept ImportError:\n logging.error(\"\"\"Numpy package required but not installed!\n Please install python-numpy >= 1.4.1\"\"\")\n exit()\n\nfrom phringes.core.models import GeometricModel, AtmosphericModel\nfrom phringes.core.macros import parse_includes\nfrom basic import (\n BasicCorrelationProvider,\n BasicRequestHandler,\n BasicTCPServer,\n \n FLOAT, SBYTE,\n MAX_REQUEST_SIZE,\n\n debug, info, warning, # actually imported\n critical, error, # from core.loggers\n)\n\n\nclass SimulatorCorrelationProvider(BasicCorrelationProvider):\n \n @debug\n def correlate(self):\n \"\"\" inst.correlate() -> None\n Uses parameters extracted from an instance of SimulatorTCPServer\n to mimic the output of the PHRINGES hardware-based correlator. It\n stores its output in appropriate instance members.\"\"\"\n antenna_temp = self.server._antenna_efficiency * self.server._source_flux\n for baseline in self._include_baselines:\n # For an unresolved source all baselines see the same\n # correlated flux, use the radiometer equation with T_sys\n # being the geometric mean of the antennas\n system_temp = sqrt(self.server._system_temp[baseline[0]] *\\\n self.server._system_temp[baseline[1]])\n phase_rms = (system_temp/antenna_temp) /\\\n sqrt(2 * (2*self.server._bandwidth/self._lags) *\\\n self.server._integration_time)\n delay = self.server._delays[baseline[1]] +\\\n self.server._delay_offsets[baseline[1]] -\\\n self.server._delays[baseline[0]] -\\\n self.server._delay_offsets[baseline[0]] +\\\n self.server._geometry.delay(baseline) +\\\n self.server._atmosphere.delay(baseline)\n phase = self.server._phases[baseline[1]] +\\\n self.server._phase_offsets[baseline[1]] -\\\n self.server._phases[baseline[0]] -\\\n self.server._phase_offsets[baseline[0]] +\\\n delay * pi * arange(0, 1+2.0/self._lags, 2.0/self._lags) +\\\n normal(0, phase_rms, 1+self._lags/2) +\\\n self.server._geometry.phase(baseline) +\\\n self.server._atmosphere.phase(baseline)\n amplitude = antenna_temp/system_temp *\\\n ones(1+self._lags/2)\n real = amplitude * cos(phase)\n imag = amplitude * sin(phase)\n half_spectrum_positive = real + imag*1j\n half_spectrum_negative = real - imag*1j\n full_spectrum = concatenate((half_spectrum_positive[:-1],\n half_spectrum_negative[1+self._lags/2:0:-1]))\n cross_correlation = ifft(full_spectrum).real\n cross_correlation = concatenate((cross_correlation[self._lags/2:],\n cross_correlation[0:self._lags/2]))\n self.logger.debug('baseline %d-%d:' %baseline)\n self.logger.debug(' phase noise RMS: %.2f rads' %phase_rms)\n self.logger.debug(' amplitude across band: %.2f Wh' %(mean(amplitude)*10**4))\n self._correlations[baseline] = cross_correlation * 2**32\n\n\nclass SimulatorTCPServer(BasicTCPServer):\n \n #@debug\n def __init__(self, address, handler=BasicRequestHandler,\n correlator=BasicCorrelationProvider,\n n_antennas=8, correlator_lags=32, \n include_baselines='*-*', initial_flux=2.0, \n initial_int_time=16, analog_bandwidth=512000000.0, \n antenna_diameter=3):\n \"\"\" SimulatorTCPServer(address, handler, correlator, lags, baselines)\n This subclasses the BasicTCPServer and adds some methods needed for\n controlling and reading data from the SimulatorCorrelationProvider.\n Please see the BasicTCPServer documentation for more detailed infor-\n mation.\n \n 128 - self.get_source_flux()\n 129 - self.set_source_flux(flux_Jy)\n 130 - self.get_system_temp(for_antennas=[1,2,3,...])\n 131 - self.set_system_temp(ant_val=[1,0.0,2,0.0,3,0.0...])\n 132 - self.get_phases(for_antennas=[1,2,3,...])\n 133 - self.set_phases(ant_val=[1,0.0,2,0.0,3,0.0...])\n 134 - self.get_delays(for_antennas=[1,2,3,...])\n 135 - self.set_delays(ant_val=[1,0.0,2,0.0,3,0.0...])\"\"\"\n BasicTCPServer.__init__(self, address, handler=handler, \n correlator=correlator, correlator_lags=correlator_lags, \n n_antennas=n_antennas, initial_int_time=initial_int_time,\n antenna_diameter=antenna_diameter, analog_bandwidth=analog_bandwidth, \n include_baselines=include_baselines)\n self._command_set.update({ 128 : self.get_source_flux,\n 129 : self.set_source_flux,\n 130 : self.get_system_temp,\n 131 : self.set_system_temp,\n 132 : self.get_phases,\n 133 : self.set_phases,\n 134 : self.get_delays,\n 135 : self.set_delays })\n self._source_flux = initial_flux\n self._atmosphere = AtmosphericModel(self)\n self._geometry = GeometricModel(self)\n self._correlator = correlator(self, self._include_baselines, correlator_lags)\n \n @info\n def get_source_flux(self, args):\n \"\"\" inst.get_source_flux() -> err_code\n Accepts no arguments (but for safety include a padding null byte in the\n request packet) and returns the current source flux density in Jansky's.\n The return packet will have an error code of 0 following by an unsigned byte\n representing the current integration time.\"\"\"\n self.logger.info('source flux density requested, currently %.2f Jy'\\\n %self._source_flux)\n return pack('!bf', 0, self._source_flux)\n\n @info\n def set_source_flux(self, args):\n \"\"\" inst.set_source_flux(flux_Jy) -> err_code\n This accepts a single float representing the requested source flux density\n in Jansky's and for right now always returns an error code of 0\n meaning that the source flux was set successfully.\"\"\"\n self._source_flux = FLOAT.unpack(args[:4])[0]\n self.logger.debug('set_source_flux(%.2f)' %self._source_flux)\n return SBYTE.pack(0)\n\n @info\n def get_system_temp(self, args):\n \"\"\" inst.get_system_temp(antennas=[1,2,3,...]) -> values=[0.0,0.0,0.0,...]\n See inst.get_phase_offsets but replace 'phase_offsets' with 'system_temp'\"\"\"\n return self.get_values('system_temp', args, type='f')\n\n @info\n def set_system_temp(self, args):\n \"\"\" inst.set_system_temp(ant_val=[1,0.0,2,0.0,3,0.0,...]) -> values=[0.0,0.0,0.0,...]\n See inst.get_phase_offsets but replace 'phase_offsets' with 'system_temp'\"\"\"\n return self.set_values('system_temp', args, type='f')\n\n @info\n def get_phases(self, args):\n \"\"\" inst.get_phases(antennas=[1,2,3,...]) -> values=[0.0,0.0,0.0,...]\n See inst.get_phase_offsets but replace 'phase_offsets' with 'phases'\"\"\"\n return self.get_values('phases', args, type='f')\n\n @info\n def set_phases(self, args):\n \"\"\" inst.set_phases(ant_val=[1,0.0,2,0.0,3,0.0,...]) -> values=[0.0,0.0,0.0,...]\n See inst.get_phase_offsets but replace 'phase_offsets' with 'phases'\"\"\"\n return self.set_values('phases', args, type='f')\n\n @info\n def get_delays(self, args):\n \"\"\" inst.get_delays(antennas=[1,2,3,...]) -> values=[0.0,0.0,0.0,...]\n See inst.get_phase_offsets but replace 'phase_offsets' with 'delays'\"\"\"\n return self.get_values('delays', args, type='f')\n\n @info\n def set_delays(self, args):\n \"\"\" inst.set_delays(ant_val=[1,0.0,2,0.0,3,0.0,...]) -> values=[0.0,0.0,0.0,...]\n See inst.get_phase_offsets but replace 'phase_offsets' with 'delays'\"\"\"\n return self.get_values('delays', args, type='f')\n","sub_path":"phringes/backends/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":8744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"508613094","text":"from sys import stdin\r\nfrom Utils.Find_path import animation\r\n\r\n\r\ndef no_randomised():\r\n print(\"Enter the labyrinth:\")\r\n map = []\r\n while True:\r\n col = stdin.readline().strip()\r\n if not col:\r\n break\r\n map.append(col)\r\n print(\"Enter the inicial positon of Pac-Man\")\r\n print(\"On this way(y ,x)\")\r\n ini_y, ini_x = [int(c) for c in stdin.readline().strip().split()]\r\n if map[ini_x][ini_y] == \"#\":\r\n print(\"The value tha you have enter is an invalid position\")\r\n no_randomised()\r\n print(\"Enter the target of Pac-Man\")\r\n target_y, target_x = [int(c) for c in stdin.readline().strip().split()]\r\n if map[target_x][target_y] == \"#\":\r\n print(\"The value tha you have enter is an invalid position\")\r\n no_randomised()\r\n animation(map, (ini_y, ini_x), (target_y, target_x), 1)\r\n\r\n","sub_path":"Proyecto/English/No_randomised.py","file_name":"No_randomised.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"389903065","text":"\"\"\"Derivation of variable `alb`.\n\nauthors:\n - crez_ba\n\n\"\"\"\n\nfrom iris import Constraint\n\nfrom ._derived_variable_base import DerivedVariableBase\n\n\nclass DerivedVariable(DerivedVariableBase):\n \"\"\"Derivation of variable `alb`.\"\"\"\n\n # Required variables\n _required_variables = {\n 'vars': [{\n 'short_name': 'rsds',\n 'field': 'T2{frequency}s'\n }, {\n 'short_name': 'rsus',\n 'field': 'T2{frequency}s'\n }]\n }\n\n def calculate(self, cubes):\n \"\"\"Compute surface albedo.\"\"\"\n rsds_cube = cubes.extract_strict(\n Constraint(name='surface_downwelling_shortwave_flux_in_air'))\n rsus_cube = cubes.extract_strict(\n Constraint(name='surface_upwelling_shortwave_flux_in_air'))\n\n rsns_cube = rsus_cube / rsds_cube\n\n return rsns_cube\n","sub_path":"esmvaltool/preprocessor/_derive/alb.py","file_name":"alb.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"245077110","text":"import collections, tokenizer\n\nclass X(collections.defaultdict):\n def __init__(self, defs = { 1: 1 }):\n initial = {}\n for k, v in defs.items():\n if v != 0.0:\n initial[k] = v\n\n super(X, self).__init__(lambda: 0.0, initial)\n\n ##################################################\n\n def __mul__(self, other):\n if isinstance(other, X):\n res = X({})\n for exp1, coeff1 in self.items():\n for exp2, coeff2 in other.items():\n res[exp1 + exp2] += coeff1 * coeff2\n return res\n elif isinstance(other, (int, float)):\n res = X({})\n for exp, coeff in self.items():\n res[exp] += coeff * other\n return res\n return NotImplemented\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n ##################################################\n\n def __add__(self, other):\n if isinstance(other, X):\n res = X(self)\n for exp, coeff in other.items():\n res[exp] += coeff\n return res\n elif isinstance(other, (int, float)):\n res = X(self)\n res[0] += other\n return res\n return NotImplemented\n\n def __radd__(self, other):\n return self.__add__(other)\n\n ##################################################\n\n def __pow__(self, other):\n #TODO: Make exponents work.\n if isinstance(other, X):\n if len(self) == 1 and len(other) == 1:\n raised_exp, degree = next(iter(other.items()))\n if raised_exp == 0:\n exp, coeff = next(iter(self.items()))\n return X({exp*degree: coeff**degree})\n\n elif isinstance(other, (int, float)):\n if len(self) == 1:\n exp, coeff = next(iter(self.items()))\n return X({exp*other: coeff**other})\n\n return NotImplemented\n\n #TODO: `rpow`\n\n ##################################################\n\n def __sub__(self, other):\n if isinstance(other, X):\n res = X(self)\n for exp, coeff in other.items():\n res[exp] -= coeff\n return res\n elif isinstance(other, (int, float)):\n res = X(self)\n res[0] -= other\n return res\n return NotImplemented\n\n def __rsub__(self, other):\n if isinstance(other, (int, float)):\n res = X({ 0: float(other) })\n for exp, coeff in self.items():\n res[exp] -= coeff\n return res\n return NotImplemented\n\n ##################################################\n\n def __div__(self, other):\n #TODO: Make division work.\n if isinstance(other, (int, float)):\n res = X(self)\n for exp, coeff in self.items():\n res[exp] = coeff / other\n return res\n return NotImplemented\n\n #TODO: `rdiv`\n\n ##################################################\n\n def __str__(self):\n def f2s(f):\n return '{:.15g}'.format(f)\n\n res = []\n\n for exp, coeff in reversed(sorted(self.items())):\n if coeff == 0: continue\n\n if exp != 0:\n term = ''\n if coeff != 1: term += f2s(coeff)\n term += 'x'\n if exp != 1: term += '^' + f2s(exp)\n else:\n term = f2s(coeff)\n\n if not term[0] == '-': term = '+' + term\n res.append(term[0])\n res.append(term[1:])\n\n return ' '.join(res).lstrip(' +')\n\n ##################################################\n\n def __setitem__(self, key, val):\n collections.defaultdict.__setitem__(self, key, val)\n if self[key] == 0.0: del self[key]\n\n __repr__ = dict.__repr__\n\ndef operate(op, out):\n if op == 'u-':\n out.append(0 - out.pop())\n return\n if op == 'u+':\n out.append(out.pop())\n return\n\n b, a = out.pop(), out.pop()\n\n if op == '*':\n out.append( a * b )\n elif op == '/':\n out.append( a / b )\n elif op == '+':\n out.append( a + b )\n elif op == '-':\n out.append( a - b )\n elif op == '^':\n out.append( a ** b )\n\ndef simplify(inp):\n out = collections.deque()\n ops = collections.deque()\n while inp:\n token = inp.pop(0)\n if isinstance(token, X):\n out.append(token)\n elif token in tokenizer.operators:\n while ops and ops[-1] in tokenizer.operators and \\\n ((tokenizer.precedence[token] <= tokenizer.precedence[ops[-1]])\n if token in tokenizer.left_associative_operators else\n (tokenizer.precedence[token] < tokenizer.precedence[ops[-1]])):\n\n operate(ops.pop(), out)\n\n ops.append(token)\n elif token in tokenizer.open_group_symbols:\n ops.append(token)\n elif token in tokenizer.close_group_symbols:\n while ops and ops[-1] not in tokenizer.open_group_symbols:\n operate(ops.pop(), out)\n ops.pop()\n while ops:\n operate(ops.pop(), out)\n\n result = out.pop()\n\n return result","sub_path":"variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"185924785","text":"'''\n\tThis file is part of Narval :\n\tan opensource and free rights static blog generator.\n'''\n\n#!/usr/bin/python3\n#-*- coding: utf-8 -*-\n\nimport time, tenjin # Tenjin is under MIT License (http://www.kuwata-lab.com/tenjin/)\nfrom tenjin.helpers import *\nfrom tenjin.html import *\nengine = tenjin.Engine(path=['views'])\n\n### PARTS OF TEMPLATES\n\n# in ( includes)\ndef TMP_head(params, helpers, tmps, path='', head={}):\n\tif head == {}:\n\t\thead['title'] = ''\n\t\thead['author'] = params.blogDefaultAuthor\n\t\thead['desc'] = params.blogSubTitle\n\n\turl, separator = '', ''\n\t\n\tif head['title'] != '':\n\t\turl = 'posts/' + helpers.niceURL(head['title'], '.html')\n\t\tseparator = ' — '\n\t\t\n\tif head['desc'] == '':\n\t\thead['desc'] = params.blogSubTitle\n\n\toutput = engine.render('parts/head.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'path': path,\n\t\t'head': head,\n\t\t'separator': separator,\n\t\t'url': params.blogUrl + '/' + url\n\t})\n\treturn output\n\n# in , page header\ndef TMP_header(params, helpers, tmps, cats, pages, typePage):\n\tcontent = {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'cats': cats,\n\t\t'pages': pages,\n\t\t'url': params.blogUrl if params.blogUrl[0:3] == 'http' else params.blogUrl + '/index.html'\n\t}\n\tif typePage == 1:\n\t\toutput1 = engine.render('parts/headerForContent.pyhtml', content)\n\t\treturn output1\n\telse:\n\t\toutput2 = engine.render('parts/headerForList.pyhtml', content)\n\t\treturn output2\n\n# in , page footer\ndef TMP_footer(params, helpers, tmps):\n\toutput = engine.render('parts/footer.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps\n\t})\n\treturn output\n\n# in , olds and recents posts\ndef TMP_paginator(pagination):\n\toutput = engine.render('parts/paginator.pyhtml', {\n\t\t'page': pagination[0],\n\t\t'total': pagination[1]\n\t})\n\treturn output\n\n# in , textual line of categories\ndef TMP_catsLine(params, helpers, tmps, cats):\n\toutput = engine.render('parts/catsLine.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'cats': cats\n\t})\n\treturn output\n\n\n\n### FULL TEMPLATES\n\ndef TMP_posts(params, helpers, tmps, catName, header, footer, posts, pagination, path=''):\n\toutput = engine.render('posts.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'catName': catName,\n\t\t'header': header,\n\t\t'footer': footer,\n\t\t'posts': posts,\n\t\t'pagination': pagination,\n\t\t'path': path\n\t})\n\treturn output\n\ndef TMP_post(params, helpers, tmps, header, post, footer):\n\thead = {'desc': post['intro']}\n\thead['author'] = params.blogDefaultAuthor if post['author'] == '' else post['author']\n\thead['title'] = helpers.cleanhtml(post['title'])\n\n\toutput = engine.render('post.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'header': header,\n\t\t'footer': footer,\n\t\t'post': post,\n\t\t'head': head,\n\t\t'url': params.blogUrl if params.blogUrl[0:3] == 'http' else params.blogUrl + '/index.html'\n\t})\n\treturn output\n\ndef TMP_page(params, helpers, tmps, header, page, footer):\n\thead = {'title': page['title'], 'desc': page['desc'], 'author': params.blogDefaultAuthor}\n\toutput = engine.render('page.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'header': header,\n\t\t'footer': footer,\n\t\t'page': page,\n\t\t'head': head,\n\t\t'url': params.blogUrl if params.blogUrl[0:3] == 'http' else params.blogUrl + '/index.html'\n\t})\n\treturn output\n\ndef TMP_archives(params, helpers, tmps, header, posts, footer):\n\thead = {\n\t\t'title': 'Archives',\n\t\t'desc': 'Blog\\'s archives.',\n\t\t'author': params.blogDefaultAuthor\n\t}\n\toutput = engine.render('archives.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'header': header,\n\t\t'footer': footer,\n\t\t'posts': posts,\n\t\t'head': head,\n\t\t'url': params.blogUrl if params.blogUrl[0:3] == 'http' else params.blogUrl + '/index.html'\n\t})\n\treturn output\n\ndef TMP_rss(params, helpers, tmps, posts):\n\toutput = engine.render('rss.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'posts': posts\n\t})\n\treturn output\n\ndef TMP_readme(params, helpers, tmps, posts, pages, cats):\n\toutput = engine.render('readme.pyhtml', {\n\t\t'params': params,\n\t\t'helpers': helpers,\n\t\t'tmps': tmps,\n\t\t'posts': posts,\n\t\t'pages': pages,\n\t\t'cats': cats,\n\t\t'time': time\n\t})\n\treturn output\n","sub_path":"template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"157826963","text":"import os\r\nimport sys\r\nimport platform\r\nimport shutil\r\nimport subprocess\r\n\r\n\r\ndef writedir2file(path, targetfile):\r\n for root, dirs, files in os.walk(path):\r\n for file in files:\r\n targetfile.write(os.path.join(root, file), os.path.join(root, file)[len(path):])\r\n\r\n\r\ndef window_task(tool_file, dir):\r\n import zipfile\r\n zipf = zipfile.ZipFile(tool_file, 'w', zipfile.ZIP_DEFLATED)\r\n writedir2file(dir, zipf)\r\n zipf.close()\r\n\r\n\r\ndef linux_task(tool_file, dir):\r\n import tarfile\r\n tarf = tarfile.open(tool_file, 'w')\r\n tarf.write = tarf.add\r\n writedir2file(dir, tarf)\r\n tarf.close()\r\n\r\n\r\ndef delete_dirs(dirs):\r\n for dir in dirs:\r\n if os.path.exists(dir):\r\n shutil.rmtree(dir)\r\n\r\n\r\ndef main():\r\n rootdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')\r\n icpy_dir = os.path.join(rootdir, 'build', 'icpy')\r\n tokentool_dir = os.path.join(rootdir, 'dist', 'tokentool')\r\n cachetool_dir = os.path.join(rootdir, 'dist', 'cachetool')\r\n initserver_dir = os.path.join(rootdir, 'dist', 'initserver')\r\n delete_dirs([icpy_dir, tokentool_dir, cachetool_dir])\r\n pyinstaller_cmd = ['pyinstaller', '--clean', '-y', '-c', 'icpy.spec']\r\n subprocess.check_call(pyinstaller_cmd, cwd=rootdir)\r\n for dir in [tokentool_dir, initserver_dir]:\r\n for root, dirs, files in os.walk(dir):\r\n for file in files:\r\n shutil.copy(os.path.join(dir, file), cachetool_dir)\r\n sysstr = platform.system()\r\n if (sysstr == \"Windows\"):\r\n tool_file = os.path.join(rootdir, 'tool', 'icpy-tools.zip')\r\n task = window_task\r\n elif (sysstr == \"Linux\"):\r\n tool_file = os.path.join(rootdir, 'tool', 'icpy-tools.tar')\r\n task = linux_task\r\n else:\r\n raise Exception('操作系统暂不支持')\r\n if os.path.exists(tool_file):\r\n os.remove(tool_file)\r\n task(tool_file, cachetool_dir)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"iclientpy/tool/buildtool.py","file_name":"buildtool.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"377500229","text":"'''\nimport\n'''\nimport keras.losses\nimport pandas as pd\nfrom model.EFF import *\nfrom tensorflow.keras.callbacks import (\n ReduceLROnPlateau,\n)\n\n'''\nbasic parameter config\n'''\n# define the img shape that we want to feed to the model\nimg_width = 480\nimg_height = 480\n\n\"\"\"\nthe following train function is for training the CLS model\nParameters:\n1. save_dir: the checkpoint you want to save, please use the format like '/home/zhang.xinxi/CV/checkpoint/man_top_color/cp-{epoch:04d}.ckpt'\n so that the function can save different epochs.\n2. csv_dir: the dir for logging the training history(e.g. acc/loss), end with '.csv'.\n3. data_dir: the dir for the data, we use the tf api to load the data information(including the class information),so the data dir should be\n structured(data structure: root path/class_name/images), and we use the root as the data_dir here.\n4. best_path: since the we use the early stop mechanism here, we store the best epoch of the model to the best_path\n5. epochs: the max epochs to train the model\n6. portion: the portion for the training set -> (1-portion) is the the portion for the val set\n7. log_dir: the class information of the data, (e.g. '方领','v领','圆领'), end with '.csv'\n8. begin_epoch: if you want to continue training using a certain checkpoint, you can enter the checkpoint here for the model to load\n the checkpoint must be ended with '.ckpt'\n9. distribute_training: whether to use multiple GPU to train\n10.binary: whether the CLS task is binary\n\"\"\"\n\ndef train(save_dir, csv_dir, data_dir, best_path, epochs, batch_size, portion,log_dir,begin_epoch='no',distribute_training=False,binary=False):\n \"\"\"\n call backs\n \"\"\"\n early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0.01, patience=4, verbose=1, mode='auto', baseline=None, restore_best_weights=True)\n logger = keras.callbacks.CSVLogger(csv_dir, separator=',', append=False)\n cp_callback = tf.keras.callbacks.ModelCheckpoint(\n filepath=save_dir,\n verbose=1,\n save_weights_only=True,\n period=1)\n\n '''\n load the data\n '''\n train_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_dir,\n validation_split=1 - portion,\n subset=\"training\",\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)\n\n val_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_dir,\n validation_split=1 - portion,\n subset=\"validation\",\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)\n class_names = train_ds.class_names\n class_nums = len(train_ds.class_names)\n print('the data has been loaded', train_ds.class_names)\n\n # transfer the label to one_hot form\n if not binary:\n def map_func(images, label):\n one_hot_label = tf.one_hot(label, depth=class_nums)\n return images, one_hot_label\n \n train_ds = train_ds.map(map_func, num_parallel_calls=tf.data.AUTOTUNE)\n val_ds = val_ds.map(map_func, num_parallel_calls=tf.data.AUTOTUNE)\n\n '''\n load the EFF model\n '''\n if distribute_training:\n mirrored_strategy = tf.distribute.MirroredStrategy()\n with mirrored_strategy.scope():\n model = get_EFFmodel(img_height, img_width, class_nums, binary=binary)\n if 'ckpt' in begin_epoch:\n model.load_weights(begin_epoch)\n if binary:\n model.compile(optimizer=keras.optimizers.Adam(lr=1e-4),\n loss=keras.losses.CategoricalCrossentropy(label_smoothing=0.1), metrics=['accuracy'])\n else:\n model.compile(optimizer=keras.optimizers.Adam(lr=1e-4),\n loss=keras.losses.BinaryCrossentropy(label_smoothing=0.1), metrics=['accuracy'])\n else:\n model = get_EFFmodel(img_height, img_width, class_nums, binary=binary)\n if 'ckpt' in begin_epoch:\n model.load_weights(begin_epoch)\n if binary:\n model.compile(optimizer=keras.optimizers.Adam(lr=1e-4),\n loss=keras.losses.CategoricalCrossentropy(label_smoothing=0.1), metrics=['accuracy'])\n else:\n model.compile(optimizer=keras.optimizers.Adam(lr=1e-4),\n loss=keras.losses.BinaryCrossentropy(label_smoothing=0.1), metrics=['accuracy'])\n print(model.summary())\n\n '''\n model training\n '''\n # prefetch\n AUTOTUNE = tf.data.AUTOTUNE\n train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)\n val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)\n\n # train\n history = model.fit(\n train_ds,\n validation_data=val_ds,\n epochs=epochs,\n callbacks=[cp_callback,\n early_stop,\n logger,\n ReduceLROnPlateau(verbose=1)]\n )\n\n # save the best weights of the model\n model.save_weights(best_path)\n print(\"training finish==================================================================================\")\n\n # save the class information to the log_dir\n names_df = pd.DataFrame(class_names).set_index(0)\n names_df.to_csv(log_dir)\n","sub_path":"P&T/model_train.py","file_name":"model_train.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608415989","text":"# -*- coding: utf-8 -*-\nimport pytest\nimport yaml\n\n\n@pytest.fixture(autouse=True)\ndef calc_remind():\n print(\"计算开始\")\n yield\n print(\"\\n计算结束\\n\")\n\n\n@pytest.fixture()\ndef login(request):\n user = request.param\n print(f\"登陆用户为{user}\")\n return user\n\n#自定义动态生成测试用例fixture\ndef pytest_generate_tests(metafunc: \"Metafunc\"):\n if \"add\" in metafunc.fixturenames:\n metafunc.parametrize(\"add\", metafunc.module.adddatas\n , ids=metafunc.module.addids\n , scope=\"function\")\n if \"dec\" in metafunc.fixturenames:\n metafunc.parametrize(\"dec\", metafunc.module.decdatas\n , ids=metafunc.module.decids\n , scope=\"function\")\n if \"div\" in metafunc.fixturenames:\n metafunc.parametrize(\"div\", metafunc.module.divdatas\n , ids=metafunc.module.divids\n , scope=\"function\")\n if \"mul\" in metafunc.fixturenames:\n metafunc.parametrize(\"mul\", metafunc.module.muldatas\n , ids=metafunc.module.mulids\n , scope=\"function\")\n\ndef pytest_addoption(parser):\n mygroup = parser.getgroup(\"Lie-tester\") #group 将下面所有的 option都展示在这个group下。\n mygroup.addoption(\"--env\", #注册一个命令行选项\n default='st',\n dest='env',\n help='set your run env'\n )\n\n@pytest.fixture(scope='session')\ndef mycmdoption(request):\n myenv = request.config.getoption(\"--env\", default='st')\n if myenv == \"test\":\n datapath = 'env/test/data.yml'\n if myenv == \"dev\":\n datapath = 'env/dev/data.yml'\n if myenv == \"st\":\n datapath = 'env/st/data.yml'\n\n with open(datapath) as f:\n datas = yaml.safe_load(f)\n\n return myenv, datas\n","sub_path":"testing/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"77561572","text":"#!/usr/bin/env python\n#\n# Copyright 2008 Willow Garage, Inc.\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\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# * Neither the name of the Willow Garage, Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport copy\nimport struct\nimport unittest\n\nfrom sensor_msgs import point_cloud2\nfrom sensor_msgs.msg import PointField\nfrom tf2_ros import TransformStamped\nimport tf2_sensor_msgs\n\n\n# A sample python unit test\nclass PointCloudConversions(unittest.TestCase):\n\n def setUp(self):\n self.point_cloud_in = point_cloud2.PointCloud2()\n self.point_cloud_in.fields = [\n PointField('x', 0, PointField.FLOAT32, 1),\n PointField('y', 4, PointField.FLOAT32, 1),\n PointField('z', 8, PointField.FLOAT32, 1)]\n\n self.point_cloud_in.point_step = 4 * 3\n self.point_cloud_in.height = 1\n # we add two points (with x, y, z to the cloud)\n self.point_cloud_in.width = 2\n self.point_cloud_in.row_step = \\\n self.point_cloud_in.point_step * self.point_cloud_in.width\n\n points = [1, 2, 0, 10, 20, 30]\n self.point_cloud_in.data = struct.pack('%sf' % len(points), *points)\n\n self.transform_translate_xyz_300 = TransformStamped()\n self.transform_translate_xyz_300.transform.translation.x = 300\n self.transform_translate_xyz_300.transform.translation.y = 300\n self.transform_translate_xyz_300.transform.translation.z = 300\n # no rotation so we only set w\n self.transform_translate_xyz_300.transform.rotation.w = 1\n\n assert(list(point_cloud2.read_points(self.point_cloud_in)) ==\n [(1.0, 2.0, 0.0), (10.0, 20.0, 30.0)])\n\n def test_simple_transform(self):\n # deepcopy is not required here because we have a str for now\n old_data = copy.deepcopy(self.point_cloud_in.data)\n point_cloud_transformed = tf2_sensor_msgs.do_transform_cloud(\n self.point_cloud_in, self.transform_translate_xyz_300)\n\n k = 300\n expected_coordinates = [(1+k, 2+k, 0+k), (10+k, 20+k, 30+k)]\n new_points = list(point_cloud2.read_points(point_cloud_transformed))\n print('new_points are %s' % new_points)\n assert(expected_coordinates == new_points)\n # checking no modification in input cloud\n assert(old_data == self.point_cloud_in.data)\n\n\nif __name__ == '__main__':\n import rosunit\n rosunit.unitrun('test_tf2_sensor_msgs', 'test_point_cloud_conversion',\n PointCloudConversions)\n","sub_path":"tf2_sensor_msgs/test/test_tf2_sensor_msgs.py","file_name":"test_tf2_sensor_msgs.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"391889183","text":"import numpy as np\nimport os \nimport pickle as pkl\n\n######################################################################\nclass Manager:\n ''' Skeleton for managers.'''\n def __init__(name='AGmanager',path='./'):\n # Where to save self.\n self.name=name\n self.pickle=\"%s.pkl\"%self.name\n\n # Ensure path is set up correctly.\n if path is None:\n path=os.getcwd()\n if path[-1]!='/': path+='/'\n self.path=path\n\n self.logname=\"%s@%s\"%(self.__class__.__name__,self.path+self.name)\n\n # Handle old results if present.\n if os.path.exists(self.path+self.pickle):\n print(self.logname,\": rebooting old manager.\")\n old=pkl.load(open(self.path+self.pickle,'rb'))\n self.recover(old)\n\n # Update the file.\n if not os.path.exists(self.path): os.mkdir(self.path)\n with open(self.path+self.pickle,'wb') as outf:\n pkl.dump(self,outf)\n\n #----------------------------------------\n def nextstep(self,qstat=None):\n ''' Redefine to have the manager do something.'''\n pass\n\n #----------------------------------------\n def collect(self):\n ''' Redefine to have manager farm data from its reader.'''\n pass\n\n #----------------------------------------\n def status(self):\n if self.completed:\n return 'ok'\n else:\n return 'not_finished'\n\n #------------------------------------------------\n def update_pickle(self):\n ''' If you make direct changes to the internals of the pickle, you need to call this to insure they are saved.'''\n with open(self.path+self.pickle,'wb') as outf:\n pkl.dump(self,outf)\n\n #----------------------------------------\n def submit(self):\n ''' Submit any work and update the manager.'''\n qsubfile=self.runner.submit()\n\n self.update_pickle()\n\n return qsubfile\n\n #----------------------------------------\n def release_commands(self):\n ''' Release the runner of any commands it was tasked with and update the manager.'''\n commands=self.runner.release_commands()\n self.update_pickle()\n\n return commands\n\n #------------------------------------------------\n def update_queueid(self,qid):\n ''' If a bundler handles the submission, it can update the queue info with this.\n Args:\n qid (str): new queue id from submitting a job. The Manager will check if this is running.\n '''\n self.runner.queueid.append(qid)\n self.update_pickle()\n\n #----------------------------------------\n def export_record(self):\n return {\n 'manager':self.__class__.__name__,\n 'name':self.name,\n 'path':self.path\n }\n\n######################################################################\ndef resolve_status(runner,reader,outfile,qstat=None):\n #Check if the reader is done\n if reader.completed:\n return 'done'\n\n #Check if the job is in the queue or running. If so, we just return that.\n currstat=runner.check_status(qstat=qstat)\n if currstat=='running':\n return currstat\n \n #Now we are in a state where either there was an error,\n #the job hasn't been run, or we haven't collected the results\n if not os.path.exists(outfile):\n return 'not_started'\n\n #We are in an error state or we haven't collected the results. \n return \"ready_for_analysis\"\n\n######################################################################\ndef deep_compare(d1,d2):\n '''I have to redo dict comparison because numpy will return a bool array when comparing.'''\n if type(d1)!=type(d2):\n return False\n if type(d1)==dict:\n if d1.keys()!=d2.keys():\n return False\n allsame=True\n for key in d1.keys():\n allsame=allsame and deep_compare(d1[key],d2[key])\n return allsame\n else:\n try:\n return np.array_equal(d1,d2)\n except TypeError:\n return d1==d2\n\n######################################################################\ndef update_attributes(copyto,copyfrom,skip_keys=[],take_keys=[]):\n ''' Save update of class attributes. If copyfrom has additional attributes, they are ignored.\n\n Args:\n copyto (obj): class who's attributes are being updated.\n copyfrom (obj): class who's attributes will be copied from.\n skip_keys (list): list of attributes (str) not to update. \n take_keys (list): list of attributes (str) that are ok to update. Others will raise warning and be skipped.\n Returns:\n bool: Whether any changes were made.\n '''\n updated=False\n for key in copyfrom.__dict__.keys():\n if key in skip_keys: \n #print(\"Skipping key (%s)\"%key)\n pass\n elif key not in copyto.__dict__.keys():\n print(\"Warning: Object update for %s. An attribute (%s) was skipped because it doesn't exist in both objects.\"%(copyto.__class__.__name__,key))\n elif not deep_compare(copyto.__dict__[key],copyfrom.__dict__[key]):\n if key not in take_keys:\n print(\"Warning: unexpected update to %s for attribute (%s) taken from old, because it requires job to be rerun.\"%(copyto.__class__.__name__,key))\n #print(\"Copy\",key)\n copyto.__dict__[key]=copyfrom.__dict__[key]\n updated=True\n else:\n #print(\"Keys match (%s)\"%key)\n pass\n return updated\n","sub_path":"autogenv2/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":5064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"420455787","text":"\n\nclass FileLoader:\n \n\n def load(self, path):\n import pandas as pd\n csv = pd.read_csv(path)\n # df = pd.DataFrame(x)\n print('('+ str(len(csv)) + ',' + str(len(csv.columns)) + ')')\n return csv\n\n def display(self, df, n):\n if n >= 0:\n print(df.head(n))\n else:\n print(df.tail(n))\n\n def proportionBySport(self, df, year, sport, gender):\n\n df = df[df.Year == year]\n df = df[df.Sex == gender]\n x = len(df[df.Sport == sport])/len(df)\n print(x)\n\n def howManyMedals(self, df, name):\n df = df[df.Name == name]\n df = df.groupby(['Year', 'Medal']).ID.agg('count')\n list_year = list(set(list(zip(*list(df.index)))[0]))\n list_medal = list(set(list(zip(*list(df.index)))[1]))\n dct = {y: {m: df[y][m] for m in list_medal} for y in list_year} \n print(dct)\n return dct\n\n \n","sub_path":"day04/ex05/FileLoader.py","file_name":"FileLoader.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"372769883","text":"\r\nfrom requests import get\r\nfrom bs4 import BeautifulSoup\r\n\r\nurl ='https://www.amazon.in/s?k=iphones&ref=nb_sb_noss_2'\r\nresponse =get(url)\r\n\r\nhtml_soup=BeautifulSoup(response.text,'html.parser')\r\nprint(html_soup)\r\n\r\niphone_names =html_soup.find_all('div',class_=\"a-section a-spacing-none\")\r\nprint(iphone_names)\r\n\r\n\r\n# lists to store the scrapped data\r\n\r\nnames =[]\r\nprice =[]\r\n\r\nfor iphonenamess in iphone_names:\r\n if iphonenamess.find('div' ,class_=\"a-link-normal a-text-normal\"):\r\n print(iphonenamess)\r\n\r\n name =iphonenamess.div.span.text\r\n names.append(name)\r\n print(names)\r\n","sub_path":"amazon api.py","file_name":"amazon api.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"373329082","text":"import urllib.request\nimport re\n\nregex = r\"(\\[.*\\].*\\[(.*)\\])\"\n\nurl = 'https://raw.githubusercontent.com/jlu5/netmeter.club/confv2/Targets-Shared'\nresponse = urllib.request.urlopen(url)\ndata = response.read()\ntext = data.decode('utf-8')\n\nmatches = re.finditer(regex, text, re.MULTILINE)\nfor matchNum, match in enumerate(matches, start=1):\n\n print(\"[hosts.\"+match.groups()[1].replace(\".\", \"_\")+\"]\")\n print(\"ip = \\\"\"+match.groups()[1]+\"\\\"\")\n print(\"description = \\\"\"+match.groups()[0]+\"\\\"\")\n print()\n","sub_path":"generateConfig.py","file_name":"generateConfig.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"613188522","text":"from pymongo import MongoClient\nimport pprint\n\nclient = MongoClient()\n\nclient = MongoClient('mongodb://localhost:27017/')\n\ndb = client['my-test-db']\n\ncollection = db['myCollection']\n\nposts = db.posts\n\nfor post in posts.find({'product_id': 'BTC-USD'}):\n pprint.pprint(post)","sub_path":"MongoReader.py","file_name":"MongoReader.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"120005799","text":"\nimport sys\nimport os\nimport warnings\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom datetime import date\nfrom datetime import timedelta\n\nimport math\nimport copy\nfrom scipy.optimize import minimize\n\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\nwarnings.filterwarnings(\"ignore\")\n\nfrom COMM import File_Util\n\n\n# List up CSV files from default folder\nbase_folder = '../DATA/CSV/futures/'\nex_list = ('FTSE China 50 Total Return', 'iBovespa Futures'\n , 'MSCI Brazil 25-50 Net Return', 'MSCI International EAFE Net'\n , 'MVIS Global Junior Gold Miners TR Net', 'Nifty 50 Futures', 'MVIS Russia TR Net'\n , 'US 10 Year T-Note Futures', 'US 30 Year T-Bond Futures')\ndatas = File_Util.ReadCSVFiles(base_folder, ex_list)\n\n# Sampling 데이터가 휴일인 경우 가장 최근 영업일 데이터를 찾기 위해 사용\nreference_list = datas.resample('D', on='Date2', convention=\"end\")\nreference_datas = datas.loc[datas['Date2'].isin(list(reference_list.indices))]\npivoted_reference_datas = reference_datas.pivot(index='Date2', columns='Name', values='Price')\n#print(pivoted_reference_datas)\n\n# Sampling 데이터 생성\nsample_list = datas.resample('M', on='Date2', convention=\"end\")\nsample_datas = datas.loc[datas['Date2'].isin(list(sample_list.indices))]\npivoted_sample_datas = sample_datas.pivot(index='Date2', columns='Name', values='Price')\n#print(pivoted_sample_datas)\n\n\n# Index의 타입을 Timestamp에서 Date로 변경\npivoted_reference_datas.index = [date(index.year, index.month, index.day) for index in pivoted_reference_datas.index]\npivoted_sample_datas.index = [date(index.year, index.month, index.day) for index in pivoted_sample_datas.index]\n# Sampling 데이터가 휴일인 경우 가장 최근 영업일 데이터로 채움\npivoted_inserted_datas = copy.deepcopy(pivoted_sample_datas)\nfor num, index in enumerate(pivoted_sample_datas.index):\n # 기본로직(Month 단위): After next month의 1일 전일\n\n # 10월 이후의 경우 After next month는 year가 넘어간다.\n year = index.year + 1 if index.month > 10 else index.year\n if index.month == 11:\n month = 1\n elif index.month == 12:\n month = 2\n else:\n month = index.month + 2\n\n # After next month의 1일 전으로 월별 말일을 찾음.\n next_last_date = date(year, month, 1) + timedelta(days=-1)\n\n # 마지말까지 확인전인 경우\n #if num + 1 < len(pivoted_sample_datas.index):\n if pivoted_sample_datas.index[-1] < pivoted_reference_datas.index[-1]:\n #print(num, len(pivoted_sample_datas.index), index, next_last_date, pivoted_sample_datas.index[num+1] == next_last_date)\n #print(next_last_date)\n # 다음 Sampling 데이터가 휴일이어서 데이터가 없는 경우 or 다음 Sampling 데이터와 다음달 말일이 다른 경우\n if next_last_date > pivoted_sample_datas.index[-1] or pivoted_sample_datas.index[num+1] != next_last_date:\n pivoted_inserted_datas = pd.concat([pivoted_inserted_datas, pd.DataFrame(index=[next_last_date], columns=pivoted_inserted_datas.columns)])\n# 새로움 Sampling 데이터는 끝에 추가되기 때문에 날짜로 Sorting\npivoted_inserted_datas = pivoted_inserted_datas.sort_index(ascending=1)\n\n\npivoted_filled_datas = copy.deepcopy(pivoted_inserted_datas)\nfor column_nm in pivoted_filled_datas.columns:\n for row_nm in pivoted_filled_datas.index:\n\n # 값이 포맷이 string인 경우 float으로 변경\n if isinstance(pivoted_filled_datas[column_nm][row_nm], str):\n pivoted_filled_datas[column_nm][row_nm] = float(pivoted_filled_datas[column_nm][row_nm].replace(',',''))\n\n #print(column_nm, \"\\t\", row_nm, \"\\t\", pivoted_sample_datas[column_nm][row_nm], \"\\t\", pivoted_filled_datas[column_nm][row_nm])\n if math.isnan(pivoted_filled_datas[column_nm][row_nm]) == True:\n # ref_row_nm = copy.copy(row_nm)\n #ref_row_nm = str(row_nm)[:10]\n ref_row_nm = row_nm\n\n # 해당일에 데이터가 없는 경우 가장 최근 값을 대신 사용함\n for loop_cnt in range(10):\n try:\n float_value = float(pivoted_reference_datas[column_nm][ref_row_nm].replace(',', '')) if isinstance(pivoted_reference_datas[column_nm][ref_row_nm], str) else pivoted_reference_datas[column_nm][ref_row_nm]\n if math.isnan(float_value) == True:\n # print(\"No Data\", str(ref_row_nm))\n #ref_row_nm = str(datetime.strptime(ref_row_nm, '%Y-%m-%d').date() - timedelta(days=1))\n ref_row_nm = ref_row_nm - timedelta(days=1)\n else:\n pivoted_filled_datas[column_nm][row_nm] = float_value\n break\n except KeyError:\n # print(\"KeyError\", str(ref_row_nm))\n #ref_row_nm = str(datetime.strptime(ref_row_nm, '%Y-%m-%d').date() - timedelta(days=1))\n ref_row_nm = ref_row_nm - timedelta(days=1)\n\n # 이후 연산작업을 위해 decimal을 float 형태로 변경\n if math.isnan(pivoted_filled_datas[column_nm][row_nm]) == False:\n pivoted_filled_datas[column_nm][row_nm] = float(pivoted_filled_datas[column_nm][row_nm])\n\n\n# 지수값을 수익률로 변경\npivoted_profit_data = pivoted_filled_datas.rolling(window=2).apply(lambda x: x[1] / x[0] - 1)\n\n\n# 유효기간을 벗어난 데이터 삭제\npivoted_droped_data = copy.deepcopy(pivoted_profit_data)\nrow_list = copy.deepcopy(pivoted_droped_data.index)\nfor row_nm in row_list:\n for column_nm in pivoted_droped_data.columns:\n # 수익률 생성시 문제있는 셀은 nan값\n if math.isnan(pivoted_droped_data[column_nm][row_nm]) == True:\n pivoted_droped_data.drop(index=row_nm, inplace=True)\n pivoted_filled_datas.drop(index=row_nm, inplace=True)\n break\n\n\n\ndef ObjectiveVol(rets, objective_type, target, lb, ub):\n rets.index = pd.to_datetime(rets.index)\n covmat = pd.DataFrame.cov(rets)\n var_list = pd.DataFrame.var(rets)\n\n def annualize_scale(rets):\n\n med = np.median(np.diff(rets.index.values))\n seconds = int(med.astype('timedelta64[s]').item().total_seconds())\n if seconds < 60:\n freq = 'second'.format(seconds)\n elif seconds < 3600:\n freq = 'minute'.format(seconds // 60)\n elif seconds < 86400:\n freq = 'hour'.format(seconds // 3600)\n elif seconds < 604800:\n freq = 'day'.format(seconds // 86400)\n elif seconds < 2678400:\n freq = 'week'.format(seconds // 604800)\n elif seconds < 7948800:\n freq = 'month'.format(seconds // 2678400)\n else:\n freq = 'quarter'.format(seconds // 7948800)\n\n def switch1(x):\n return {\n 'day': 252,\n 'week': 52,\n 'month': 12,\n 'quarter': 4,\n }.get(x)\n\n return switch1(freq)\n\n # --- Risk Budget Portfolio Objective Function ---#\n\n def EqualRiskContribution_objective(x):\n\n variance = x.T @ covmat @ x\n sigma = variance ** 0.5\n mrc = 1 / sigma * (covmat @ x)\n rc = x * mrc\n #a = np.reshape(rc, (len(rc), 1))\n a = np.reshape(rc.values, (len(rc), 1))\n risk_diffs = a - a.T\n sum_risk_diffs_squared = np.sum(np.square(np.ravel(risk_diffs)))\n\n return (sum_risk_diffs_squared)\n\n def MinVariance_objective(x):\n\n variance = x.T @ covmat @ x\n sigma = variance ** 0.5\n\n return (sigma)\n\n def MostDiversifiedPortfolio_objective(x):\n\n portfolio_variance = x.T @ covmat @ x\n portfolio_sigma = portfolio_variance ** 0.5\n weighted_sum_sigma = x @ (var_list ** 0.5)\n\n return (portfolio_sigma / weighted_sum_sigma)\n\n # --- Constraints ---#\n\n def TargetVol_const_lower(x):\n\n variance = x.T @ covmat @ x\n sigma = variance ** 0.5\n sigma_scale = sigma * np.sqrt(annualize_scale(rets))\n\n vol_diffs = sigma_scale - (target * 1.00)\n\n return (vol_diffs)\n\n def TargetVol_const_upper(x):\n\n variance = x.T @ covmat @ x\n sigma = variance ** 0.5\n sigma_scale = sigma * np.sqrt(annualize_scale(rets))\n\n vol_diffs = (target * 1.00) - sigma_scale\n\n return (vol_diffs)\n\n def TotalWgt_const(x):\n\n return x.sum() - 1\n\n # --- Calculate Portfolio ---#\n\n x0 = np.repeat(1 / covmat.shape[1], covmat.shape[1])\n #print(x0)\n lbound = np.repeat(lb, covmat.shape[1])\n ubound = np.repeat(ub, covmat.shape[1])\n bnds = tuple(zip(lbound, ubound))\n constraints = ({'type': 'ineq', 'fun': TargetVol_const_lower},\n {'type': 'ineq', 'fun': TargetVol_const_upper},\n {'type': 'eq', 'fun': TotalWgt_const})\n options = {'ftol': 1e-20, 'maxiter': 5000, 'disp': False}\n\n obejctive_func = EqualRiskContribution_objective\n if objective_type == 1:\n obejctive_func = EqualRiskContribution_objective\n elif objective_type == 2:\n obejctive_func = MinVariance_objective\n elif objective_type == 3:\n obejctive_func = MostDiversifiedPortfolio_objective\n\n result = minimize(fun=obejctive_func,\n x0=x0,\n method='SLSQP',\n constraints=constraints,\n options=options,\n bounds=bnds)\n #print(result)\n return (result.fun, result.x)\n\n\nfor objective_type in range(1, 4):\n\n # hyper-parameter\n acc_profit = 1\n period_term = 24 # Covariance Matrix 계산을 위한 기간 (12, 36 보다 24가 좋았음)\n\n # 결과 저장 parameter\n output_weights = {} # 기간별 & 자산별 가중치\n output_vols = {}\n output_profit = [] # 기간별 포트폴리오 수익률\n output_acc_profit = [] # 기간별 포트폴리오 누적 수익률\n output_vol = [] # 기간별 포트폴리오 변동성\n\n for prd_idx, index in enumerate(pivoted_droped_data.index):\n\n # 마지막 결정일은 weight 산출만 가능, 그 이후는 불가\n if index > pivoted_droped_data.index[-period_term]:\n print('break', prd_idx + period_term, len(pivoted_droped_data))\n break\n\n\n # 자산배분 결정일 (익일에 결정일 종가까지를 이용해서 계산)\n date = pivoted_droped_data.index[prd_idx + period_term - 1]\n\n # lb는 자산별 최소비율(%), ub는 자산별 최대비율(%)\n output_weights[date] = {}\n output_vols[date] = {}\n rst_value, rst_weights = ObjectiveVol(pivoted_droped_data[prd_idx:prd_idx + period_term], objective_type, target=0.1, lb=0.00, ub=1.00)\n asset_vols = pd.DataFrame.var(pivoted_droped_data[prd_idx:prd_idx + period_term])\n\n # 결과 저장을 위해 Container에 입력\n profit = 0\n for col_idx, column in enumerate(pivoted_droped_data.columns):\n output_weights[date][column] = rst_weights[col_idx]\n output_vols[date][column] = asset_vols.values[col_idx]\n\n if index < pivoted_droped_data.index[-period_term]:\n # 예를 들어 0~11까지 수익률로 변동성을 구하면 12의 수익률을 사용.\n profit += rst_weights[col_idx] * pivoted_droped_data[column][prd_idx + period_term]\n\n if index < pivoted_droped_data.index[-period_term]:\n acc_profit *= profit + 1\n\n # 결과 데이터\n output_profit.append(profit)\n output_acc_profit.append(acc_profit - 1)\n output_vol.append(math.sqrt(rst_weights.T @ pd.DataFrame.cov(pivoted_droped_data[prd_idx:prd_idx + period_term]) @ rst_weights) * math.sqrt(12))\n print(prd_idx, date, profit, acc_profit - 1, math.sqrt(rst_weights.T @ pd.DataFrame.cov(pivoted_droped_data[prd_idx:prd_idx + period_term]) @ rst_weights) * math.sqrt(12))\n\n result = pd.DataFrame.from_dict(output_weights).transpose()\n result['Vol'] = output_vol\n result['Profit'] = output_profit\n result['AccProfit'] = output_acc_profit\n\n if 1:\n File_Util.SaveExcelFiles(file='pivoted_data_%s.xlsx' % (objective_type), obj_dict={'pivoted_reference_datas': pivoted_reference_datas\n , 'pivoted_sample_datas': pivoted_sample_datas, 'pivoted_inserted_datas': pivoted_inserted_datas\n , 'pivoted_filled_datas': pivoted_filled_datas, 'pivoted_profit_data': pivoted_profit_data\n , 'pivoted_droped_data': pivoted_droped_data, 'Result': result , 'AssetVols': pd.DataFrame.from_dict(output_vols).transpose()})","sub_path":"CODE/LOGIC/AssetAllocation_Traditionals.py","file_name":"AssetAllocation_Traditionals.py","file_ext":"py","file_size_in_byte":12649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"595954323","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport importlib\nimport os\nimport shutil\nimport sys\nimport six.moves.urllib as urllib\n\nfrom unittest.mock import MagicMock\n\nsys.path.insert(0, os.path.abspath('.'))\nsys.path.insert(0, os.path.abspath('..'))\n\n\n# We have to mock the ffi module\nclass Mock(MagicMock):\n @classmethod\n def __getattr__(cls, name):\n return Mock()\n\n\nMOCK_MODULES = ['pywayland._ffi']\nsys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)\n\n# -- Build pywayland.protocol w/docs --------------------------------------\n\nprotocol_build_dir = '../pywayland/protocol/'\nprotocol_doc_dir = 'module/protocol'\n\nprotocol_version = '1.7.0'\nprotocol_source = 'http://cgit.freedesktop.org/wayland/wayland/plain/protocol/wayland.xml?id={}'.format(protocol_version)\n\nindex_header = \"\"\"\\\n.. _protocol:\n\nProtocol Modules\n================\n\nWayland protocols built against Wayland {}.\n\n.. toctree::\n :maxdepth: 2\n\n\"\"\".format(protocol_version)\n\nprotocol_rst = \"\"\"\\\n.. module:: pywayland.protocol.{mod_lower}\n\n{mod_upper}\n{empty:=^{len}}\n\n.. wl_protocol:: pywayland.protocol.{mod_lower} {mod_upper}\n\"\"\"\n\n\ndef protocol_build(output_dir):\n from pywayland.scanner import Scanner\n\n protocol_dest = 'wayland.xml'\n\n urllib.request.urlretrieve(protocol_source, protocol_dest)\n scanner = Scanner(protocol_dest)\n scanner.scan()\n scanner.output(output_dir)\n\n\n# There is probably a better way to do this in Sphinx, templating or something\n# ... but this works\ndef protocol_doc(input_dir, output_dir):\n py_files = os.listdir(input_dir)\n doc_files = [os.path.splitext(f)[0] for f in py_files\n if f[0] != '_']\n\n # Write out the index file\n index_file = os.path.join(output_dir, 'index.rst')\n with open(index_file, 'w') as f:\n f.write(index_header)\n for d in doc_files:\n f.write(' {}\\n'.format(d))\n\n for mod_lower in doc_files:\n mod = importlib.import_module('pywayland.protocol.' + mod_lower)\n for mod_upper in dir(mod):\n if mod_upper.lower() == mod_lower:\n break\n\n mod_len = len(mod_lower)\n doc_file = os.path.join(output_dir, '{}.rst'.format(mod_lower))\n with open(doc_file, 'w') as f:\n f.write(protocol_rst.format(\n mod_lower=mod_lower,\n mod_upper=mod_upper,\n len=mod_len,\n empty=''\n ))\n\n\n# Build the protocol directoryon RTD, or if it does not exist\nif os.environ.get('READTHEDOCS', None) or not os.path.exists(protocol_build_dir):\n if not os.path.exists(protocol_build_dir):\n os.makedirs(protocol_build_dir)\n\n protocol_build(protocol_build_dir)\n\n# Re-build the protocol documentation directory\nif os.path.exists(protocol_doc_dir):\n shutil.rmtree(protocol_doc_dir)\nos.makedirs(protocol_doc_dir)\n\nprotocol_doc(protocol_build_dir, protocol_doc_dir)\n\n\n# -- General configuration ------------------------------------------------\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx_wl_protocol'\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix of source filenames.\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# General information about the project.\nproject = 'pywayland'\ncopyright = '2015, Sean Vig'\n\n# The short X.Y version.\nversion = '0.0.1'\n# The full version, including alpha/beta/rc tags.\nrelease = '0.0.1a.dev5'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = ['_build']\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# Set the html_theme when building locally\nif not os.environ.get('READTHEDOCS', None):\n import sphinx_rtd_theme\n html_theme = 'sphinx_rtd_theme'\n html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'pywaylanddoc'\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n ('index', 'pywayland.tex', 'pywayland Documentation',\n 'Sean Vig', 'manual'),\n]\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n ('index', 'pywayland', 'pywayland Documentation',\n ['Sean Vig'], 1)\n]\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n ('index', 'pywayland', 'pywayland Documentation',\n 'Sean Vig', 'pywayland', 'Python bindings for the libwayland library',\n 'Miscellaneous'),\n]\n","sub_path":"doc/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":5164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"405467858","text":"import sys\nimport re\nfrom random import shuffle\ndata = {}\ndata_nodes = {}\ncurrent_file = None\ncurrent_cluster = None\nnum_clusters_start = 0\nfor line in sys.stdin:\n #print(line.strip())\n x = re.search(\"file.\\.txt\", line).group()\n words = line.split()\n num_clusters_start += 1\n nodes = [int(i) for i in re.search(\"nodes \\[(.*)\\] per\", line).group(1).split(\",\")]\n for i in nodes:\n data_nodes[i] = num_clusters_start\n perimeter = [int(i) for i in re.search(\"perimeter \\[(.*)\\]$\",line).group(1).split(\",\") if i != \"\"]\n data[num_clusters_start] = {'nodes':nodes, 'area': int(words[2]), 'perimeter':perimeter}\n\n#print(data)\n#print(data_nodes)\ndata_nodes_out = {}\nfor i in data_nodes:\n data_nodes_out[i] = None\ndata_out = {}\n\ndef add_to_cluster(c, x, area):\n data_out[c][\"area\"] = area\n for i in data[x][\"nodes\"]:\n data_out[c][\"nodes\"].append(i)\n data_nodes_out[i] = c\n for i in data[x][\"perimeter\"]:\n data_out[c][\"perimeter\"].append(i)\n #data_nodes[x] = c\n #print(data_out[c][\"perimeter\"])\n temp = []\n for i in data_out[c][\"perimeter\"]:\n #print(\"inside\",i, data_out[c][\"perimeter\"])\n if(i in data_out[c][\"nodes\"]):\n pass\n else:\n temp.append(i)\n data_out[c][\"perimeter\"] = temp\n \n\n\nnum_clusters = 0\nfor c in data:\n already_mapped = False\n for i in data[c][\"nodes\"]:\n if(data_nodes_out[i] != None):\n already_mapped = True\n \n print(\"Already_mapped: \", already_mapped, c)\n if(already_mapped):\n continue\n num_clusters += 1\n for i in data[c][\"nodes\"]:\n data_nodes_out[i] = num_clusters\n \n data_out[num_clusters] = {'nodes':data[c]['nodes'][:], 'area':data[c]['area'], 'perimeter':data[c]['perimeter'][:]}\n \n print(\"TOP\",c, data[c])\n print(data_nodes)\n #try:\n old_perimeter = len(data[c]['perimeter'])\n old_area = data[c][\"area\"]\n shuffle(data[c]['perimeter']) #add some much needed randomness\n for node in data[c]['perimeter']:\n if(data_nodes_out[node] != None):\n continue\n try:\n \n new_cluster = data_nodes[node]\n if(new_cluster == c): \n print(\"Already in the cluster!\")\n continue\n print(node, data_nodes[node], data[new_cluster])\n print(data[new_cluster][\"perimeter\"])\n links = 0 \n for new_new_node in data[new_cluster][\"perimeter\"]:\n try:\n print(new_new_node, data_nodes[new_new_node])\n if(data_nodes[new_new_node] == c):\n links += 1\n\n except KeyError:\n print(\"KeyError on new_new_node\", new_new_node)\n print(\"links: \" ,links)\n print(\"old_per: \",old_perimeter, \"old_area: \", old_area)\n new_area = old_area + links + data[new_cluster][\"area\"]\n new_perimeter = old_perimeter + len(data[new_cluster][\"perimeter\"]) -2*links\n print(\"new_per: \", new_perimeter, \"new_area: \", new_area)\n passed = new_area/(new_perimeter +0.0001) > old_area/(old_perimeter+0.0001)\n print(\"Pass? \", passed)\n if(passed): add_to_cluster(num_clusters, new_cluster, new_area)\n \n except KeyError:\n print(\"KeyError on\", node)\n \n\nprint(data_out)\nprint(data_nodes_out)\n","sub_path":"python/cluster/reduce_cluster.py","file_name":"reduce_cluster.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"411148059","text":"#!/usr/bin/env python3\nimport os.path\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nimport arrow\n\nfrom ipdb import set_trace\n\nfrom credentials import username, password\n\noutput_dir = \"data\"\ndump_file = \"aldi-{}-{:02d}.json\"\ncookie_file = \"cookies.json\"\n\n\nbase_url = \"https://www.alditalk-kundenbetreuung.de/de%s\"\nheaders = { \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36\" }\n\nsession = requests.Session()\nsession.headers.update(headers)\n\ndef get_csrf_token():\n resp = session.get(base_url % \"/\")\n bs = BeautifulSoup(resp.text, 'html.parser')\n token = bs.find('input', attrs={'name':'_csrf_token'}).attrs['value']\n print(\"Got csrf token {}\".format(token))\n return token\n\n\ndef login():\n if os.path.exists(cookie_file):\n session.cookies.update(json.load(open(cookie_file)))\n print(\"Found cookies\")\n return\n else:\n data = { '_csrf_token': get_csrf_token(),\n 'form[username]': username,\n 'form[password]': password,\n }\n\n resp = session.post(base_url % \"/login_check\", data=data, allow_redirects=False)\n assert resp.status_code == 302, \"Got no 302 back, login failed. Got {}\".format(resp.headers)\n assert resp.headers['Location'] == \"/de/\", \"Got wrong redirect: '{}'\".format(resp.headers['Location'])\n with open(cookie_file, \"w\") as f:\n json.dump(dict(session.cookies), f)\n print(\"Login ok\")\n\n\ndef dump(data, date_string):\n output_file = os.path.join(\"data\", date_string)\n with open(output_file, \"w\") as f:\n json.dump(data, f)\n print(\"Dump data to {}\".format(output_file))\n\n\ndef get_kilobyte(volume, unit):\n factor = 1.0\n if unit == \"KB\":\n factor = 1.0/1024.0\n if unit == \"GB\":\n factor = 1024.0\n return round(float(volume)*factor, 2)\n\n\ndef get_einzelverbindung_of_month(year, month):\n data = []\n url = \"https://www.alditalk-kundenbetreuung.de/de/konto/kontoubersicht/einzelverbindungen?month={}-{:02d}&date=&voice=&data=&sms=&extended=\".format(year, month)\n resp = session.get(url)\n bs = BeautifulSoup(resp.text, 'html.parser')\n for entry in bs.findAll('tr', attrs={'class':\"egn-free\"}):\n if not \"Volumen\" in entry.text:\n # do nothing for a call\n continue\n __, date, time, __, __, __, volume, unit = entry.text.strip().split()\n data.append({'date': date, 'time': time, 'volume': get_kilobyte(volume, unit), 'unit': 'MB' })\n date_string = dump_file.format(year, month)\n #dump(data, date_string)\n return data\n\n\ndef iterate_months():\n for month in range(1, 5):\n get_einzelverbindung_of_month(2019, month)\n\n\ndef get_abo_infos():\n print(\"get abo infos\")\n resp = session.get(\"https://www.alditalk-kundenbetreuung.de/de\")\n bs = BeautifulSoup(resp.text, 'html.parser')\n free = bs.find(\"span\", attrs={'class':'pack__usage-remaining'}).text\n total = bs.find(\"span\", attrs={'class':'pack__usage-total'}).text\n unit = bs.find(\"span\", attrs={'class':'pack__usage-unit'}).text\n table_ugly = bs.find(\"div\", attrs={'class':'table'})\n abo_bis = table_ugly.findAll(\"td\")[4].text\n return \"Volumen: {}/{} {} - läuft bis {}\".format(free, total, unit, abo_bis)\n\n\ndef get_summary_of_current_month():\n print(\"get sumary of month\")\n today = arrow.now()\n data = get_einzelverbindung_of_month(today.year, today.month)\n data = sorted(data, key=lambda x: x['volume'], reverse=True)[:10]\n output = []\n for e in data:\n day_of_week = arrow.get(e['date'], \"DD.MM.YYYY\").format(\"dddd\")\n output.append(\"{} {:9s} {:10s} {:6.2f} {}\".format(e['date'], day_of_week, e['time'], e['volume'], e['unit']))\n #print(\"\\n\".join(output))\n return output\n\n\ndef go():\n login()\n output = []\n output.append(get_abo_infos())\n output.extend(get_summary_of_current_month())\n #print(output)\n return output\n\nif __name__ == '__main__':\n #login()\n #iterate_months()\n go()\n","sub_path":"aldi.py","file_name":"aldi.py","file_ext":"py","file_size_in_byte":4057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"197731735","text":"# -*- coding: utf-8 -*-\n# Copyright 2018 Mobicage NV\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# @@license_version:1.3@@\n\nimport logging\n\nfrom jinja2 import nodes\nfrom jinja2.ext import Extension\n\nfrom shop.business.i18n import shop_translate\n\n\nclass TranslateExtension(Extension):\n tags = {'shop_translate'}\n\n def parse(self, parser):\n _ = parser.parse_expression() # translate tag\n args = parser.parse_tuple()\n args = [a for a in args.iter_child_nodes()]\n return nodes.Output([self.call_method('_translate', args), ])\n\n def _translate(self, language, key, *args):\n try:\n kwargs = dict()\n for arg in args:\n arg_pieces = arg.split('=', 1)\n kwargs[arg_pieces[0]] = arg_pieces[1]\n\n translation = shop_translate(language, key, **kwargs)\n if \"_html\" in kwargs:\n translation = translation.replace('\\n', '
')\n return translation\n except:\n logging.error(\"Failed to translate %s\" % key, exc_info=1)\n raise\n","sub_path":"src/shop/jinja_extensions.py","file_name":"jinja_extensions.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"571956429","text":"#第十七章 使用webAPI\n#17.1.1-17.1.4\nimport requests\nimport pygal\nfrom pygal.style import LightColorizedStyle as LCS,LightenStyle as LS\n#执行API调用并存储响应\nurl = 'https://api.github.com/search/repositories?q=language:Go&sort=stars'\nr =requests.get(url)\nprint(\"stars code\",r.status_code)\n\n#将API响应存储在一个变量中\nresponse_dict = r.json()\n#处理结果\n\n# print(requests_dict.keys())\n\n#17.1.1-17.1.4\n#\nprint(\"Total respositories:\",response_dict['total_count'])\n\n#17.1.5探索有关仓库的信息\n\nrepo_dicts = response_dict['items']\nprint(\"Respositories returned:\",len(repo_dicts))\n\n#研究第一个仓库\n# repo_dict = repo_dicts[0]\n# print(\"\\nKeys:\",len(repo_dict))\n# for key in sorted(repo_dict.keys()):\n# print(key)\n#print(\"\\nselected infomation about each respository:\")\n#17.1.6-17.1.7概述最受欢饮的仓库\n# for repo_dict in repo_dicts:\n# print('Name:',repo_dict['name'])\n# print('Owner:',repo_dict['owner']['login'])\n# print('Stars:',repo_dict['stargazers_count'])\n# print('Respository:',repo_dict['html_url'])\n# print('Created:',repo_dict['created_at'])\n# print('Updated:',repo_dict['updated_at'])\n# print('Description:',repo_dict['description'])\n#\n\n#17.2.0使用pygal可视化仓库\n#\n# names,stars =[],[]\n# for repo_dict in repo_dicts:\n# names.append(repo_dict['name'])\n# stars.append(repo_dict['stargazers_count'])\n#\n# my_style =LS('#333366',base_style=LCS)\n# chart = pygal.Bar(style = my_style,x_label_rotation=20,show_legend=False)\n# chart.title = 'Most - Starred python projects on GitHub'\n# chart.x_labels =names\n#\n# chart.add('',stars)\n# chart.render_to_file('python_repos.svg')\n#17.2.1改进pygal图标\n\nnames = []\n# stars=[]\nplot_dicts =[]\nfor repo_dict in repo_dicts:\n names.append(repo_dict['name'])\n # stars.append(repo_dict['stargazers_count'])\n plot_dict ={\n 'value':repo_dict['stargazers_count'],\n 'label':str(repo_dict['description']),\n 'xlink': repo_dict['html_url'],\n }\n plot_dicts.append(plot_dict)\n#可视化\nmy_style =LS('#333366',base_style=LCS)\n\nmy_config = pygal.Config()\nmy_config.x_label_rotation = 45\nmy_config.show_legend =False\nmy_config.title_font_siza =24\nmy_config.label_font_size =14\nmy_config.major_label_font_size = 18\nmy_config.truncate_label = 15\nmy_config.show_y_guides = False\nmy_config.width = 1000\n\nchart = pygal.Bar(my_config,style = my_style)\nchart.title = 'Most - Starred python projects on GitHub'\nchart.x_labels =names\n\nchart.add('',plot_dicts)\nchart.render_to_file('Go_repos2.svg')","sub_path":"python_repos.py","file_name":"python_repos.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"514550698","text":"from __future__ import print_function\n\n\ndef binomial_coeff_recursive(n, k):\n \"\"\"\" A naive recursive Python implementation\"\"\"\n if k == 0 or k == n:\n return 1\n\n # Recursive Call\n return binomial_coeff_recursive(n - 1, k - 1) + binomial_coeff_recursive(\n n - 1, k)\n\n\ndef binomial_coeff_dynamic(n, k):\n \"\"\"A Dynamic Programming based Python Program that uses table C[][] to\n calculate the Binomial Coefficient\n\n Returns value of Binomial Coefficient C(n, k)\"\"\"\n C = [[0 for _ in range(k + 1)] for _ in range(n + 1)]\n\n # Calculate value of Binomial Coefficient in bottom up manner\n for i in range(n + 1):\n for j in range(min(i, k) + 1):\n # Base Cases\n if j == 0 or j == i:\n C[i][j] = 1\n\n # Calculate value using previously stored values\n else:\n C[i][j] = C[i - 1][j - 1] + C[i - 1][j]\n\n return C[n][k]\n\n\nn = 5\nk = 2\nprint('Value of C({0}, {1}) is ({2})'.format(n, k,\n binomial_coeff_recursive(n, k)))\nprint('Value of C({0}, {1}) is ({2})'.format(n, k,\n binomial_coeff_dynamic(n, k)))\n","sub_path":"pascal_given_col_row_recursive_dynamic.py","file_name":"pascal_given_col_row_recursive_dynamic.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"552689498","text":"import socket\nfrom pathlib import Path\nfrom utils import extract_route, read_file, load_data\n\nCUR_DIR = Path(__file__).parent\nSERVER_HOST = '0.0.0.0'\nSERVER_PORT = 8080\n\nNOTE_TEMPLATE = '''
  • \n

    {title}

    \n

    {details}

    \n
  • \n'''\n\nRESPONSE_TEMPLATE = '''HTTP/1.1 200 OK\n\n\n\n\n\nGet-it\n\n\n\n\n

    Como o Post-it, mas com outro verbo

    \n\n
      \n{notes}\n
    \n\n\n\n'''\n\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver_socket.bind((SERVER_HOST, SERVER_PORT))\nserver_socket.listen()\n\nprint(f'Servidor escutando em (ctrl+click): http://{SERVER_HOST}:{SERVER_PORT}')\n\nwhile True:\n client_connection, client_address = server_socket.accept()\n\n request = client_connection.recv(1024).decode()\n #print(request)\n\n route = extract_route(request)\n filepath = CUR_DIR / route\n if filepath.is_file():\n response = 'HTTP/1.1 200 OK\\n\\n'.encode() + read_file(filepath)\n else:\n # Cria uma lista de
  • 's para cada anotação\n # Se tiver curiosidade: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\n notes_li = [\n NOTE_TEMPLATE.format(title=dados['titulo'], details=dados['detalhes'])\n for dados in load_data('notes.json')\n ]\n notes = '\\n'.join(notes_li)\n\n response = RESPONSE_TEMPLATE.format(notes=notes).encode()\n client_connection.sendall(response)\n\n client_connection.close()\n\nserver_socket.close()","sub_path":"handout1/server_p3.py","file_name":"server_p3.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"211393803","text":"from django.conf.urls import url\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n url(r'^upload/$',views.upload,name='upload'),\r\n url(r'^allupload/$',views.allupload,name='allupload'),\r\n url(r'^showall/$',views.showall,name='showall'),\r\n #url(r'^showmore/(?P\\d\\d\\w\\w\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d)/$',views.showmore),\r\n url(r'^showmore/(?P\\w+([-+.]\\w+)*\\w+([-.]\\w+)*\\w+([-.]\\w+)*)/$',views.showmore), \r\n]\r\n","sub_path":"gongzuo/example001/example1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"463963854","text":"from abc import abstractmethod, ABCMeta\nimport json\nimport uuid\nimport base64\nimport os\nimport math\nfrom time import strftime, gmtime\n\nfrom .audi_models import (\n CurrentVehicleDataResponse,\n VehicleDataResponse,\n VehiclesResponse,\n Vehicle,\n)\nfrom .audi_api import AudiAPI\nfrom .util import to_byte_array, get_attr\n\nfrom hashlib import sha256, sha512\nimport asyncio\n\nfrom urllib.parse import urlparse, parse_qs\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom requests import RequestException\n\nfrom typing import Dict\n\n\nMAX_RESPONSE_ATTEMPTS = 10\nREQUEST_STATUS_SLEEP = 10\n\nSUCCEEDED = \"succeeded\"\nFAILED = \"failed\"\nREQUEST_SUCCESSFUL = \"request_successful\"\nREQUEST_FAILED = \"request_failed\"\n\nXCLIENT_ID = \"77869e21-e30a-4a92-b016-48ab7d3db1d8\"\n\n\nclass BrowserLoginResponse:\n def __init__(self, response: requests.Response, url: str):\n self.response = response # type: requests.Response\n self.url = url # type : str\n\n def get_location(self) -> str:\n \"\"\"\n Returns the location the previous request redirected to\n \"\"\"\n location = self.response.headers[\"Location\"]\n if location.startswith(\"/\"):\n # Relative URL\n return BrowserLoginResponse.to_absolute(self.url, location)\n return location\n\n @classmethod\n def to_absolute(cls, absolute_url, relative_url) -> str:\n \"\"\"\n Converts a relative url to an absolute url\n :param absolute_url: Absolute url used as baseline\n :param relative_url: Relative url (must start with /)\n :return: New absolute url\n \"\"\"\n url_parts = urlparse(absolute_url)\n return url_parts.scheme + \"://\" + url_parts.netloc + relative_url\n\n\nclass AudiService:\n def __init__(self, api: AudiAPI, country: str, spin: str):\n self._api = api\n self._country = country\n self._type = \"Audi\"\n self._spin = spin\n self._homeRegion = {}\n self._homeRegionSetter = {}\n\n if self._country is None:\n self._country = \"DE\"\n\n async def login(self, user: str, password: str, persist_token: bool = True):\n await self.login_request(user, password)\n\n async def refresh_vehicle_data(self, vin: str):\n res = await self.request_current_vehicle_data(vin.upper())\n request_id = res.request_id\n\n checkUrl = \"{homeRegion}/fs-car/bs/vsr/v1/{type}/{country}/vehicles/{vin}/requests/{requestId}/jobstatus\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type,\n country=self._country,\n vin=vin.upper(),\n requestId=request_id,\n )\n\n await self.check_request_succeeded(\n checkUrl,\n \"refresh vehicle data\",\n REQUEST_SUCCESSFUL,\n REQUEST_FAILED,\n \"requestStatusResponse.status\",\n )\n\n async def request_current_vehicle_data(self, vin: str):\n self._api.use_token(self.vwToken)\n data = await self._api.post(\n \"{homeRegion}/fs-car/bs/vsr/v1/{type}/{country}/vehicles/{vin}/requests\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n )\n return CurrentVehicleDataResponse(data)\n\n async def get_preheater(self, vin: str):\n self._api.use_token(self.vwToken)\n return await self._api.get(\n \"{homeRegion}/fs-car/bs/rs/v1/{type}/{country}/vehicles/{vin}/status\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n )\n \n async def get_preheater(self, vin: str):\n self._api.use_token(self.vwToken)\n return await self._api.get(\n \"{homeRegion}/fs-car/bs/rs/v1/{type}/{country}/vehicles/{vin}/status\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n ) \n async def get_stored_vehicle_data(self, vin: str):\n self._api.use_token(self.vwToken)\n data = await self._api.get(\n \"{homeRegion}/fs-car/bs/vsr/v1/{type}/{country}/vehicles/{vin}/status\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n )\n return VehicleDataResponse(data)\n\n async def get_charger(self, vin: str):\n self._api.use_token(self.vwToken)\n return await self._api.get(\n \"{homeRegion}/fs-car/bs/batterycharge/v1/{type}/{country}/vehicles/{vin}/charger\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n )\n\n async def get_climater(self, vin: str):\n self._api.use_token(self.vwToken)\n return await self._api.get(\n \"{homeRegion}/fs-car/bs/climatisation/v1/{type}/{country}/vehicles/{vin}/climater\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n )\n\n async def get_stored_position(self, vin: str):\n self._api.use_token(self.vwToken)\n return await self._api.get(\n \"{homeRegion}/fs-car/bs/cf/v1/{type}/{country}/vehicles/{vin}/position\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n )\n\n async def get_operations_list(self, vin: str):\n self._api.use_token(self.vwToken)\n return await self._api.get(\n \"https://mal-1a.prd.ece.vwg-connect.com/api/rolesrights/operationlist/v3/vehicles/\"\n + vin.upper()\n )\n\n async def get_timer(self, vin: str):\n self._api.use_token(self.vwToken)\n return await self._api.get(\n \"{homeRegion}/fs-car/bs/departuretimer/v1/{type}/{country}/vehicles/{vin}/timer\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n )\n\n async def get_vehicles(self):\n self._api.use_token(self.vwToken)\n return await self._api.get(\n \"https://msg.volkswagen.de/fs-car/usermanagement/users/v1/{type}/{country}/vehicles\".format(\n type=self._type, country=self._country\n )\n )\n\n async def get_vehicle_information(self):\n self._api.use_token(self.audiToken)\n data = await self._api.get(\n \"https://msg.audi.de/myaudi/vehicle-management/v2/vehicles\"\n )\n response = VehiclesResponse()\n response.parse(data)\n return response\n\n async def get_vehicle_data(self, vin: str):\n self._api.use_token(self.vwToken)\n data = await self._api.get(\n \"{homeRegion}/fs-car/vehicleMgmt/vehicledata/v2/{type}/{country}/vehicles/{vin}/\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n )\n )\n\n async def _fill_home_region(self, vin: str): \n self._homeRegion[vin] = \"https://msg.volkswagen.de\"\n self._homeRegionSetter[vin] = \"https://mal-1a.prd.ece.vwg-connect.com\"\n\n try:\n self._api.use_token(self.vwToken)\n res = await self._api.get(\"https://mal-1a.prd.ece.vwg-connect.com/api/cs/vds/v1/vehicles/{vin}/homeRegion\".format(vin=vin))\n if res != None and res.get(\"homeRegion\") != None and res[\"homeRegion\"].get(\"baseUri\") != None and res[\"homeRegion\"][\"baseUri\"].get(\"content\") != None:\n uri = res[\"homeRegion\"][\"baseUri\"][\"content\"]\n if uri != \"https://mal-1a.prd.ece.vwg-connect.com/api\":\n self._homeRegionSetter[vin] = uri.split(\"/api\")[0]\n self._homeRegion[vin] = self._homeRegionSetter[vin].replace(\"mal-\", \"fal-\")\n except Exception:\n pass\n\n async def _get_home_region(self, vin: str):\n if self._homeRegion.get(vin) != None:\n return self._homeRegion[vin]\n\n await self._fill_home_region(vin)\n \n return self._homeRegion[vin]\n\n async def _get_home_region_setter(self, vin: str):\n if self._homeRegionSetter.get(vin) != None:\n return self._homeRegionSetter[vin]\n\n await self._fill_home_region(vin)\n \n return self._homeRegionSetter[vin]\n\n async def _get_security_token(self, vin: str, action: str):\n # Challenge\n headers = {\n \"User-Agent\": \"okhttp/3.7.0\",\n \"X-App-Version\": \"3.14.0\",\n \"X-App-Name\": \"myAudi\",\n \"Accept\": \"application/json\",\n \"Authorization\": \"Bearer \" + self.vwToken.get(\"access_token\"),\n }\n\n body = await self._api.request(\n \"GET\",\n \"{homeRegionSetter}/api/rolesrights/authorization/v2/vehicles/\".format(homeRegionSetter=await self._get_home_region_setter(vin.upper()))\n + vin.upper()\n + \"/services/\"\n + action\n + \"/security-pin-auth-requested\",\n headers=headers,\n data=None,\n )\n secToken = body[\"securityPinAuthInfo\"][\"securityToken\"]\n challenge = body[\"securityPinAuthInfo\"][\"securityPinTransmission\"][\"challenge\"]\n\n # Response\n securityPinHash = self._generate_security_pin_hash(challenge)\n data = {\n \"securityPinAuthentication\": {\n \"securityPin\": {\n \"challenge\": challenge,\n \"securityPinHash\": securityPinHash,\n },\n \"securityToken\": secToken,\n }\n }\n\n headers = {\n \"User-Agent\": \"okhttp/3.7.0\",\n \"Content-Type\": \"application/json\",\n \"X-App-Version\": \"3.14.0\",\n \"X-App-Name\": \"myAudi\",\n \"Accept\": \"application/json\",\n \"Authorization\": \"Bearer \" + self.vwToken.get(\"access_token\"),\n }\n\n body = await self._api.request(\n \"POST\",\n \"{homeRegionSetter}/api/rolesrights/authorization/v2/security-pin-auth-completed\".format(homeRegionSetter=await self._get_home_region_setter(vin.upper())),\n headers=headers,\n data=json.dumps(data),\n )\n return body[\"securityToken\"]\n\n def _get_vehicle_action_header(self, content_type: str, security_token: str):\n headers = {\n \"User-Agent\": \"okhttp/3.7.0\",\n \"Host\": \"msg.volkswagen.de\",\n \"X-App-Version\": \"3.14.0\",\n \"X-App-Name\": \"myAudi\",\n \"Authorization\": \"Bearer \" + self.vwToken.get(\"access_token\"),\n \"Accept-charset\": \"UTF-8\",\n \"Content-Type\": content_type,\n \"Accept\": \"application/json, application/vnd.vwg.mbb.ChargerAction_v1_0_0+xml,application/vnd.volkswagenag.com-error-v1+xml,application/vnd.vwg.mbb.genericError_v1_0_2+xml, application/vnd.vwg.mbb.RemoteStandheizung_v2_0_0+xml, application/vnd.vwg.mbb.genericError_v1_0_2+xml,application/vnd.vwg.mbb.RemoteLockUnlock_v1_0_0+xml,*/*\",\n }\n\n if security_token != None:\n headers[\"x-mbbSecToken\"] = security_token\n\n return headers\n\n async def set_vehicle_lock(self, vin: str, lock: bool):\n security_token = await self._get_security_token(\n vin, \"rlu_v1/operations/\" + (\"LOCK\" if lock else \"UNLOCK\")\n )\n data = '{action}'.format(\n action=\"lock\" if lock else \"unlock\"\n )\n headers = self._get_vehicle_action_header(\n \"application/vnd.vwg.mbb.RemoteLockUnlock_v1_0_0+xml\", security_token\n )\n res = await self._api.request(\n \"POST\",\n \"{homeRegion}/fs-car/bs/rlu/v1/{type}/{country}/vehicles/{vin}/actions\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n ),\n headers=headers,\n data=data,\n )\n\n checkUrl = \"{homeRegion}/fs-car/bs/rlu/v1/{type}/{country}/vehicles/{vin}/requests/{requestId}/status\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type,\n country=self._country,\n vin=vin.upper(),\n requestId=res[\"rluActionResponse\"][\"requestId\"],\n )\n\n await self.check_request_succeeded(\n checkUrl,\n \"lock vehicle\" if lock else \"unlock vehicle\",\n REQUEST_SUCCESSFUL,\n REQUEST_FAILED,\n \"requestStatusResponse.status\",\n )\n\n async def set_battery_charger(self, vin: str, start: bool):\n data = '{action}'.format(\n action=\"start\" if start else \"stop\"\n )\n headers = self._get_vehicle_action_header(\n \"application/vnd.vwg.mbb.ChargerAction_v1_0_0+xml\", None\n )\n res = await self._api.request(\n \"POST\",\n \"{homeRegion}/fs-car/bs/batterycharge/v1/{type}/{country}/vehicles/{vin}/charger/actions\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n ),\n headers=headers,\n data=data,\n )\n\n checkUrl = \"{homeRegion}/fs-car/bs/batterycharge/v1/{type}/{country}/vehicles/{vin}/charger/actions/{actionid}\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type,\n country=self._country,\n vin=vin.upper(),\n actionid=res[\"action\"][\"actionId\"],\n )\n\n await self.check_request_succeeded(\n checkUrl,\n \"start charger\" if start else \"stop charger\",\n SUCCEEDED,\n FAILED,\n \"action.actionState\",\n )\n\n async def set_climatisation(self, vin: str, start: bool):\n if start:\n data = 'startClimatisationelectric'\n else:\n data = 'stopClimatisation'\n\n headers = self._get_vehicle_action_header(\n \"application/vnd.vwg.mbb.ClimaterAction_v1_0_0+xml;charset=utf-8\", None\n )\n res = await self._api.request(\n \"POST\",\n \"{homeRegion}/fs-car/bs/climatisation/v1/{type}/{country}/vehicles/{vin}/climater/actions\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n ),\n headers=headers,\n data=data,\n )\n\n checkUrl = \"{homeRegion}/fs-car/bs/climatisation/v1/{type}/{country}/vehicles/{vin}/climater/actions/{actionid}\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type,\n country=self._country,\n vin=vin.upper(),\n actionid=res[\"action\"][\"actionId\"],\n )\n\n await self.check_request_succeeded(\n checkUrl,\n \"start climatisation\" if start else \"stop climatisation\",\n SUCCEEDED,\n FAILED,\n \"action.actionState\",\n )\n\n async def set_window_heating(self, vin: str, start: bool):\n data = '{action}'.format(\n action=\"startWindowHeating\" if start else \"stopWindowHeating\"\n )\n\n headers = self._get_vehicle_action_header(\n \"application/vnd.vwg.mbb.ClimaterAction_v1_0_0+xml\", None\n )\n res = await self._api.request(\n \"POST\",\n \"{homeRegion}/fs-car/bs/climatisation/v1/{type}/{country}/vehicles/{vin}/climater/actions\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n ),\n headers=headers,\n data=data,\n )\n\n checkUrl = \"{homeRegion}/fs-car/bs/climatisation/v1/{type}/{country}/vehicles/{vin}/climater/actions/{actionid}\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type,\n country=self._country,\n vin=vin.upper(),\n actionid=res[\"action\"][\"actionId\"],\n )\n\n await self.check_request_succeeded(\n checkUrl,\n \"start window heating\" if start else \"stop window heating\",\n SUCCEEDED,\n FAILED,\n \"action.actionState\",\n )\n\n async def set_pre_heater(self, vin: str, activate: bool):\n security_token = await self._get_security_token(\n vin, \"rheating_v1/operations/P_QSACT\"\n )\n\n data = '{input}'.format(\n input='true'\n if activate\n else 'false'\n )\n\n headers = self._get_vehicle_action_header(\n \"application/vnd.vwg.mbb.RemoteStandheizung_v2_0_0+xml\", security_token\n )\n await self._api.request(\n \"POST\",\n \"{homeRegion}/fs-car/bs/rs/v1/{type}/{country}/vehicles/{vin}/action\".format(\n homeRegion=await self._get_home_region(vin.upper()),\n type=self._type, country=self._country, vin=vin.upper()\n ),\n headers=headers,\n data=data,\n )\n\n async def check_request_succeeded(\n self, url: str, action: str, successCode: str, failedCode: str, path: str\n ):\n\n for _ in range(MAX_RESPONSE_ATTEMPTS):\n await asyncio.sleep(REQUEST_STATUS_SLEEP)\n\n self._api.use_token(self.vwToken)\n res = await self._api.get(url)\n\n status = get_attr(res, path)\n\n if status is None or (failedCode is not None and status == failedCode):\n raise Exception(\n \"Cannot {action}, return code '{code}'\".format(\n action=action, code=status\n )\n )\n\n if status == successCode:\n return\n\n raise Exception(\"Cannot {action}, operation timed out\".format(action=action))\n\n # 13.09.2020 New login taken from https://github.com/davidgiga1993/AudiAPI/issues/13\n async def login_request(self, user: str, password: str):\n self._api.use_token(None)\n\n # OpenID Configuration\n if self._country.upper() == \"US\":\n configuration_endpoint = \"https://idkproxy-service.apps.na.vwapps.io/v1/na/openid-configuration\"\n client_id = \"7c6b4634-f0c5-488b-a78f-b1a65414fb90@apps_vw-dilab_com\"\n else:\n configuration_endpoint = \"https://idkproxy-service.apps.emea.vwapps.io/v1/emea/openid-configuration\"\n client_id = \"09b6cbec-cd19-4589-82fd-363dfa8c24da@apps_vw-dilab_com\"\n\n openid_configuration = await self._api.get(configuration_endpoint)\n authorization_endpoint = openid_configuration.get(\"authorization_endpoint\")\n\n # Authorization code\n state = str(uuid.uuid4())\n nonce = str(uuid.uuid4())\n query_params = {\n \"response_type\": \"token id_token\",\n \"client_id\": client_id,\n \"redirect_uri\": \"myaudi:///\",\n \"scope\": \"address profile badge birthdate birthplace nationalIdentifier nationality profession email \"\n \"vin phone nickname name picture mbb gallery openid\",\n \"state\": state,\n \"nonce\": nonce,\n \"prompt\": \"login\",\n \"ui_locales\": \"en-US en\",\n }\n reply = await self._api.get(\n authorization_endpoint,\n raw_reply=True,\n allow_redirects=False,\n params=query_params,\n )\n\n # Submit the email\n reply = await self._emulate_browser(\n BrowserLoginResponse(reply, authorization_endpoint), {\"email\": user}\n )\n\n # Submit the password\n reply = await self._emulate_browser(reply, {\"password\": password})\n\n sso_url = reply.get_location()\n sso_reply = await self._api.get(sso_url, raw_reply=True, allow_redirects=False)\n consent_url = BrowserLoginResponse(sso_reply, sso_url).get_location()\n consent_reply = await self._api.get(\n consent_url, raw_reply=True, allow_redirects=False\n )\n success_url = BrowserLoginResponse(consent_reply, consent_url).get_location()\n success_reply = await self._api.get(\n success_url, raw_reply=True, allow_redirects=False\n )\n query_strings = parse_qs(\n urlparse(success_reply.headers.get(\"location\")).fragment\n )\n access_token = query_strings[\"access_token\"][0]\n id_token = query_strings[\"id_token\"][0]\n\n # Get the Audi Token\n data = {\n \"config\": \"myaudi\",\n \"grant_type\": \"id_token\",\n \"stage\": \"live\",\n \"token\": access_token,\n }\n reply = await self._api.post(\n \"https://app-api.live-my.audi.com/azs/v1/token\", data=data\n )\n self.audiToken = reply\n\n # Get the VW Token\n data = {\n \"grant_type\": \"id_token\",\n \"scope\": \"sc2:fal\",\n \"token\": id_token,\n }\n headers = {\"X-Client-ID\": XCLIENT_ID}\n reply = await self._api.post(\n \"https://mbboauth-1d.prd.ece.vwg-connect.com/mbbcoauth/mobile/oauth2/v1/token\",\n data=data,\n headers=headers,\n use_json=False,\n )\n self.vwToken = reply\n\n def _generate_security_pin_hash(self, challenge):\n pin = to_byte_array(self._spin)\n byteChallenge = to_byte_array(challenge)\n b = bytes(pin + byteChallenge)\n return sha512(b).hexdigest().upper()\n\n async def _emulate_browser(\n self, reply: BrowserLoginResponse, form_data: Dict[str, str]\n ) -> BrowserLoginResponse:\n # The reply redirects to the login page\n login_location = reply.get_location()\n page_reply = await self._api.get(login_location, raw_contents=True)\n\n # Now parse the html body and extract the target url, csfr token and other required parameters\n html = BeautifulSoup(page_reply, \"html.parser\")\n form_tag = html.find(\"form\")\n\n form_inputs = html.find_all(\"input\", attrs={\"type\": \"hidden\"})\n for form_input in form_inputs:\n name = form_input.get(\"name\")\n form_data[name] = form_input.get(\"value\")\n\n # Extract the target url\n action = form_tag.get(\"action\")\n if action.startswith(\"http\"):\n # Absolute url\n username_post_url = action\n elif action.startswith(\"/\"):\n # Relative to domain\n username_post_url = BrowserLoginResponse.to_absolute(login_location, action)\n else:\n raise RequestException(\"Unknown form action: \" + action)\n\n headers = {\"referer\": login_location}\n reply = await self._api.post(\n username_post_url,\n form_data,\n headers=headers,\n use_json=False,\n raw_reply=True,\n allow_redirects=False,\n )\n return BrowserLoginResponse(reply, username_post_url)\n","sub_path":"custom_components/audiconnect/audi_services.py","file_name":"audi_services.py","file_ext":"py","file_size_in_byte":24064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"68874559","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nget_ipython().system('pip install requests')\n\n\n# In[ ]:\n\n\n#!/usr/bin/env python\n#conding=utf-8\n\n\nimport paho.mqtt.client as mqtt\nimport pymysql\nimport logging \nimport requests\ntoken = 'c3XbAW87YujrhR6KKNGQSKWReX3sTKtvMkxzpLJNf8N'\nmoidrypir1warning = '注意!!!土壤太乾,有人經過感測區!!!'\nmoidrypir0warning = '注意!!!土壤太乾!!!'\nmoiwatpir1warning = '注意!!!土壤太濕,有人經過感測區!!!'\nmoiwatpir0warning = '注意!!!土壤太濕!!!'\nmoinonpir1warning = '注意!!!有人經過感測區!!!'\n\n\ndef linenotifyMessage(token, msg):\n headers = {\n \"Authorization\": \"Bearer \" + token, \n \"Content-Type\" : \"application/x-www-form-urlencoded\"\n }\n\n payload = {'message': msg}\n r = requests.post(\"https://notify-api.line.me/api/notify\", headers = headers, params = payload)\n return r.status_code\n\n # 修改為你要傳送的訊息內容\n#message = 'Notify from LINE, HELLO WORLD'\n # 修改為你的權杖內容\n\n\n\n\n\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n\n # 將訂閱主題寫在on_connet中\n # 如果我們失去連線或重新連線時 \n # 地端程式將會重新訂閱\n client.subscribe(\"GIOT-GW/UL/1C497B455949\")\n\n# 當接收到從伺服器發送的訊息時要進行的動作\ndef on_message(client, userdata, msg):\n # 轉換編碼utf-8才看得懂中文\n #print(msg.topic+\" \"+ msg.payload.decode('utf-8'))\n data = msg.payload.decode('utf-8')\n str_data = str(data)\n data_split = str_data.split(',',-1)\n mac = data_split[11][12:28]\n\n \n if mac =='00000000aa110090':\n sadata = data_split[12][9:19]\n MOI = sadata[0:3]\n PIR = sadata[3:6]\n print(MOI)\n print(PIR)\n \n moi = int(MOI)\n pir = int(PIR)\n \n \n \n if moi <= 50 and pir == 1:\n linenotifyMessage(token, moidrypir1warning)\n elif moi <= 50 and pir == 0:\n linenotifyMessage(token, moidrypir0warning)\n elif moi >= 85 and pir == 1:\n linenotifyMessage(token, moiwatpir1warning)\n elif moi >= 85 and pir == 0:\n linenotifyMessage(token, moiwatpir0warning)\n elif moi < 85 and moi > 50 and pir == 1:\n linenotifyMessage(token, moinonpir1warning)\n else:\n None\n \n \n\n\n\n \n \n \n\n \n \n \n\n\n# 連線設定\n# 初始化地端程式\nclient = mqtt.Client()\n\n# 設定連線的動作\nclient.on_connect = on_connect\n\n# 設定接收訊息的動作\nclient.on_message = on_message\n\n# 設定登入帳號密碼\nclient.username_pw_set(\"admin\",\"admin\")\n\n# 設定連線資訊(IP, Port, 連線時間)\nclient.connect(\"104.199.215.165\", 1883, 60)\n\n# 開始連線,執行設定的動作和處理重新連線問題\n# 也可以手動使用其他loop函式來進行連接\nclient.loop_forever()\n\n\n# In[ ]:\n\n#test for git pull\n\n\n","sub_path":"linenotify.py","file_name":"linenotify.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"59115127","text":"from layer import *\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport glob\n\n\n# this depends on your own file path!\n\npath = 'C:/Users/eid7/Documents/GitHub/alexnet-sbs/dataSet/parsed_test/*.npy'\nfnames = glob.glob(path)\n#test_path = \"D:/alexnet-sbs/dataSet//*.npy\"\nclass batch_helper():\n def __init__(self):\n self.batches = []\n self.test_input = []\n self.test_label = []\n\n def load_data(self):\n for filename in fnames:\n print('Loading ' + filename)\n self.batches.append(np.load(filename))\n\n def next_batch(self):\n return self.batches.pop()\n\n def set_test_img(self, path):\n self.test = np.load(path)\n for item in self.test:\n self.test_input.append(item[1].flatten())\n self.test_label.append(item[0])\n\n\n# BUILD NET\npred = alex_net(x_input, weights, biases, keep_prob)\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_true, logits = pred))\ntrain = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n# TEST NETWORK\nmatches = tf.equal(tf.argmax(pred, 1), tf.argmax(y_true, 1))\naccuracy = tf.reduce_mean(tf.cast(matches, tf.float32))\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n feeder = batch_helper()\n feeder.load_data()\n feeder.set_test_img(\"C:/Users/eid7/Documents/GitHub/alexnet-sbs/dataSet/parsed_test\")\n for i in range(training_iters):\n batch = feeder.next_batch()\n cur_input = []\n cur_label = []\n for item in batch:\n cur_label.append(item[0])\n cur_input.append(item[1].flatten())\n cur_input = np.array(cur_input)\n cur_label = np.array(cur_label)\n sess.run(train, feed_dict={x_input: cur_input, y_true: cur_label, keep_prob: dropout})\n # PRINT OUT A MESSAGE EVERY 100 STEPS\n print(i)\n print('Currently on step {}'.format(i))\n print('Accuracy is:')\n # Test the Train Model\n matches = tf.equal(tf.argmax(pred, 1), tf.argmax(y_true, 1))\n acc = tf.reduce_mean(tf.cast(matches, tf.float32))\n print(sess.run(acc, feed_dict={x_input: feeder.test_input, y_true: feeder.test_label, keep_prob: 1.0}))\n print('\\n')","sub_path":"src/chest_xray_tf/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"483164573","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n'''provides a simple stateless caching system for Kodi addons and plugins'''\n\nimport xbmcvfs, xbmcgui, xbmc, xbmcaddon\nimport datetime\nimport time\nimport sqlite3\ntry: from sqlite3 import dbapi2 as database\nexcept ImportError: from pysqlite2 import dbapi2 as database\nfrom functools import reduce\nfrom resources.lib.modules.utils import to_utf8\nfrom resources.lib.modules import settings\n# from resources.lib.modules.utils import logger\n\n__addon_id__ = 'plugin.video.fen'\n__addon__ = xbmcaddon.Addon(id=__addon_id__)\nprofile_dir = xbmc.translatePath(__addon__.getAddonInfo('profile'))\ntrakt_cache_file = xbmc.translatePath(\"%s/fen_trakt.db\" % profile_dir).decode('utf-8')\n\nwindow = xbmcgui.Window(10000)\n\n\nclass TraktCache(object):\n '''simple stateless caching system for Kodi'''\n _exit = False\n _auto_clean_interval = datetime.timedelta(hours=4)\n _win = None\n _busy_tasks = []\n _database = None\n\n def __init__(self):\n '''Initialize our caching class'''\n self._monitor = xbmc.Monitor()\n self.check_cleanup()\n\n def close(self):\n '''tell any tasks to stop immediately (as we can be called multithreaded) and cleanup objects'''\n self._exit = True\n # wait for all tasks to complete\n while self._busy_tasks:\n xbmc.sleep(25)\n del self._monitor\n self._log_msg(\"Closed\")\n\n def __del__(self):\n '''make sure close is called'''\n if not self._exit:\n self.close()\n\n def get(self, endpoint):\n '''\n get object from cache and return the results\n endpoint: the (unique) name of the cache object as reference\n '''\n cur_time = self._get_timestamp(datetime.datetime.now())\n result = None\n # 1: try memory cache first\n result = self._get_mem_cache(endpoint, cur_time)\n # 2: fallback to _database cache\n if result is None:\n result = self._get_db_cache(endpoint, cur_time)\n\n return result\n\n def set(self, endpoint, data, expiration=datetime.timedelta(days=30)):\n '''\n set data in cache\n '''\n task_name = \"set.%s\" % endpoint\n self._busy_tasks.append(task_name)\n expires = self._get_timestamp(datetime.datetime.now() + expiration)\n\n # memory cache: write to window property\n self._set_mem_cache(endpoint, expires, data)\n\n # db cache\n if not self._exit:\n self._set_db_cache(endpoint, expires, data)\n\n # remove this task from list\n self._busy_tasks.remove(task_name)\n\n def check_cleanup(self):\n '''check if cleanup is needed - public method, may be called by calling addon'''\n cur_time = datetime.datetime.now()\n lastexecuted = window.getProperty(\"fen_trakt.clean.lastexecuted\")\n if not lastexecuted:\n window.setProperty(\"fen_trakt.clean.lastexecuted\", repr(cur_time))\n elif (eval(lastexecuted) + self._auto_clean_interval) < cur_time:\n # cleanup needed...\n self._do_cleanup()\n\n def _get_mem_cache(self, endpoint, cur_time):\n '''\n get cache data from memory cache\n we use window properties because we need to be stateless\n '''\n result = None\n cachedata = window.getProperty(endpoint.encode(\"utf-8\"))\n if cachedata:\n cachedata = eval(cachedata)\n if cachedata[0] > cur_time:\n result = cachedata[1]\n return result\n\n def _set_mem_cache(self, endpoint, expires, data):\n '''\n window property cache as alternative for memory cache\n usefull for (stateless) plugins\n '''\n cachedata = (expires, data)\n cachedata_str = repr(cachedata).encode(\"utf-8\")\n window.setProperty(endpoint.encode(\"utf-8\"), cachedata_str)\n\n def _get_db_cache(self, endpoint, cur_time):\n '''get cache data from sqllite _database'''\n result = None\n query = \"SELECT expires, data FROM fen_trakt WHERE id = ?\"\n cache_data = self._execute_sql(query, (endpoint,))\n if cache_data:\n cache_data = cache_data.fetchone()\n if cache_data and cache_data[0] > cur_time:\n result = eval(cache_data[1])\n # also set result in memory cache for further access\n self._set_mem_cache(endpoint, cache_data[0], result)\n return result\n\n def _set_db_cache(self, endpoint, expires, data):\n ''' store cache data in _database '''\n query = \"INSERT OR REPLACE INTO fen_trakt(id, expires, data) VALUES (?, ?, ?)\"\n data = repr(data)\n self._execute_sql(query, (endpoint, expires, data))\n\n def _do_cleanup(self):\n '''perform cleanup task'''\n if self._exit or self._monitor.abortRequested():\n return\n self._busy_tasks.append(__name__)\n cur_time = datetime.datetime.now()\n cur_timestamp = self._get_timestamp(cur_time)\n self._log_msg(\"Running cleanup...\")\n if window.getProperty(\"fentraktcachecleanbusy\"):\n return\n window.setProperty(\"fentraktcachecleanbusy\", \"busy\")\n\n query = \"SELECT id, expires FROM fen_trakt\"\n for cache_data in self._execute_sql(query).fetchall():\n if self._exit or self._monitor.abortRequested():\n return\n # always cleanup all memory objects on each interval\n window.clearProperty(cache_data[0].encode(\"utf-8\"))\n # clean up db cache object only if expired\n if cache_data[1] < cur_timestamp:\n query = 'DELETE FROM fen_trakt WHERE id = ?'\n self._execute_sql(query, (cache_data[0],))\n self._log_msg(\"delete from db %s\" % cache_data[0])\n\n # compact db\n self._execute_sql(\"VACUUM\")\n\n # remove task from list\n self._busy_tasks.remove(__name__)\n window.setProperty(\"fen_trakt.clean.lastexecuted\", repr(cur_time))\n window.clearProperty(\"fentraktcachecleanbusy\")\n self._log_msg(\"Auto cleanup done\")\n\n def _get_database(self):\n '''get reference to our sqllite _database - performs basic integrity check'''\n if not xbmcvfs.exists(profile_dir):\n xbmcvfs.mkdirs(profile_dir)\n try:\n connection = sqlite3.connect(trakt_cache_file, timeout=30, isolation_level=None)\n connection.execute('SELECT * FROM fen_trakt LIMIT 1')\n return connection\n except Exception as error:\n # our _database is corrupt or doesn't exist yet, we simply try to recreate it\n if xbmcvfs.exists(trakt_cache_file):\n xbmcvfs.delete(trakt_cache_file)\n try:\n connection = sqlite3.connect(trakt_cache_file, timeout=30, isolation_level=None)\n connection.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS fen_trakt(\n id TEXT UNIQUE, expires INTEGER, data TEXT)\"\"\")\n return connection\n except Exception as error:\n self._log_msg(\"Exception while initializing _database: %s\" % str(error), xbmc.LOGWARNING)\n self.close()\n return None\n\n def _execute_sql(self, query, data=None):\n '''little wrapper around execute and executemany to just retry a db command if db is locked'''\n retries = 0\n result = None\n error = None\n with self._get_database() as _database:\n while not retries == 10:\n if self._exit:\n return None\n try:\n if isinstance(data, list):\n result = _database.executemany(query, data)\n elif data:\n result = _database.execute(query, data)\n else:\n result = _database.execute(query)\n return result\n except sqlite3.OperationalError as error:\n if \"_database is locked\" in error:\n self._log_msg(\"retrying DB commit...\")\n retries += 1\n self._monitor.waitForAbort(0.5)\n else:\n break\n except Exception as error:\n break\n self._log_msg(\"_database ERROR ! -- %s\" % str(error), xbmc.LOGWARNING)\n return None\n\n @staticmethod\n def _log_msg(msg, loglevel=xbmc.LOGDEBUG):\n '''helper to send a message to the kodi log'''\n if isinstance(msg, unicode):\n msg = msg.encode('utf-8')\n xbmc.log(\"Fen Trakt Cache --> %s\" % msg, level=loglevel)\n\n @staticmethod\n def _get_timestamp(date_time):\n '''Converts a datetime object to unix timestamp'''\n return int(time.mktime(date_time.timetuple()))\n\ndef cache_trakt_object(function, string, url):\n _cache = TraktCache()\n cache = _cache.get(string)\n if cache: return to_utf8(cache)\n result = function(url)\n _cache.set(string, result, expiration=datetime.timedelta(hours=settings.trakt_cache_duration()))\n return to_utf8(result)\n\ndef clear_trakt_watched_data(db_type, media_id=None):\n settings.check_database(trakt_cache_file)\n dbcon = database.connect(trakt_cache_file)\n dbcur = dbcon.cursor()\n if db_type == 'tvshow':\n clear_trakt_next_episode_data(media_id)\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id=?\", ('trakt_watched_shows',))\n dbcon.commit()\n window.clearProperty('trakt_watched_shows')\n action = 'trakt_indicators_movies' if db_type in ('movie', 'movies') else 'trakt_indicators_tv'\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id=?\", (action,))\n dbcon.commit()\n window.clearProperty(action)\n\ndef clear_trakt_next_episode_data(media_id=None):\n settings.check_database(trakt_cache_file)\n try:\n dbcon = database.connect(trakt_cache_file)\n dbcur = dbcon.cursor()\n dbcur.execute(\"SELECT * FROM fen_trakt WHERE id = ?\", ('trakt_watched_shows',))\n shows = dbcur.fetchone()[2]\n shows = eval(shows)\n show_ids = [i['show']['ids'] for i in shows]\n except: return\n if media_id:\n try:\n trakt_id = [i['trakt'] for i in show_ids if i['imdb'] == media_id][0]\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id=?\", ('trakt_view_history_%s' % str(trakt_id),))\n dbcon.commit()\n window.clearProperty('trakt_view_history_%s' % str(trakt_id))\n except: pass\n return\n if not media_id:\n trakt_ids = [i['trakt'] for i in show_ids]\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id LIKE 'trakt_view_history%'\")\n dbcon.commit()\n for i in trakt_ids: window.clearProperty('trakt_view_history_%s' % str(i))\n\ndef clear_trakt_hidden_data(list_type):\n settings.check_database(trakt_cache_file)\n action = 'trakt_hidden_items_%s' % list_type\n try:\n dbcon = database.connect(trakt_cache_file)\n dbcur = dbcon.cursor()\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id=?\", (action,))\n dbcon.commit()\n window.clearProperty(action)\n except: pass\n\ndef clear_trakt_collection_watchlist_data(list_type, db_type):\n settings.check_database(trakt_cache_file)\n action = 'trakt_collection_%s' % db_type if list_type == 'collection' else 'trakt_watchlist_%s' % db_type\n try:\n dbcon = database.connect(trakt_cache_file)\n dbcur = dbcon.cursor()\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id=?\", (action,))\n dbcon.commit()\n window.clearProperty(action)\n window.setProperty('trakt_reset_passed_list', 'true')\n except: pass\n\ndef clear_trakt_list_contents_data(clear_all=False, user=None, slug=None):\n from resources.lib.modules.trakt import get_trakt_my_lists, get_trakt_liked_lists\n settings.check_database(trakt_cache_file)\n if clear_all:\n my_lists = [(item[\"user\"][\"username\"], item[\"ids\"][\"slug\"]) for item in get_trakt_my_lists(build_list=False)]\n liked_lists = [(item[\"list\"][\"user\"][\"username\"], item[\"list\"][\"ids\"][\"slug\"]) for item in get_trakt_liked_lists(build_list=False)]\n my_lists.extend(liked_lists)\n try:\n dbcon = database.connect(trakt_cache_file)\n dbcur = dbcon.cursor()\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id LIKE 'trakt_list_contents%'\")\n dbcon.commit()\n except: pass\n for i in my_lists: window.clearProperty('trakt_list_contents_%s_%s' % (i[0], i[1]))\n else:\n action = 'trakt_list_contents_%s_%s' % (user, slug)\n try:\n dbcon = database.connect(trakt_cache_file)\n dbcur = dbcon.cursor()\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id=?\", (action,))\n dbcon.commit()\n window.clearProperty(action)\n window.setProperty('trakt_reset_passed_list', 'true')\n except: pass\n\ndef clear_trakt_list_data(list_type):\n settings.check_database(trakt_cache_file)\n action = 'trakt_my_lists' if list_type == 'my_lists' else 'trakt_liked_lists'\n try:\n dbcon = database.connect(trakt_cache_file)\n dbcur = dbcon.cursor()\n dbcur.execute(\"DELETE FROM fen_trakt WHERE id=?\", (action,))\n dbcon.commit()\n window.clearProperty(action)\n except: pass\n\ndef clear_all_trakt_cache_data(list_type='progress_watched'):\n try:\n if not xbmcgui.Dialog().yesno('Are you sure?','Fen will Clear the Trakt Cache.'):\n return False\n try: clear_trakt_hidden_data(list_type)\n except: pass\n for i in ('movie', 'tvshow'):\n try: clear_trakt_watched_data(i)\n except: pass\n for j in ('collection', 'watchlist'):\n try: clear_trakt_collection_watchlist_data(j, i)\n except: pass\n try: clear_trakt_list_contents_data(clear_all=True)\n except: pass\n for i in ('my_lists', 'liked_lists'):\n try: clear_trakt_list_data(i)\n except: pass\n return True\n except:\n return False\n","sub_path":"plugin.video.fen/resources/lib/modules/trakt_cache.py","file_name":"trakt_cache.py","file_ext":"py","file_size_in_byte":14146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"598493369","text":"import json\nfrom datetime import datetime, date, timedelta\nfrom dateutil.relativedelta import relativedelta\n\n\nclass LoanReturn ():\n\n def __init__(self, total_money, installments, year_rate):\n self.total_money = total_money\n self.installments = installments\n self.year_rate = year_rate\n\n # b保留两位小数的方法,(不四舍五入)\n def two(self, number):\n number = str (number)\n for i in range (0, len (number)):\n if number[i] == '.':\n number = number[0:i + 3]\n number = float (number)\n return number\n\n # 计算月利率并保留十位小数\n def cal_month_rate(self, year_rate):\n month_rate = str (year_rate / 12)\n month_rate = month_rate[0:12]\n month_rate = float (month_rate)\n return month_rate\n\n # 计算每月还款利息\n\n def interest_permon(self):\n month_rate = self.cal_month_rate (self.year_rate)\n # 每月应还款总额\n month_Income = self.total_money * (month_rate * (pow (1 + month_rate, self.installments))) / (\n pow (1 + month_rate, self.installments) - 1)\n month_Income = round (month_Income, 2)\n per_mon_interest = dict ()\n total = self.total_money\n for i in range (1, self.installments + 1):\n month_insteres = total * month_rate\n month_insteres2 = round (self.two (month_insteres), 2)\n total = total - (float (month_Income) - float (month_insteres2))\n per_mon_interest[i] = month_insteres2\n return per_mon_interest\n\n # 计算每月还款本金\n def principal_permon(self):\n month_rate = self.cal_month_rate (self.year_rate)\n # 每月还款总额\n month_Income = self.total_money * (month_rate * (pow (1 + month_rate, self.installments))) / (\n pow (1 + month_rate, self.installments) - 1)\n month_Income = round (month_Income, 2)\n # 获取每月的还款利息并存入字典\n month_interest = self.interest_permon ()\n per_mon_principal = dict ()\n total_principal = 0\n for i in range (1, self.installments + 1):\n principal = round (month_Income - float (month_interest[i]), 2)\n if i == self.installments:\n principal = round (self.total_money - total_principal, 2)\n total_principal = total_principal + principal\n per_mon_principal[i] = principal\n return per_mon_principal\n\n\n# 获取还款计划\nclass Get_Plan ():\n\n def __init__(self,\n productNo, # 产品号\n loanAmount, # 贷款金额\n installments, # 期数\n apr, # 利率\n standardFUpdatePlanEnums, # 修改还款计划\n updateInstallments # 修改第几期\n ):\n self.productNo = productNo\n self.loanAmount = loanAmount\n self.installments = installments\n self.apr = apr\n self.standardFUpdatePlanEnums = standardFUpdatePlanEnums\n self.updateInstallments = updateInstallments\n\n def return_plan(self):\n Loan = LoanReturn(self.loanAmount,self.installments,self.apr)\n #每期的本金\n Principal = Loan.principal_permon()\n #每期的利息\n Interest = Loan.interest_permon()\n\n if(self.standardFUpdatePlanEnums==\"principal\"):\n Principal[self.updateInstallments-1] = Principal[self.updateInstallments-1] + 0.01;\n\n interestStartDate = date.today ()\n\n for i in range(1,self.installments+1):\n dueMonth = interestStartDate + relativedelta (months=i)\n #当期的本金、利息\n\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n test1 = 1998\n test2 = 6\n test3 = 0.39\n Plan = Get_Plan('33A',1000,6,0.23,'test','none')\n Plan.return_plan()\n\n #json2 = json.dumps (Princal)\n\n","sub_path":"API1/Loanreturn.py","file_name":"Loanreturn.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"242086031","text":"import urllib.request\n\n\ndef wordCount(url, word):\n fp = urllib.request.urlopen(url)\n mybytes = fp.read()\n mystr = mybytes.decode(\"utf8\")\n fp.close()\n wordlower = word.lower()\n count = 0\n line = mystr.split()\n for each in line:\n wordline = each.lower()\n wordline = wordline.strip(\"!@#$%¨&*()_-+=?/.,<>:;{}[]\")\n if wordlower == wordline:\n count += 1\n return count\n","sub_path":"DesafioPontoTel/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"362464128","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 6 13:39:58 2021\r\n\r\n@author: siboc\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport scipy\r\nimport math\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom sklearn.metrics import r2_score\r\nimport tensorflow as tf\r\nimport keras.backend as K\r\n# check scikit-learn version\r\n\r\n# check scikit-learn version\r\nimport sklearn\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.datasets import make_regression\r\nfrom sklearn.neighbors import KNeighborsRegressor\r\nfrom sklearn.tree import DecisionTreeRegressor\r\nimport pandas as pd\r\n\r\ndef data_set_order(file):\r\n\ttrain_data = np.array(pd.read_csv(file))[:-2,:]\r\n\tr0=train_data[:,:1001][:,:201]\r\n\tr1=train_data[:,1001:2002][:,:201]\r\n\tr2=train_data[:,2002:3003][:,:201]\r\n\tr3=train_data[:,3003:]\r\n\tr3[:,-1]=r3[:,-1]/100\r\n\ttrain_data=np.insert(r0,[i+1 for i in range(r0.shape[1])],r1,axis=1)\r\n\ttrain_data=np.insert(train_data,[(i+1)*2 for i in range(int(train_data.shape[1]/2))],r2,axis=1)\r\n\ttrain_data=np.concatenate((train_data,r3),axis=1)\r\n\treturn train_data\r\n\r\n#input\r\ntrain_data = data_set_order('lorenz_cov_train_v2/trainset_withx_steps1000_1.csv')\r\nprint(\"train_data shape: \",train_data.shape)\r\n\r\n\r\n# train_data1 = data_set_order('lorenz_cov_train/trainset_withx_repeat10bis3.csv')\r\n# print(\"train_data1 shape: \",train_data1.shape)\r\n\r\n# train_data2 = data_set_order('lorenz_cov_train/trainset_withx_repeat10bis4.csv')\r\n# print(\"train_data2 shape: \",train_data2.shape)\r\n\r\n# train_data3 = data_set_order('lorenz_cov_train/trainset_withx_repeat10bis5.csv')\r\n# print(\"train_data3 shape: \",train_data3.shape)\r\n\r\n# train_data4 = data_set_order('lorenz_cov_train/trainset_withx_repeat10bis6.csv')\r\n# print(\"train_data4 shape: \",train_data4.shape)\r\n\r\n# train_data5 = data_set_order('lorenz_cov_train/trainset_withx_repeat10bis7.csv')\r\n# print(\"train_data5 shape: \",train_data5.shape)\r\n\r\n# train_data6 = data_set_order('lorenz_cov_train/trainset_withx_repeat10bis8.csv')\r\n# print(\"train_data6 shape: \",train_data6.shape)\r\n\r\n#size: num_steps*3,r1,r2,r3,v\r\n\r\n\r\n#########################################################################################\r\n\r\n#train_data = np.array(pd.read_csv('data_1000steps/trainset_withx_1000steps.csv'))\r\n#\r\n#\r\n#train_data1 = np.array(pd.read_csv('data_1000steps/trainset_withx_1000stepsbis1.csv'))\r\n#\r\n#train_data2 = np.array(pd.read_csv('data_1000steps/trainset_withx_1000stepsbis2.csv'))\r\n#\r\n#train_data3 = np.array(pd.read_csv('data_1000steps/trainset_withx_1000stepsbis3.csv'))\r\n\r\n\r\n\r\n\r\n\r\n# train_data = np.concatenate((train_data6,train_data5),axis = 0)\r\n\r\n# train_data = np.concatenate((train_data,train_data4),axis = 0)\r\n\r\n# train_data = np.concatenate((train_data,train_data3),axis = 0)\r\n\r\n# train_data = np.concatenate((train_data,train_data2),axis = 0)\r\n\r\n# train_data = np.concatenate((train_data,train_data1),axis = 0)\r\n\r\n# train_data = np.concatenate((train_data,train_data0),axis = 0)\r\n\r\n# train_data=train_data[:120000,:]\r\n\r\n\r\n#weightstrain_data[:,604:]\r\nnp.random.shuffle(train_data )\r\n\r\ninput_data = train_data[:,0:603]\r\noutput_data = train_data[:,603:]\r\n\r\n\r\n\r\n########################################################################\r\ntrain_part = 0.97\r\n\r\nthreshold = int(train_part*train_data.shape[0])\r\n\r\n\r\n##########################################################################\r\n\r\ntrain_input = input_data[:threshold]\r\n\r\nprint(\"input_data shape: \",input_data.shape)\r\n\r\ntrain_output = output_data[:threshold]\r\n\r\nprint(\"output_data shape: \",output_data.shape)\r\n\r\n\r\ntest_input = input_data [threshold:]\r\n\r\ntrue_test_output = output_data[threshold:]\r\n\r\n\r\n\r\nX1 = train_input\r\nY1 = train_output\r\n\r\nX2 = test_input\r\n#Y2 = ValidationSet_Y\r\n\r\n############################################################################\r\n\r\n\r\n\r\n#def my_loss_fn(y_true, y_pred):\r\n# \r\n# return K.mean(K.abs(y_true - y_pred) * weight)\r\n\r\n# ========================================================================================\r\nfrom keras.layers import LSTM,Dropout\r\nfrom keras.layers import TimeDistributed\r\nfrom keras.callbacks import EarlyStopping\r\nfrom keras.callbacks import ModelCheckpoint\r\nfrom keras.optimizers import Adam\r\n\r\n\r\n\r\n\r\n# save data\r\nimport os\r\nimport json\r\nimport pickle\r\n\r\nif not os.path.isdir('save_data_v2'):\r\n\tos.makedirs('save_data_v2')\r\n\r\nhidden_size=200\r\n\r\ninput_sample=input_data.shape[0] #for one sample\r\n\r\n\r\noutput_sample=output_data.shape[0]\r\n\r\ninput_data=input_data.reshape(input_sample,201,3) #201 is the time steps in data_generation\r\noutput_data=output_data.reshape(output_sample,4)\r\n\r\nuse_dropout=True\r\nmodel = Sequential()\r\nmodel.add(LSTM(hidden_size,input_shape=(201,3)))\r\n\r\nmodel.add(Dense(4))\r\n# opt = Adam(lr=0.0001)\r\nmodel.compile(loss='mean_squared_error', optimizer='Adam', metrics=['mae'])\r\nprint(model.summary())\r\n\r\nes=EarlyStopping(monitor='val_loss',mode='min',verbose=1,patience=50)\r\n# modelcheckpoint\r\nmc=ModelCheckpoint('save_data_v2/sequentiallstm200_ing.h5',monitor='val_loss',mode='min',save_best_only=True,verbose=1)\r\n\r\nhistory=model.fit(input_data, output_data, validation_split=0.1, epochs=100, batch_size=128, verbose=1,callbacks=[es,mc])\r\n\r\n\r\n\r\n\r\n# model.save('save_data/sequentiallstm2')\r\nmodel.save('save_data_v2/sequentiallstm200_ing_f.h5')\r\n\r\n# https://stackoverflow.com/a/44674337/10349608\r\nwith open('save_data_v2/sequentiallstm200_ing_history.pickle', 'wb') as file_his:\r\n\tpickle.dump(history.history, file_his)\r\n\r\n\r\n# Calculate predictions\r\nPredTestSet = model.predict(X1.reshape(X1.shape[0],201,3))\r\nPredValSet = model.predict(X2.reshape(X2.shape[0],201,3))\r\n\r\n\r\n\r\n\r\nplt.plot(history.history['loss'])\r\nplt.plot(history.history['val_loss'])\r\nplt.title('Model loss')\r\nplt.ylabel('Loss')\r\nplt.xlabel('Epoch')\r\nplt.legend(['Train', 'Test'], loc='upper left')\r\n#plt.savefig('figure_dp/loss_trace.eps', format='eps',bbox_inches='tight')\r\nplt.show()\r\n\r\n\r\n\r\nplt.plot(PredValSet[:,2],true_test_output[:,2],'o', color='blue',markersize=5)\r\n#plt.plot(list(range(0,1,0.1)),list(range(0,1,0.1)),'k')\r\nplt.show()\r\n\r\nplt.plot(PredValSet[:,3],true_test_output[:,3],'o',color='blue',markersize=5)\r\n#plt.plot(list(range(0,1,0.1)),list(range(0,1,0.1)),'k')\r\nplt.show()\r\n\r\n\r\n\r\n# predint = model.predict(train_input[:3000])\r\n\r\n# trueint = train_output[:3000]\r\n\r\n\r\n# plt.plot(predint[:,3],trueint[:,3],'o', color='blue',markersize=5)\r\n# #plt.plot(list(range(0,1,0.1)),list(range(0,1,0.1)),'k')\r\n# plt.show()\r\n\r\n","sub_path":"lorenz/lorenz_lstm200.py","file_name":"lorenz_lstm200.py","file_ext":"py","file_size_in_byte":6433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"174486455","text":"# -*- python -*-\nimport ConfigParser\nimport errno\nimport io\nimport logging\nimport os\nimport sys\nimport re\nimport fileutils\nimport SCons.Node.FS\nimport SCons.Util\nfrom SCons.Script import Mkdir, Chmod, Copy, WhereIs\nimport shutil\nimport state\n\nsrc_dir = Dir('.').srcnode().abspath\nstate.init(src_dir)\nenv = state.env\n\n#########################\n#\n# Defining dependencies\n#\n#########################\n\nenv.Default(env.Alias(\"build\"))\nenv.Depends(\"build\", env.Alias(\"init-build-env\"))\nenv.Depends(\"install\", env.Alias(\"build\"))\n\nenv.Depends(\"python-tests\", env.Alias(\"init-build-env\"))\nenv.Requires(env.Alias('python-tests'), env.Alias('admin'))\nenv.Requires(env.Alias('python-tests'), env.Alias('dist-css'))\n\nenv.Alias(\"install\",\n [\n env.Alias(\"dist-core\"),\n env.Alias(\"dist-css\"),\n env.Alias(\"admin\"),\n env.Alias(\"python-tests\"),\n env.Alias(\"templates\")\n ]\n)\n\n################################\n#\n# Build documentation \n#\n################################\ndoc = env.Command(\"build-doc\", [], \"cd doc && PATH={0} bash build.sh\".format(os.getenv(\"PATH\")))\nenv.Alias(\"doc\", doc)\n\n# documentation generation must be possible even if build\n# environment isn't available\nif ['doc'] == COMMAND_LINE_TARGETS:\n state.log.debug(\"Only building Qserv documentation\") \n\nelse:\n################################\n#\n# Init build environment \n#\n################################\n state.initBuild()\n\n################################\n#\n# Install tests python modules\n#\n################################\n python_tests = env.InstallPythonModule(target=env['python_prefix'], source=os.path.join(\"tests\", \"python\"))\n env.Alias(\"python-tests\", python_tests)\n\n#########################\n#\n# Install css\n#\n#########################\n cssbin_target = os.path.join(env['prefix'], \"bin\")\n env.RecursiveInstall(cssbin_target, os.path.join(\"css\", \"bin\"))\n python_css = env.InstallPythonModule(\n target=env['python_prefix'],\n source=os.path.join(\"css\", \"python\")\n )\n env.Alias(\"dist-css\",\n [\n python_css,\n cssbin_target\n ]\n )\n\n#########################\n#\n# Install admin commands\n#\n#########################\n adminbin_target = os.path.join(env['prefix'], \"bin\")\n env.RecursiveInstall(adminbin_target, os.path.join(\"admin\", \"bin\"))\n env.RecursiveInstall(adminbin_target, os.path.join(\"tests\", \"bin\"))\n python_admin = env.InstallPythonModule(target=env['python_prefix'], source=os.path.join(\"admin\", \"python\"))\n\n template_target = os.path.join(env['prefix'], \"admin\", \"templates\")\n env.RecursiveInstall(template_target, os.path.join(\"admin\", \"templates\"))\n\n env.Alias(\"admin\",\n [\n python_admin,\n template_target,\n adminbin_target,\n ]\n)\n\n#############################\n#\n# Install Qserv code\n#\n#############################\n\n# Trigger the modules build\n############################\n\n# computing install target paths\n#################################\n def get_install_targets() :\n\n # Setup the #include paths\n # env.Append(CPPPATH=\"modules\")\n\n (coreFilesToInstall, testTargets) = SConscript('core/modules/SConscript',\n variant_dir=env['build_dir'],\n duplicate=1,\n exports=['env', 'ARGUMENTS']\n )\n targetFiles = []\n for (path, sourceNode) in coreFilesToInstall :\n installPath=os.path.join(env['prefix'], path)\n state.log.debug(\"%s %s\" % (installPath, sourceNode))\n targetFile = fileutils.replace_base_path(None, installPath, sourceNode, env)\n env.InstallAs(targetFile, sourceNode)\n targetFiles.append(targetFile)\n\n installTargets = targetFiles + testTargets\n state.log.debug(\"%s \" % installTargets)\n\n return installTargets\n\n env.Alias(\"dist-core\", get_install_targets())\n\n#########################################\n#\n# Templates :\n# - fill user configuration file\n# - alias for Qserv start/stop commands\n#\n#########################################\n\n def get_template_targets():\n\n template_dir_path= os.path.join(\"admin\",\"templates\", \"install\")\n target_lst = []\n\n state.log.info(\"Applying configuration information via templates files \")\n\n script_dict = {\n '{{QSERV_DIR}}': env['prefix'],\n '{{XROOTD_DIR}}': env['XROOTD_DIR'],\n '{{LUA_DIR}}': env['LUA_DIR'],\n '{{MYSQL_DIR}}': env['MYSQL_DIR'],\n '{{MYSQLPROXY_DIR}}': env['MYSQLPROXY_DIR']\n }\n\n for src_node in fileutils.recursive_glob(template_dir_path, \"*\", env):\n\n target_node = fileutils.replace_base_path(template_dir_path, env['prefix'], src_node,env)\n\n if isinstance(src_node, SCons.Node.FS.File) :\n\n state.log.debug(\"Template SOURCE : %s, TARGET : %s\" % (src_node, target_node))\n env.Substfile(target_node, src_node, SUBST_DICT=script_dict)\n target_lst.append(target_node)\n\n return target_lst\n\n env.Alias(\"templates\", get_template_targets())\n\n# List all aliases\ntry:\n from SCons.Node.Alias import default_ans\nexcept ImportError:\n pass\nelse:\n aliases = default_ans.keys()\n aliases.sort()\n env.Help('\\n')\n env.Help('Recognized targets:\\n')\n for alias in aliases:\n env.Help(' %s\\n' % alias)\n\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"421770097","text":"Desc = cellDescClass(\"CLKBUFX16\")\nDesc.properties[\"cell_leakage_power\"] = \"5029.443900\"\nDesc.properties[\"cell_footprint\"] = \"clkbuf\"\nDesc.properties[\"area\"] = \"63.201600\"\nDesc.pinOrder = ['A', 'Y']\nDesc.add_arc(\"A\",\"Y\",\"combi\")\nDesc.set_job(\"buf\") # A\nDesc.add_param(\"area\",63.201600);\nDesc.add_pin(\"A\",\"input\")\nDesc.add_pin(\"Y\",\"output\")\nDesc.add_pin_func(\"Y\",\"unknown\")\nCellLib[\"CLKBUFX16\"]=Desc\n","sub_path":"synlib/descriptions/CLKBUFX16.py","file_name":"CLKBUFX16.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"275576555","text":"from django.shortcuts import render,get_object_or_404,redirect \nfrom .models import Post \nfrom .forms import PostForm\n#from django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\ndef post_list(request):\n\tposts = Post.objects.filter(published_date__isnull=False).order_by('published_date')\n\treturn render(request,'blog/post_list.html',{'posts':posts})\n\ndef post_detail(request,pk):\n\tpost = get_object_or_404(Post, pk=pk)\n\treturn render(request, 'blog/post_detail.html',{'post':post})\n\n@login_required\ndef post_edit(request,pk):\n\tpost = get_object_or_404(Post, pk=pk)\n\tif request.method == \"POST\": \n\t\tform = PostForm(request.POST,instance=post)\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\t\t\t\n\t\t\tme = User.objects.get(username='root')\n\t\t\tpost.author = request.user()\n\t\t\tpost.save()\n\t\t\treturn redirect('blog.views.post_detail',pk=post.pk)\n\telse:\n\t\tform = PostForm(instance=post)\n\treturn render(request,'blog/post_edit.html',{'form':form})\n\n@login_required\ndef post_new(request):\n\tif request.method == \"POST\":\n\t\tform = PostForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tpost = form.save(commit=False)\n\t\t\tme = User.objects.get(username='root')\n\t\t\tpost.author = request.user()\n\t\t\tpost.save()\n\t\t\treturn redirect('blog.views.post_detail',pk=post.pk)\n\telse :\n\t\tform = PostForm()\n \n\treturn render(request, 'blog/post_edit.html',{'form':form})\n","sub_path":"static/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"45749390","text":"\"\"\" Skyline: puzzle game\n\nGrid puzzle with clues.\nPlayer has to fill the grid in a sodoku style.\nMultiple solutions possible.\n\n\"\"\"\n\nimport itertools\nimport random\ntry:\n import tkinter as tk\nexcept ImportError:\n try:\n import Tkinter as tk\n except ImportError:\n input(\"Failed to load tkinter, aborting...\")\n\n__author__ = \"6057374: Vincent Kühn, 6192860: Georg Schuhardt\"\n__copyright__ = \"Copyright 2015/2016 – EPR-Goethe-Uni\"\n__credits__ = \"none this time\"\n__email__ = \"georg.schuhardt@gmail.com\"\n__github__ = \"https://github.com/banur/EPR1_SuperBrain\"\n\n\nclass Skyline(tk.Frame):\n\n \"\"\" Skyline puzzle game. \"\"\"\n\n __boardsize = 0\n __skyline = []\n __hints = []\n __solved_grid = []\n __solved = 0\n __entry_fields = []\n __input_list = []\n\n def __init__(self, boardsize=4, master=None):\n \"\"\" Initialise the game. \"\"\"\n tk.Frame.__init__(self, master)\n self.__boardsize = boardsize\n self.grid()\n self.__start_game()\n\n def __start_game(self):\n \"\"\" Setup the games subroutines. \"\"\"\n self.__generate_skyline()\n self.__hints = self.__generate_hints()\n self.__generate_empty_board()\n self.__build_ui()\n\n def __generate_skyline(self):\n \"\"\" Generate a possible solution by choosing from permutations. \"\"\"\n boardsize = self.__boardsize\n street = []\n for i in range(1, boardsize + 1):\n street.append(i)\n perm_list = list(itertools.permutations(street, boardsize))\n for rows in range(boardsize):\n street = random.choice(perm_list)\n perm_list.remove(street)\n removal_list = []\n for house in range(len(street)):\n for available_streets in perm_list:\n if street[house] == available_streets[house]:\n removal_list.append(available_streets)\n for remove_street in removal_list:\n try:\n perm_list.remove(remove_street)\n except:\n pass\n self.__skyline.append(street)\n\n def __generate_hints(self, skyline=None):\n \"\"\" Generate the hints for the code, return as list. \"\"\"\n hints = []\n if skyline is None:\n skyline = self.__skyline\n for orientation in (\"down\", \"up\", \"to_right\", \"to_left\"):\n if orientation == \"to_left\" or orientation == \"to_right\":\n hints.append([])\n for row in skyline:\n if orientation == \"to_right\":\n condition_range = [0, range(len(row))]\n elif orientation == \"to_left\":\n condition_range = [-1, range(len(row) - 1, -1, -1)]\n visible_houses = 1\n highest_visible = row[condition_range[0]]\n for house in condition_range[1]:\n if highest_visible < row[house]:\n visible_houses += 1\n highest_visible = row[house]\n hints[-1].append(visible_houses)\n if orientation == \"up\" or orientation == \"down\":\n hints.append([])\n for column in range(len(skyline)):\n if orientation == \"down\":\n condition_range = [0, range(len(skyline))]\n elif orientation == \"up\":\n condition_range = [-1, range(len(skyline) - 1, -1, -1)]\n visible_houses = 1\n highest_visible = skyline[condition_range[0]][column]\n for house in condition_range[1]:\n if highest_visible < skyline[house][column]:\n visible_houses += 1\n highest_visible = skyline[house][column]\n hints[-1].append(visible_houses)\n return hints\n\n def __compare_grid(self):\n \"\"\" Compare the users input, call victory popup. \"\"\"\n is_filled = False\n for bracket in self.__solved_grid:\n if 0 not in bracket:\n is_filled = True\n else:\n is_filled = False\n if is_filled:\n user_code = self.__generate_hints(self.__solved_grid)\n if user_code == self.__hints:\n self.__quit_game()\n\n def __quit_game(self):\n \"\"\" Display victory popup and exit prompt. \"\"\"\n top = tk.Toplevel()\n top.title(\"Victory!\")\n msg = \"You found a right solution.\"\n top_frame = tk.Frame(top)\n top_frame.grid()\n top.geometry(\"+360+360\")\n popup_label = tk.Label(top_frame, text=msg)\n popup_label.grid(columnspan=2)\n exit_button = tk.Button(top_frame, text=\"Exit\", command=self.quit)\n exit_button.grid(row=1, column=1)\n\n def __user_input(self):\n \"\"\" Save the users input to list and compare to the skyline. \"\"\"\n for item in range(len(self.__input_list)):\n row = item // self.__boardsize\n column = item % self.__boardsize\n try:\n input_item = self.__input_list[item].get()\n except AttributeError:\n pass\n if input_item.isdigit():\n if input_item == \"1337\":\n self.__solved_grid = list(self.__skyline)\n break\n else:\n self.__solved_grid[row][column] = int(input_item)\n self.__compare_grid()\n\n def __generate_empty_board(self):\n \"\"\" Generate an empty board. \"\"\"\n for i in range(self.__boardsize):\n self.__solved_grid.append([])\n for i in range(self.__boardsize):\n self.__solved_grid[-1].append(0)\n self.__input_list.append([])\n\n def __create_entry_fields(self):\n \"\"\" Create entry fields based on the boardsize. \"\"\"\n for i in range(self.__boardsize**2):\n string_var = self.__input_list[i] = tk.StringVar()\n row = i // self.__boardsize + 1\n column = i % self.__boardsize + 1\n string_var.trace(\"w\", lambda name, index, mode,\n string_var=string_var: self.__user_input())\n new_entry = tk.Entry(self.master, width=5, textvariable=string_var)\n new_entry.grid(row=row, column=column)\n self.__entry_fields.insert(0, i)\n\n def __create_labels(self):\n \"\"\" Create labels based on the boardsize and fill with hints. \"\"\"\n hints = self.__hints\n for i in range(1, self.__boardsize + 1):\n new_label_top = tk.Label(self.master, text=hints[0][i - 1])\n new_label_top.grid(row=0, column=i)\n new_label_bot = tk.Label(self.master, text=hints[1][i - 1])\n new_label_bot.grid(row=self.__boardsize + 1, column=i)\n new_label_left = tk.Label(self.master, text=hints[2][i - 1])\n new_label_left.grid(row=i, column=0)\n new_label_right = tk.Label(self.master, text=hints[3][i - 1])\n new_label_right.grid(row=i, column=self.__boardsize + 1)\n\n def __build_ui(self):\n \"\"\" Generate the users UI, start GUI loop. \"\"\"\n self.master.title('Skyline')\n self.master.geometry(\"+300+300\")\n quit_buttton = tk.Button(None, text=\"quit\", command=self.quit)\n quit_buttton.grid(row=1000, column=1000)\n info_text = \"Fill the grid with unique digits from 1 to {0}.\".format(\n self.__boardsize)\n info_label = tk.Label(None, text=info_text)\n info_label.grid(row=1000, columnspan=6)\n self.__create_entry_fields()\n self.__create_labels()\n self.mainloop()\n\nnew_game = Skyline()\n","sub_path":"skyline.py","file_name":"skyline.py","file_ext":"py","file_size_in_byte":7737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"549218788","text":"\"\"\"\nCopyright (c) 2020, All Rights Reserved, http://www.pyxll.com/\n\nTHIS CODE AND INFORMATION ARE PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY\nKIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A\nPARTICULAR PURPOSE.\n\"\"\"\nfrom ._errors import Help, Error\nfrom ._cert import _install_certificate\nfrom ._utils import (\n AutoDeleteFile,\n AutoDeleteFolder,\n _print,\n _input,\n _find_excel_version_info,\n _get_latest_pyxll_version,\n _compare_pyxll_versions,\n _find_excel_path,\n _get_exe_bitness,\n _get_dll_bitness,\n _check_excel_is_not_running,\n _check_python_exe,\n _find_pyxll_addin,\n _get_xll_version_info,\n _get_xll_file_version,\n _download_pyxll,\n _unzip_pyxll,\n _backup_files,\n _clear_zone_identifier\n)\nimport platform\nimport tempfile\nimport logging\nimport shutil\nimport glob\nimport sys\nimport os\n\n_log = logging.getLogger(__name__)\n\ndef update(*args):\n pyxll_version = None\n pyxll_download_path = None\n force = False\n\n auto_delete_files = []\n unexpected_args = []\n args = list(args)\n while args:\n arg = args.pop(0)\n value = None\n if \"=\" in arg:\n arg, value = arg.split(\"=\", 1)\n value = value[0].strip(\"\\'\\\"\") if value else None\n if arg == \"--version\":\n if not value and args and not args[0].startswith(\"-\"):\n value = args.pop(0)\n if not value:\n raise Help(\"No version specified with --version option\")\n pyxll_version = value\n elif arg == \"--force\":\n force = True\n else:\n unexpected_args.append(arg)\n\n if len(unexpected_args) == 1:\n pyxll_download_path = unexpected_args.pop(0)\n if not os.path.exists(pyxll_download_path):\n raise Error(\"Path '%s' not found.\" % pyxll_download_path)\n\n if pyxll_version:\n raise Error(\"Use --version or a filename, not both.\")\n\n if unexpected_args:\n raise Help(\"Unexpected arguments '%s' to command 'update'.\" % \", \".join(unexpected_args))\n\n _check_python_exe()\n _check_excel_is_not_running()\n\n # Check Excel is installed and exists\n excel_exe = _find_excel_path()\n if not excel_exe:\n raise Error((\"Excel does not appear to be installed.\\n\\n\"\n \"Please ensure that Excel is installed correctly and try again.\"))\n\n bits = platform.architecture()[0]\n xl_version_info = _find_excel_version_info(bits)\n if xl_version_info is None:\n raise Error((\"Excel does not appear to be installed.\\n\\n\"\n \"Please ensure that Excel is installed correctly and try again.\"))\n\n xl_version, root_hkey, subkey, flags = xl_version_info\n print((\"Found Excel %s installed\" % xl_version))\n\n # Check PyXLL is already installed\n pyxll_path = _find_pyxll_addin(root_hkey, subkey, flags)\n if not pyxll_path or not os.path.exists(pyxll_path):\n raise Error((\"No existing install of PyXLL was found.\\n\\n\"\n \"Please use the 'pyxll install' to install PyXLL instead.\"))\n\n # Get the existing version info and check if there is a new version available\n latest_version = _get_latest_pyxll_version()\n installed_version = _get_xll_file_version(pyxll_path)\n version_info = _get_xll_version_info(pyxll_path)\n if version_info is not None:\n _, installed_version, _ = version_info\n\n if pyxll_version is None and pyxll_download_path is None and not force:\n if _compare_pyxll_versions(installed_version, latest_version) >= 0:\n raise Error(\"PyXLL %s is already installed and no newer version was found.\" % installed_version)\n\n _print(\"\\nPyXLL is installed in '%s'.\" % os.path.dirname(pyxll_path))\n _print(\"\\nYour existing PyXLL add-in will be backed up before updating to PyXLL %s.\" %\n str(pyxll_version if pyxll_version else latest_version))\n _print(\"\\nYour existing pyxll.cfg file will *not* be changed and any new \"\n \"examples will not be installed.\")\n _print(\"\\nIf you want to try out a new version before updating use 'pyxll install' \"\n \"and install PyXLL into a different folder than your current installation.\")\n\n # Check the bitness of Excel matches Python\n excel_bits = _get_exe_bitness(excel_exe)\n python_bits = _get_exe_bitness(sys.executable)\n if python_bits != excel_bits:\n raise Error((\"Excel is %(excel_bits)s but Python is %(python_bits)s.\\n\\n\"\n \"Please check the version of Office you have installed and either install \"\n \"the %(python_bits)s version of Excel or install a %(excel_bits)s version of Python.\")\n % {\"excel_bits\": excel_bits, \"python_bits\": python_bits})\n\n # Find or download PyXLL\n pyxll_install_path = os.path.dirname(pyxll_path)\n\n # Look for pyxll in the current directory (if it's not the folder PyXLL is installed in)\n if not pyxll_download_path:\n cwd = os.getcwd()\n if os.path.normpath(pyxll_install_path) != os.path.normpath(cwd) \\\n and os.path.exists(os.path.join(cwd, \"pyxll.xll\")):\n response = None\n _print(\"\\nA PyXLL add-in was found in the current folder.\")\n while response not in (\"y\", \"n\"):\n response = _input(\"Do you want to update your install of PyXLL to use the pyxll.xll found \"\n \"in the current folder ([y]/n)? \").strip().lower()\n if not response:\n response = \"y\"\n if response == \"y\":\n pyxll_download_path = cwd\n\n # If not found prompt the user for another path\n if not pyxll_download_path:\n _print(\"\")\n response = None\n while response not in (\"y\", \"n\"):\n response = _input(\"Have you already downloaded the new version of the PyXLL add-in you \"\n \"want to update to (y/[n])? \").strip().lower()\n if not response:\n response = \"n\"\n\n if response == \"y\":\n _print(\"\")\n while True:\n pyxll_download_path = _input(\"Enter the path of new PyXLL version you downloaded: \", is_path=True).strip()\n if not pyxll_download_path:\n continue\n\n if not os.path.exists(pyxll_download_path):\n _print(\"\\nThe path entered does not exist. Please try again.\\n\\n\")\n continue\n\n # Use the absolute path\n pyxll_download_path = os.path.abspath(pyxll_download_path)\n\n if os.path.isfile(pyxll_download_path):\n if os.path.basename(pyxll_download_path).lower() == \"pyxll.xll\":\n # Update to the pyxll.xll file found in this folder\n pyxll_download_path = os.path.dirname(pyxll_download_path)\n if os.path.normpath(pyxll_download_path) == os.path.normpath(pyxll_install_path):\n _print(\"\\nThe path you entered for the downloaded new version is the same as where PyXLL \"\n \"is currently installed.\\n\\n\")\n continue\n break\n\n _, ext = os.path.splitext(pyxll_download_path)\n if ext.lower() == \".zip\":\n break\n\n _print(\"\\nThe downloaded file should be a zip file. Please try again.\\n\\n\")\n continue\n\n elif os.path.isdir(pyxll_download_path):\n if os.path.normpath(pyxll_download_path) == os.path.normpath(pyxll_install_path):\n _print(\"\\nThe path you entered for the downloaded new version is the same as where PyXLL \"\n \"is currently installed.\\n\\n\")\n continue\n if not os.path.exists(os.path.join(pyxll_download_path, \"pyxll.xll\")):\n _print(\"\\npyxll.xll is missing from the folder specified. Please try again.\\n\\n\")\n continue\n else:\n break\n\n # If the user doesn't already have PyXLL then download it\n if not pyxll_download_path:\n pyxll_download_path, pyxll_version = _download_pyxll(python_bits, pyxll_version)\n auto_delete_files.append(AutoDeleteFile(pyxll_download_path))\n\n # Check we're not trying to use the installed version to update from\n if os.path.normpath(pyxll_download_path) == os.path.normpath(pyxll_install_path):\n raise Error((\"The PyXLL add-in '%s' is already installed. Please try again and \"\n \"choose the path of the new version of PyXLL you wish to update to.\") % pyxll_path)\n\n # Unzip the download into the install path if necessary\n if os.path.isdir(pyxll_download_path):\n pyxll_unzipped_path = pyxll_download_path\n elif os.path.basename(pyxll_download_path) == \"pyxll.xll\":\n pyxll_unzipped_path = os.path.dirname(pyxll_download_path)\n else:\n pyxll_unzipped_path = tempfile.mkdtemp()\n auto_delete_files.append(AutoDeleteFolder(pyxll_unzipped_path))\n _unzip_pyxll(pyxll_download_path, pyxll_unzipped_path)\n\n # Check the pyxll.xll file exists\n pyxll_xll_path = os.path.join(pyxll_unzipped_path, \"pyxll.xll\")\n if not os.path.exists(pyxll_xll_path):\n raise Error(\"Couldn't find pyxll.xll file in '%s'\" % pyxll_unzipped_path)\n\n # Check the installed version of PyXLL is the correct bitness\n pyxll_bits = _get_dll_bitness(pyxll_xll_path)\n if pyxll_bits != python_bits:\n raise Error((\"Excel and Python are %(excel_bits)s but the downloaded PyXLL add-in is %(pyxll_bits)s.\\n\\n\"\n \"You should download the %(excel_bits)s version of PyXLL and install that, or \"\n \"you can use the following command to re-install PyXLL:\\n\\n\"\n \"pyxll install\\n\\n\"\n \"See the PyXLL website https://www.pyxll.com for detailed installation instructions.\")\n % {\"excel_bits\": excel_bits, \"python_bits\": python_bits, \"pyxll_bits\": pyxll_bits})\n\n # Check the PyXLL version matches our Python version\n version_info = _get_xll_version_info(pyxll_xll_path)\n unzipped_version = _get_xll_file_version(pyxll_xll_path)\n\n # Older PyXLL add-ins do not have version information we can extract\n if version_info is not None:\n name, unzipped_version, py_version = version_info\n if py_version != \"py%d%d\" % sys.version_info[:2]:\n raise Error((\"The downloaded PyXLL add-in is for a different version of Python.\\n\\n\"\n \"The PyXLL add-in downloaded is for Python %(pyxll_py_version)s but the actual Python \"\n \"interpreter in use is Python %(py_version)s.\\n\\n\" +\n \"You will need to download the correct version of PyXLL, or change the version \"\n \"of Python you are using.\\n\\n\"\n \"You can re-install PyXLL by running:\\n\\n\"\n \"pyxll install\\n\\n\"\n \"or see the PyXLL website https://www.pyxll.com for installation instructions.\") % {\n \"py_version\": \"%d.%d\" % sys.version_info[:2],\n \"pyxll_py_version\": \"%s.%s\" % (py_version[2:3], py_version[3:])})\n\n if pyxll_version is not None \\\n and unzipped_version != pyxll_version:\n raise Error((\"PyXLL version '%s' was requested but version '%s' was found.\" % (\n pyxll_version, unzipped_version)) +\n (\"\\nPlease check the version and try again.\"))\n\n if not force:\n _print(\"\")\n response = None\n while response not in (\"y\", \"n\"):\n response = _input(\"Do you want to update PyXLL from %s to %s ([y]/n)? \" % (\n installed_version or \"\", unzipped_version or \"\")).lower()\n if not response:\n response = \"y\"\n if response != \"y\":\n return 1\n\n # Backup the previous files and copy over the new ones\n whl_files = [os.path.basename(x) for x in glob.glob(os.path.join(pyxll_unzipped_path, \"pyxll-*.whl\"))]\n files_to_copy = [\n \"pyxll.xll\",\n \"readme.pdf\",\n \"license-agreement.pdf\",\n ] + whl_files\n\n unchanged = _backup_files(pyxll_unzipped_path, pyxll_install_path, files_to_copy)\n\n for filename in files_to_copy:\n if filename in unchanged:\n continue\n if os.path.exists(os.path.join(pyxll_unzipped_path, filename)):\n shutil.copyfile(os.path.join(pyxll_unzipped_path, filename),\n os.path.join(pyxll_install_path, filename))\n\n # Unblock the file if it is blocked\n _clear_zone_identifier(pyxll_xll_path)\n\n # Try installing the certificate\n try:\n _install_certificate()\n except Exception:\n _log.warning(\"Unable to install the Trusted Publisher certificate.\",\n exc_info=_log.getEffectiveLevel() <= logging.DEBUG)\n _log.warning(\"If Excel cannot load the PyXLL add-in check your Trust Center Settings in Options in Excel.\")\n\n _print(\"\\n\")\n _print(\"-\" * 79)\n _print(\"PyXLL has been successfully updated%s\" % ((\" to \" + unzipped_version) if unzipped_version else \"\"))\n _print(\"-\" * 79)\n\n return 0","sub_path":"Env/Lib/site-packages/pyxll/_update.py","file_name":"_update.py","file_ext":"py","file_size_in_byte":13495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"626392041","text":"# coding = utf-8\n\nimport qrcode\nimport os\n\n\ndef qr(url, file_name):\n qr_code = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_L,\n box_size=10,\n border=4,\n )\n qr_code.add_data(url)\n qr_code.make(fit=True)\n img = qr_code.make_image()\n file_name += '.jpg'\n\n img.save(os.path.join(os.path.dirname(__file__)+'/static/qr/', file_name), 'jpeg')\n\nif __name__ == '__main__':\n qr('http://www.baidu.com/')","sub_path":"ENV/qr.py","file_name":"qr.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"608607","text":"import random\nimport requests\n\n## pick my lotto number\ndef pick_lotto():\n numbers = list(range(1,46))\n my_numbers = random.sample(numbers, 6)\n my_numbers.sort()\n return my_numbers\n\n\n\n## get my lotto number\ndef get_lotto(round):\n url = 'https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo={}'.format(round)\n response = requests.get(url)\n lotto_data = response.json()\n\n real_numbers = []\n for key in lotto_data:\n if 'drwt' in key:\n real_numbers.append(lotto_data[key])\n\n real_numbers.sort()\n bonus_number = lotto_data['bnusNo']\n return {'real_numbers' : real_numbers, 'bonus_number' : bonus_number}\n\n\n\ndef am_i_lucky(my_numbers, win_numbers):\n my_numbers = set(my_numbers)\n real_numbers = set(win_numbers['real_numbers'])\n bonus_number = win_numbers['bonus_number']\n\n if len(my_numbers.intersection(real_numbers)) == 6:\n result = '축하합니다. 1등 입니다!'\n elif len(my_numbers.intersection(real_numbers)) == 5:\n if bonus_number in my_numbers:\n result = '축하합니다. 2등 입니다!'\n else:\n result = '축하합니다. 3등 입니다!' \n elif len(my_numbers.intersection(real_numbers)) == 4:\n result = '축하합니다. 4등 입니다!'\n elif len(my_numbers.intersection(real_numbers)) == 3:\n result = '축하합니다. 5등 입니다!'\n elif len(my_numbers.intersection(real_numbers)) == 2:\n result = '축하합니다. 6등 입니다!'\n elif len(my_numbers.intersection(real_numbers)) == 1:\n result = '축하합니다. 7등 입니다!'\n else:\n result = '당첨되지 않았습니다. 다음에 도전해주세요!'\n\n return result\n\n\n\n# my_numbers = pick_lotto()\n# win_numbers = get_lotto(837)\n\n\n# print('내가 선택한 번호 :', my_numbers)\n# print('실제 당첨 번호, 보너스 번호 :', win_numbers['real_numbers'], ',', win_numbers['bonus_number'])\n\n# result = am_i_lucky(my_numbers, win_numbers)\n\n# print('결과는...', result)","sub_path":"00.SSAFY/0.startcamp/day4/lotto_function.py","file_name":"lotto_function.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"229801594","text":"'''\nEnv-aware configuration for the scheduler.\n\nThis config.py is a common file that I have used in many applications. It has\nbeen very effective at abstracting where exactly configuration details come\nfrom.\n\nTypically, shared configs are checked into yaml config files, while sensitive or\nmachine-dependent configurations come from either a private.yml file placed on\nthe server (not tracked in version control), or from a sourced config.sh file.\n\nThis file will detect configurations coming from any of those sources.\n'''\nimport os\nimport sys\nimport yaml\nimport pymongo\nimport logging\n\n# The app will only accept recognized environments\nVALID_ENVS = ['devel', 'staging', 'prod']\n\n\n# Don't bring up the app if the env is not explicitly set\ntry:\n env = os.environ['ENV']\nexcept KeyError as e:\n print('FATAL - app misconfigured - no ENV variable set')\n sys.exit(-1)\n\n\n# Restrict what env the app can come up in to predefined values\nif env not in VALID_ENVS:\n print('FATAL - app misconfigured - ENV {0} is not recognized'.format(env))\n\n\nif env == 'devel':\n level = logging.DEBUG\nelse:\n level = logging.INFO\n\n# Set up logging\nlogging.basicConfig(level=level)\nlog = logging.getLogger(__name__)\n\n\ndef load_config_from_env(config):\n ''' Util to pull config vars from the environment '''\n for key, val in os.environ.items():\n config[key] = val\n\n\ndef merge_config(left, right):\n '''Merges the right-hand config ainto the left-hand config,\n\n Merges are performed with the following logic:\n Non-dict objects with the same key:\n - the value on the RHS is preferred\n Dict objects:\n - all values from LHS are merged into existing RHS\n '''\n for key, val in right.items():\n if key in left and isinstance(left[key], dict) and isinstance(val, dict):\n left[key] = merge_config(left[key], val)\n else:\n left[key] = val\n return left\n\n\n# Find the config file for this env and load it (eg config/devel.yml')\n_here = os.path.dirname(os.path.abspath(__file__))\n_config_file = open(os.path.join(_here, 'config/{env}.yml'.format(env=env)), 'r')\nconfig = yaml.load(_config_file)\n\n\n# Attempt to load a private config file - this may or may not be present\ntry:\n _private_file = open(os.path.join(_here, 'config/private.yml'), 'r')\n merge_config(config, yaml.load(_private_file))\nexcept FileNotFoundError as e:\n log.debug(\"private.yml file not found - skipping\")\n\n\n# Pull the environment config into the app\nload_config_from_env(config)\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"77139656","text":"# -*- coding:utf8 -*-\nfrom django.shortcuts import render, HttpResponse, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\n\nfrom hackspacedjango.views import HACKSPACEView\nfrom hackspacedjango.utils import sha256sum\nfrom hackspacedjango.exceptions import InvalidParameterError, APIInvalidParameterError\n\nfrom challenge.models import Challenge, Tag, ChallengeTag, ChallengeFile, ChallengeSolver\n\nfrom admin.challenge.forms import ChallengeAddForm, ChallengeUpdateForm\n\nfrom hackspacedjango.utils import paginate\n\nfrom math import ceil\nimport ujson\n\n\nclass ChallengeListView(HACKSPACEView):\n login_required = True\n staff_login_required = True\n superuser_login_required = True\n \n def get(self, request):\n page = self.get_get_parameter('page', default=1, is_required=False)\n tag_name = self.get_get_parameter('tag', default=u'All', is_required=False)\n title = self.get_get_parameter('title', is_required=False)\n tag = None\n\n if title:\n challenges = Challenge.objects.filter(title__contains=title)\n else:\n if tag_name == 'All':\n challenges = Challenge.objects.all()\n else:\n try:\n tag = Tag.objects.get(name=tag_name)\n except Tag.DoesNotExist:\n tag = None\n challenges = Challenge.objects.all()\n else:\n challenges = ChallengeTag.get_challenges_by_tag(tag)\n\n paged_challenges = paginate(challenges, page, 20)\n total_pages = int(ceil(len(challenges)/20.0))\n return render(request, 'admin/challenge/list.html',\n dict(tags=Tag.objects.all(), selected_tag=tag.id if tag else 1, challenges=paged_challenges,\n total_pages=total_pages, current_page=page, title=title))\n\n\nclass ChallengeAddView(HACKSPACEView):\n login_required = True\n staff_login_required = True\n superuser_login_required = True\n \n def get(self, request):\n return render(request, 'admin/challenge/add.html', dict(form=ChallengeAddForm()))\n \n def post(self, request):\n form = ChallengeAddForm(request.POST, request.FILES)\n if form.is_valid():\n data = form.cleaned_data\n challenge = Challenge.objects.create(\n creator=request.user, title=data['title'], description=data['description'],\n point=data['point'], answer=data['answer'], is_opened=data['is_opened'])\n for f in data['files']:\n challenge.files.add(ChallengeFile.objects.create(file=f))\n challenge.save()\n ChallengeTag.objects.create(challenge=challenge, tag=data['tag'])\n return HttpResponseRedirect(reverse('admin:challenge:list'))\n else:\n try:\n self.reason = form.errors.values()[0][0]\n except IndexError:\n pass\n return render(request, 'admin/challenge/add.html', dict(error_message=self.reason, form=form))\n\n\nclass ChallengeUpdateView(HACKSPACEView):\n login_required = True\n staff_login_required = True\n superuser_login_required = True\n \n def common(self, request, challenge_id):\n try:\n return Challenge.objects.get(id=challenge_id)\n except Challenge.DoesNotExist:\n raise InvalidParameterError(\"Bad Request\")\n \n def get(self, request, challenge):\n default = challenge.to_dict(exclude_fields=['id', 'file', 'created_at', 'updated_at'])\n return render(request, 'admin/challenge/update.html', dict(form=ChallengeUpdateForm(initial=default),\n challenge=challenge))\n \n def post(self, request, challenge):\n form = ChallengeUpdateForm(request.POST, request.FILES)\n if form.is_valid():\n data = form.cleaned_data\n challenge.title = data['title']\n challenge.description = data['description']\n challenge.answer = data['answer']\n challenge.is_opened = data['is_opened']\n if data['point']:\n diff = -(challenge.point - data['point'])\n if diff != 0:\n solvers = [challenge_solver.user for challenge_solver in ChallengeSolver.objects.filter(challenge=challenge)]\n for solver in solvers:\n solver.score += diff\n solver.save()\n challenge.point = data['point']\n\n try:\n challenge_tag = ChallengeTag.objects.get(challenge=challenge)\n except ChallengeTag.DoesNotExist:\n challenge_tag = ChallengeTag.objects.create(challenge=challenge, tag=data['tag'])\n else:\n challenge_tag.tag = data['tag']\n challenge_tag.save()\n for f in data['files']:\n file_hash = sha256sum(f)\n try:\n challenge_file = ChallengeFile.objects.get(hash=file_hash)\n except ChallengeFile.DoesNotExist:\n challenge_file = ChallengeFile.objects.create(file=f, hash=file_hash)\n challenge.files.add(challenge_file)\n challenge.save()\n return HttpResponseRedirect(reverse('admin:challenge:list'))\n else:\n try:\n self.reason = form.errors.values()[0][0]\n except IndexError:\n pass\n return render(request, 'admin/challenge/update.html', dict(challenge=challenge, form=form,\n error_message=self.reason))\n\n def put(self, request, challenge):\n status = self.get_put_parameter('status')\n if status == 'opened':\n after_status = 'Closed'\n challenge.is_opened = False\n elif status == 'closed':\n after_status = 'Opened'\n challenge.is_opened = True\n else:\n raise APIInvalidParameterError(\"Bad Request\")\n challenge.save()\n return HttpResponse(ujson.dumps(dict(status=dict(reason=self.reason, code=self.code),\n data=dict(status=after_status))))\n\n def delete(self, request, challenge):\n option = self.get_delete_parameter('option', default='challenge', is_required=False)\n if option == 'challenge':\n challenge.delete()\n elif option == 'file':\n file_id = self.get_delete_parameter('file_id')\n ChallengeFile.objects.get(id=file_id).delete()\n else:\n self.reason = \"Bad Request\"\n self.code = 'FAIL'\n return HttpResponse(ujson.dumps(dict(status=dict(reason=self.reason, code=self.code))))\n","sub_path":"admin/challenge/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"637758433","text":"import os \nimport numpy as np\nimport pandas as pd\nimport codecs, json \nimport math\n\ndef cal_varn_4 (data_num) :\n \n mat = np.cov(data_num.T)\n mat = np.diag(np.diag(mat))\n return np.divide(mat,100) \n\n\ndef generate_num_neighbors_4 (inst_num, n, varn):\n return np.random.multivariate_normal(inst_num,varn,n)\n\ndef generate_categ_neighbors_4 (inst_categ,n ,mat_nb_categ,special) :\n \n \n rs = np.random.RandomState() \n p_categ = np.size(inst_categ)\n categ_neigh = np.zeros(n*p_categ).reshape(n,p_categ)\n \n for j in range(0,p_categ) :\n med = int(n/2)\n\n if j in special :\n \tcateg_neigh[:med,j] = inst_categ[j] - 1\n else :\n \tcateg_neigh[:med,j] = inst_categ[j]\n\n categ_neigh[med:,j] = rs.choice(mat_nb_categ[j], size=(1, med))[0] \n \n return categ_neigh\n\n\ndef generate_all_neighbors_4(data, num_indices, categ_indices, mat_nb_categ, n_neigh,special) :\n \n list_neigh = []\n n = np.size(data,0)\n data_num = data[:,num_indices]\n varn = cal_varn_4 (data_num)\n \n for i in range(0,n) :\n inst_num = data_num[i]\n num_neigh_i = generate_num_neighbors_4(inst_num,n_neigh,varn)\n \n inst_categ = data[i,categ_indices]\n categ_neigh_i = generate_categ_neighbors_4(inst_categ,n_neigh ,mat_nb_categ,special)\n \n list_neigh.append(np.concatenate((num_neigh_i,categ_neigh_i),axis=1))\n \n return list_neigh\n\n\n\n\n\n","sub_path":"tabular data/classification/SplitSD4X/supplementary/neighbors_generation_4.py","file_name":"neighbors_generation_4.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"255571538","text":"import numpy as np\n\n\ndef default_delta_func(x, y):\n \"\"\"\n Default delta function. If there two characters are the same, \n give a score of 1; otherwise (including the case of a gap), give\n a a score of -1.\n\n Alternative delta functions should be defined similarly.\n \n Attributes\n ----------\n x, y : char\n The characters in the alphabet (including `-` for a gap).\n \n Returns\n -------\n float\n The delta score.\n \n \"\"\"\n if x == y:\n return 1.0\n else:\n return -1.0\n\n\ndef align_global(v1, v2, delta=default_delta_func, minimize=False):\n \"\"\"\n Apply global sequence-to-sequence alignment using the Needleman–\n Wunsch algorithm.\n \n Parameters\n ----------\n v1, v2 : str\n The two input sequences.\n delta : function, optional\n The character-to-character score function. The default value \n is ``default_delta_func``.\n minimize : bool, optional\n If True, the aligner will minimize, instead of maximize, the \n final score. It should be set to True for the classical edit \n distance problem. The default value is False.\n\n Returns\n -------\n str\n The aligned sequence ``v1``, with gaps denoted by ``-``.\n str\n The aligned sequence ``v2``, with gaps denoted by ``-``.\n float\n The final alignment score.\n\n Example\n -------\n >>> align_global('ACTTGAC', 'ACGTGC')\n ('ACTTGAC', 'ACGT-GC', 3.0)\n \n \"\"\"\n score_mat = np.zeros((len(v1) + 1, len(v2) + 1))\n case_mat = np.zeros_like(score_mat, dtype='uint8')\n selector = np.argmin if minimize else np.argmax\n\n # Table filling\n for i in range(1, len(v1) + 1):\n for j in range(1, len(v2) + 1):\n ii, jj = i - 1, j - 1\n scores = [\n score_mat[i - 1, j] + delta(v1[ii], '-'),\n score_mat[i, j - 1] + delta('-', v2[jj]),\n score_mat[i - 1, j - 1] + delta(v1[ii], v2[jj])\n ]\n argmax = selector(scores)\n score_mat[i, j] = scores[argmax]\n case_mat[i, j] = argmax + 1\n\n # Backtrace\n i, j = len(v1), len(v2)\n path = []\n while i != 0 and j != 0:\n case = case_mat[i, j]\n path.append((i, j, case))\n if case == 1: # from top (add gap to v2)\n i -= 1\n elif case == 2: # from left (add gap to v1)\n j -= 1\n else: # align\n i -= 1\n j -= 1\n path.reverse()\n\n # Update strings\n v1_padded, v2_padded = list(v1), list(v2)\n for i, j, case in path:\n ii, jj = i - 1, j - 1\n if case == 1: # add gap to v2 at location jj\n v2_padded.insert(jj, '-')\n elif case == 2: # add gap to v1 at location ii\n v1_padded.insert(ii, '-')\n final_len = max(len(v1_padded), len(v2_padded))\n if len(v1_padded) < final_len:\n v1_padded = v1_padded + ['-'] * (final_len - len(v1_padded))\n if len(v2_padded) < final_len:\n v2_padded = v2_padded + ['-'] * (final_len - len(v2_padded))\n \n return ''.join(v1_padded), ''.join(v2_padded), score_mat[-1, -1]\n \n\n\nclass Profile:\n \"\"\"\n A multisequence profile representing the frequencies of character \n appearances at each position.\n\n Attributes\n ----------\n alphabet : list\n A list of allowed characters, including the gap character.\n profile : ndarray\n The 2-dimensional profile table.\n\n Methods\n -------\n add_profile(profile, labels=None)\n Add a profile to the current Profile object and perform \n alignment.\n add_str(v, label=None)\n Add a sequence to the current Profile object and perform\n alignment.\n copy()\n Return a copy of the current Profile object.\n \n \"\"\"\n def __init__(self, strings, labels=None, alphabet=None, \n delta=default_delta_func):\n \"\"\"\n Initialize a profile.\n \n Parameters\n ----------\n strings : list\n A list of strings each denoting a sequence. They must have\n identical lengths.\n labels : list, optional\n The string labels of the sequences. If not specified, \n labels of the format ``v`` will be assigned where\n ```` is an integer.\n alphabet : list, optional\n A list of allowed characters, including the gap character.\n If not specified, it is assumed that all characters are \n covered in the input sequences.\n delta : function, optional\n The character-to-character score function. The default value \n is ``default_delta_func``.\n\n Example\n -------\n >>> profile = Profile(['ACTTGAC', 'ACGTGCC', 'ACGGCAC'],\n ... labels=['seq1', 'seq2', 'seq3'],\n ... alphabet=['A', 'C', 'T', 'G', '-'])\n <__main__.Profile at 0x7ff8dbec3898>\n\n \"\"\"\n assert len(strings) > 0\n for s in strings:\n assert len(s) == len(strings[0])\n if alphabet is None:\n alphabet = sorted(list({x for x in s for s in [*strings, '-']}))\n self.alphabet = alphabet\n if labels is None:\n labels = ['v%d' % (i + 1) for i in range(len(strings))]\n else:\n assert len(labels) == len(strings)\n self._string_labels = labels\n self._delta = delta\n self._strings = np.array([list(s) for s in strings])\n self.profile = self._build_profile_from_strings(self._strings)\n \n def __str__(self):\n lines = []\n # Print strings\n lines.append('Alignment:')\n for i, s in enumerate(self._strings):\n lines.append(self._string_labels[i] + '\\t' + '\\t'.join(s))\n lines.append('')\n # Print profile\n lines.append('Profile:')\n for i in range(self.profile.shape[0]):\n s = self.alphabet[i] + '\\t'\n s += '\\t'.join(['%.2f' % x for x in self.profile[i, :]])\n lines.append(s)\n return '\\n'.join(lines)\n \n def copy(self):\n res = Profile.__new__(Profile)\n res.alphabet = self.alphabet[:]\n res._string_labels = self._string_labels[:]\n res._delta = self._delta\n res._strings = self._strings.copy()\n res.profile = self.profile.copy()\n return res\n\n def _build_profile_from_strings(self, strings):\n \"\"\"\n Build profile table from a list of strings of equal lengths.\n \"\"\"\n profile = np.zeros((len(self.alphabet), strings.shape[1]))\n for j in range(strings.shape[1]):\n chars = list(strings[:, j])\n for i in range(len(self.alphabet)):\n profile[i, j] = chars.count(self.alphabet[i]) / strings.shape[0]\n return profile\n\n def _tau(self, x, j):\n \"\"\"\n Calculate the :math:`\\tau` score of character ``x`` and column \n ``j``.\n \"\"\"\n res = 0\n for i, y in enumerate(self.alphabet):\n res += self.profile[i, j] * self._delta(x, y)\n return res\n \n def _sigma(self, i, q, j):\n \"\"\"\n Calculate the :math:`\\sigma` score between the ith column of\n the current profile and the jth column of the profile ``q``.\n \"\"\"\n res = 0\n for ix, x in enumerate(self.alphabet):\n for iy, y in enumerate(q.alphabet):\n res += (self.profile[ix, i] * q.profile[iy, j] *\n self._delta(x, y))\n return res\n \n def add_str(self, v, label=None):\n \"\"\"\n Add a sequence to the current Profile object and perform\n alignment.\n\n Parameters\n ----------\n v : str\n The new sequence to add.\n label : str, optional\n The label of the new sequence. If not specified, ``v``\n will be used where ```` is an integer.\n\n Returns\n -------\n float\n The alignment score.\n\n \"\"\"\n score_mat = np.zeros((len(v) + 1, self.profile.shape[1] + 1))\n case_mat = np.zeros_like(score_mat, dtype='uint8')\n \n # Table filling\n for i in range(1, len(v) + 1):\n for j in range(1, self.profile.shape[1] + 1):\n ii, jj = i - 1, j - 1\n scores = [\n score_mat[i - 1, j] + self._delta(v[ii], '-'),\n score_mat[i, j - 1] + self._tau('-', jj),\n score_mat[i - 1, j - 1] + self._tau(v[ii], jj)\n ]\n argmax = np.argmax(scores)\n score_mat[i, j] = scores[argmax]\n case_mat[i, j] = argmax + 1\n \n # Backtrace\n i, j = len(v), self.profile.shape[1]\n path = []\n while i != 0 and j != 0:\n case = case_mat[i, j]\n path.append((i, j, case))\n if case == 1: # from top (add gap to profile)\n i -= 1\n elif case == 2: # from left (add gap to string)\n j -= 1\n else: # align\n i -= 1\n j -= 1\n path.reverse()\n\n # Update profile\n strings = self._strings\n v_padded = np.array(list(v)).reshape(1, -1)\n for i, j, case in path:\n ii, jj = i - 1, j - 1\n if case == 1: # add gap to profile at location jj\n strings = np.insert(strings, jj, '-', axis=1)\n elif case == 2: # add gap to string at location ii\n v_padded = np.insert(v_padded, ii, '-', axis=1)\n strings = np.concatenate([strings, v_padded])\n self._strings = strings\n self.profile = self._build_profile_from_strings(strings)\n if label is None:\n label = 'v%d' % (len(self._string_labels) + 1)\n self._string_labels.append(label)\n\n return score_mat[-1, -1]\n\n def add_profile(self, profile, labels=None):\n \"\"\"\n Add a profile to the current Profile object and perform \n alignment.\n\n Parameters\n ----------\n profile : object:Profile\n The profile to add to the current profile.\n label : list, optional\n The labels of sequences in the new profile. If not \n specified, ``v`` will be used where ```` is an \n integer.\n\n Returns\n -------\n float\n The alignment score.\n\n \"\"\"\n score_mat = np.zeros((self.profile.shape[1] + 1, \n profile.profile.shape[1] + 1))\n case_mat = np.zeros_like(score_mat, dtype='uint8')\n my_num_cols = self.profile.shape[1]\n its_num_cols = profile.profile.shape[1]\n\n # Table filling\n for i in range(1, score_mat.shape[0]):\n for j in range(1, score_mat.shape[1]):\n ii, jj = i - 1, j - 1\n scores = [\n score_mat[i - 1, j] + self._tau('-', ii),\n score_mat[i, j - 1] + profile._tau('-', jj),\n score_mat[i - 1, j - 1] + self._sigma(ii, profile, jj)\n ]\n argmax = np.argmax(scores)\n score_mat[i, j] = scores[argmax]\n case_mat[i, j] = argmax + 1\n \n # Backtrace\n i, j = self.profile.shape[1], profile.profile.shape[1]\n path = []\n while i != 0 or j != 0:\n if i == 0: # add more gaps to the other profile\n case = 2\n elif j == 0: # add more gaps to myself\n case = 1\n else:\n case = case_mat[i, j]\n path.append((i, j, case))\n if case == 1: # from top (add gap to myself)\n i -= 1\n elif case == 2: # from left (add gap to the other profile)\n j -= 1\n else: # align\n i -= 1\n j -= 1\n path.reverse()\n\n # Update profile\n my_strings = self._strings\n its_strings = profile._strings\n m, n = my_strings.shape[0], its_strings.shape[0]\n final_strings = np.empty((m + n, len(path)), dtype='`` will be used where ```` is an integer.\n delta : function, optional\n The character-to-character score function. The default value \n is ``default_delta_func``.\n alphabet : list, optional\n A list of allowed characters, including the gap character.\n If not specified, it is assumed that all characters are \n covered in the input sequences.\n \n Returns\n -------\n object:Profile\n The aligned Profile object.\n\n Example\n -------\n >>> p = multi_align(['TTGAGCGATT',\n ... 'TTGATGAGT',\n ... 'TTGAGTTT',\n ... 'TTGAGTGAGT',\n ... 'TTGAGTGAGT'])\n >>> print(p)\n <__main__.Profile at 0x7fdbac9d4400>\n\n \"\"\"\n if labels is None:\n labels = ['v%d' % (i + 1) for i in range(len(sequences))]\n profiles = [Profile([seq], labels=[label], alphabet=alphabet, delta=delta)\n for seq, label in zip(sequences, labels)]\n while len(profiles) > 1:\n new_profiles = []\n for i in range(0, len(profiles), 2):\n # handle the last one of an odd number of profiles\n if i + 1 == len(profiles):\n new_profiles[-1].add_profile(profiles[i])\n else:\n p1, p2 = profiles[i : i+2]\n p1.add_profile(p2)\n new_profiles.append(p1)\n profiles = new_profiles\n return profiles[0]\n\n","sub_path":"greedy_aligner.py","file_name":"greedy_aligner.py","file_ext":"py","file_size_in_byte":14762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"492410564","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\nfrom demo.src.applicant import Applicant\n\nclass Applicant_group:\n def __init__(self, name, color, line_style, size, scores, loan_demand, error_rate, score_error, market, repays, ir_limit=np.inf):\n self.name = name\n self.color = color\n self.line_style = line_style\n self.size = size\n self.loan_demand = loan_demand\n self.score_repay_prob = self.get_repay_prob_mapping(market.score_range, repays)\n self.initial_mean_score = np.mean(scores)\n \n real_scores = self.set_real_scores(scores, error_rate, score_error, market)\n self.applicants = self.create_applicants(scores, real_scores, ir_limit)\n self.sort_by_score()\n \n #Creates applicant objects and initializes them\n def create_applicants(self, scores, real_scores, ir_limit):\n applicants = []\n for i in range (0, self.size):\n applicants.append(Applicant(self, scores[i], real_scores[i], ir_limit))\n return applicants\n \n def sort_by_score(self):\n self.applicants.sort(key=lambda x: x.score, reverse=True)\n return self.applicants\n \n def get_repay_prob_mapping(self, score_range, repay_prob):\n x_axis = np.linspace(score_range[0],score_range[1],score_range[1]-score_range[0]+1, dtype=int)\n y_axis = np.interp(x_axis, repay_prob.index, repay_prob[self.name])\n return dict(zip(x_axis, y_axis))\n \n \n #simulating that some members of the group have better score/repay prob than rated\n def set_real_scores(self, scores, error_rate, score_error, market):\n real_scores = scores.copy()\n better_applicants = np.sort(random.sample(range(0, self.size), int(self.size*error_rate)))\n for applicant in better_applicants:\n if real_scores[applicant] + score_error < market.score_range[0]:\n real_scores[applicant] = market.score_range[0]\n elif real_scores[applicant] + score_error > market.score_range[1]:\n real_scores[applicant] = market.score_range[1]\n else:\n real_scores[applicant] += score_error\n return real_scores\n \n def get_scores(self):\n return list(applicant.score for applicant in self.applicants)\n \n def get_mean_score_change(self):\n return np.mean(self.get_scores())-self.initial_mean_score\n\n def toJSON(self):\n return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True, indent=4)\n\n def plot_histogram(self, market):\n plt.figure()\n plt.hist(self.get_scores(), range = market.score_range, label='Step ' + str(market.step))\n plt.ylabel(\"Occurence\")\n plt.xlabel(\"Score\")\n plt.ylim([0,self.size*0.75])\n plt.legend(loc=\"upper left\")\n plt.show()\n return 1\n \n def __str__(self):\n return str(self.__class__) + \": \" + str(self.__dict__)\n","sub_path":"demo/src/applicant_group.py","file_name":"applicant_group.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"387727115","text":"from abc import ABC, abstractmethod\n\nclass ScoreComponent(ABC):\n score_types = []\n extra_types = []\n\n def __init__(self, name=None, priority: float = 0):\n super().__init__()\n self.priority = priority\n self.is_filter = hasattr(self, 'filter')\n self.is_trimmer = hasattr(self, 'trim')\n self.is_score = hasattr(self, 'score')\n self.name = name if name else self.__class__.__name__\n if not (self.is_score or self.is_filter or self.is_trimmer):\n raise TypeError(f'ScoreComponent {self.name} must define one of filter, trim or score')\n if self.is_score != bool(self.score_types):\n raise TypeError(f'ScoreComponent {self.name} must define score and score_type together')\n if not isinstance(self.score_types, (tuple, list)):\n raise TypeError(f'{self.name}.score_types must be list or tuple')\n if not all(isinstance(s, str) for s in self.score_types):\n raise TypeError(f'{self.name}.score_types contents must be str')\n if not all(isinstance(s, str) for s in self.extra_types):\n raise TypeError(f'{self.name}.extra_types contents must be str')\n\n def __repr__(self):\n return f'ScoreComponent {self.name}'\n","sub_path":"rpxdock/score/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"257292189","text":"import sys\nfrom Model import Vgg16\nfrom Trainer import Trainer\nimport numpy as np\nfrom ImageOps import ImageOps\nimageOps = ImageOps()\n\nbatchsize = 32\nimageSize = 64\n\nmodel = Vgg16()\nmodel.noOfClasses = 2\nmodel.hiddenUnits = 2048\nmodel.imageShape = [imageSize, imageSize, 3]\nmodel.addMetrics('Accuracy')\nmodel.convActivation = \"relu\"\nmodel.fcActivation = \"leakyrelu\"\nmodel.regularizationCoefficient = 0.005\nmodel.regularizationType = \"l2\"\nmodel.build()\n\ntrainer = Trainer(model)\ntrainer.batchSize = 32\ntrainer.workingDir = \"vggDogCat\"\n\n\nimg=imageOps.readImage([\"test1.jpg\",\"test2.jpg\"])\nimg= imageOps.resizeImageWithAspectRatio(img,imageSize)\nimg=np.array(img).reshape([-1,imageSize,imageSize,3])\nprint(img.shape)\ntest={\n \"x\":img\n}\n\nprint(trainer.predict(test))\n\n\n","sub_path":"testVgg.py","file_name":"testVgg.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"309386434","text":"import os\nimport sys\nsys.path.append('../../')\nimport logging\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport scipy.signal as ss\nfrom glob import glob\nfrom copy import deepcopy\nfrom obspy import read\nfrom tools.data_utils import sac_len_complement\nfrom tools.data_utils import gen_tar_func\nfrom tools.data_utils import stream_standardize\nfrom tools.network_RF_example_parser import write_TFRecord_RF_network\nlogging.basicConfig(level=logging.INFO,\n format='%(levelname)s : %(asctime)s : %(message)s')\n\ngen_type = 'val'\nbasepath = '../'\nclear_rfid = np.sort(pd.read_table( os.path.join(\n basepath, 'metadata', 'clear_rf_ex.txt')).values.T[0])\nwfdir = os.path.join(basepath, 'labeled_sac', \n 'RF_multiple_sta_label')\noutpath = os.path.join(basepath, \n 'tfrecord_Association', 'RF', gen_type)\noutfigpath = os.path.join(basepath, \n 'fig_tfrecord_Association', 'RF', gen_type)\n\nos.system(f'rm -rf {outpath} {outfigpath}')\nos.makedirs(outpath); os.makedirs(outfigpath)\n# load labeling metadata\nlbl_data = np.load(os.path.join(basepath, 'metadata',\n 'rockfall_labels.npy'), allow_pickle=True)\nlbl_idx = np.array(list(lbl_data.item()))\n# load partition metadata\npartition_data = np.load(os.path.join(basepath, 'metadata',\n 'partition', 'rockfall_partition.npy'), allow_pickle=True)\nrf_train_evid = partition_data.item()[gen_type]\n\ncenter_sec = 60\ndata_length = 6000\n\n### generate training data\ntrain_ct = []\nsta_order = np.array(['LH01', 'LH02', 'LH03', 'LH04'])\nfor i in range(len(rf_train_evid)):\n evid = str(rf_train_evid[i])\n if not int(evid) in clear_rfid:\n continue\n if os.path.exists(os.path.join(wfdir, evid)):\n logging.info(f\"Generating {gen_type} data: {rf_train_evid[i]}\")\n else:\n continue\n \n stas = np.sort([os.path.basename(s).split('.')[1] for s in \n glob(os.path.join(wfdir, evid, '*.EHZ.*.sac'))])\n unlbl_sta = sta_order[np.isin(sta_order, stas, invert=True)]\n\n sta_ct = 0\n sta_meta = dict()\n for j in range(len(stas)):\n sta_lbl = lbl_data.item()[f'{evid}_{stas[j]}']\n sta_lbl_center = np.mean(sta_lbl, axis=-1)\n\n # determine the centering label\n center_idx = np.array([np.logical_and(\n l[0]<=center_sec, center_sec<=l[1]) for l in sta_lbl])\n if np.array_equal(center_idx, np.full(len(sta_lbl), False)):\n center_idx[\n np.argmin(np.abs(center_sec-sta_lbl_center))] = True\n\n ### read waveform and make rockfall mask\n st = read(os.path.join(wfdir, evid, f'*.{stas[j]}.EH?.*.sac'))\n trc_stt = st[0].stats.starttime\n RF_mask = np.zeros(st[0].stats.npts)\n RF_mask_trc = deepcopy(st[0])\n for l in range(len(sta_lbl)):\n if np.logical_and(\n 60-sta_lbl[l][0] > 0, sta_lbl[l][1] - 60 > 0):\n center_lbl = sta_lbl[l]\n\n #### make target functions first\n rf_st_sec, rf_ent_sec = sta_lbl[l]\n rf_st = int(np.round(rf_st_sec, 2)*100)\n rf_ent = int(np.round(rf_ent_sec, 2)*100)\n _front = gen_tar_func(st[0].stats.npts, rf_st, 100)\n _front[np.argmax(_front)+1:] = 0\n\n if rf_ent != 12000:\n _back = gen_tar_func(st[0].stats.npts, rf_ent, 100)\n _back[:np.argmax(_back)-1] = 0\n\n mask = _front + _back\n mask[rf_st:rf_ent-1] = 1\n else:\n mask = np.zeros(st[0].stats.npts)\n mask[rf_st:] = 1\n RF_mask += mask\n\n if RF_mask.max() != 1:\n stop\n #continue\n if RF_mask.min() != 0:\n stop\n #continue\n\n RF_mask_trc.data = RF_mask\n\n sta_meta[stas[j]] = dict()\n sta_meta[stas[j]]['st'] = st\n sta_meta[stas[j]]['rf_mask'] = RF_mask_trc\n sta_meta[stas[j]]['center_label'] = center_lbl\n\n center_lbl_all = np.array([sta_meta[c]['center_label'] for c in stas])\n # make rockfall occurrence stream\n ev_stt = np.min(center_lbl_all[:, 0]) - 0.5\n last_lbl_ent = ev_stt + \\\n (np.max(center_lbl_all[:, 1]) - np.min(center_lbl_all[:, 0]))\n rf_occ_st = deepcopy(st[0])\n rf_occ_st.data = gen_tar_func(st[0].stats.npts, int(ev_stt*100), 100)\n\n # fake up waveform of random floats for unlabeled stations\n for k in range(len(unlbl_sta)):\n _st = deepcopy(st)\n for _w in _st:\n _w.data = np.random.random(len(_w.data))\n _rf_mask_trc = deepcopy(st[0])\n _rf_mask_trc.data = np.zeros(len(st[0].data))\n sta_meta[unlbl_sta[k]] = dict()\n sta_meta[unlbl_sta[k]]['st'] = _st\n sta_meta[unlbl_sta[k]]['rf_mask'] = _rf_mask_trc\n sta_meta[unlbl_sta[k]]['center_label'] = [0, 0]\n \n # determine the center waveform with randomly distributed location\n available_sec = int(data_length*0.01) - (last_lbl_ent-ev_stt)\n center_start_sec = ev_stt - available_sec/2\n\n if np.logical_and(ev_stt > available_sec, available_sec>10) :\n avail_bef = available_sec\n else:\n avail_bef = ev_stt\n \n seg_front_start_sec = np.sort([ev_stt - \n np.random.randint(int(avail_bef*100))*0.01 \n for C in range(3)])\n\n\n seg_back_stt_sec = np.sort(np.array([ \n np.random.uniform(\n low=center_start_sec,\n high=ev_stt\n ) for C in range(3)]))\n assert np.all(seg_back_stt_sec > center_start_sec)\n\n # remove trace with insufficient data \n if gen_type == 'test':\n seg_start_sec = np.array([center_start_sec])\n else:\n seg_start_sec = np.hstack([\n center_start_sec, seg_back_stt_sec, seg_front_start_sec])\n\n seg_start_sec = seg_start_sec[\n np.logical_and(\n seg_start_sec>0,\n (seg_start_sec+int(data_length*0.01)) < len(st[0].data)*0.01)\n ]\n seg_start_sec = np.sort(seg_start_sec)\n\n # make tfrecord\n for s in range(len(seg_start_sec)):\n ev_occ_npts = int(100*(ev_stt - seg_start_sec[s]))\n rf_occ_pdf = gen_tar_func(data_length, ev_occ_npts, 100)\n eq_occ_pdf = np.zeros(data_length)\n\n tar_rf_occ = np.array([\n rf_occ_pdf, np.ones(data_length)-rf_occ_pdf]).T\n tar_eq_occ = np.array([\n eq_occ_pdf , np.ones(data_length)-eq_occ_pdf ]).T\n\n tfr_idx = f'{evid}_rf_{s+1:02}'\n\n net_data = []\n for m in range(len(sta_order)):\n wf_metadata = sta_meta[sta_order[m]]\n wf = deepcopy(wf_metadata['st'])\n rf_mask = deepcopy(wf_metadata['rf_mask'])\n wf_stt = wf[0].stats.starttime\n\n # waveform data\n slice_stt = wf_stt+seg_start_sec[s]\n slice_ent = slice_stt + data_length*0.01\n\n seg_wf = stream_standardize(\n sac_len_complement(\n deepcopy(wf).slice(\n starttime=slice_stt, endtime=slice_ent),\n max_length=data_length),\n data_length=data_length\n )\n\n #seg_wf.plot()\n seg_RF_mask_trc = rf_mask.slice(slice_stt, slice_ent,\n nearest_sample=False)\n \n trc_3C = np.array([\n seg_wf[0].data, seg_wf[1].data, seg_wf[2].data]).T\n\n # STFT\n tmp_data = deepcopy(seg_wf[2].data)\n tmp_mean = np.mean(tmp_data)\n tmp_data -= tmp_mean\n\n sos = ss.butter(4, 0.1, 'high', fs=100, output='sos')\n tmp_data = ss.sosfilt(sos, tmp_data)\n\n f, t, tmp_FT = ss.stft(tmp_data, fs=100, nperseg=20, \n nfft=100, boundary='zeros')\n tmp_std = np.std(tmp_FT)\n norm_FT = tmp_FT/tmp_std\n norm_FT_real, norm_FT_imag = norm_FT.real, norm_FT.imag\n norm_FT_real[np.isnan(norm_FT_real)]=0\n norm_FT_imag[np.isnan(norm_FT_imag)]=0\n norm_FT_real[np.isinf(norm_FT_real)]=0\n norm_FT_imag[np.isinf(norm_FT_imag)]=0\n spectrogram = np.stack([norm_FT_real, norm_FT_imag], -1)\n\n # rockfall \n seg_RF_mask = seg_RF_mask_trc.data[:data_length]\n seg_RF_unmask = np.ones(data_length) - seg_RF_mask\n tar_RFmask = np.array([seg_RF_mask, seg_RF_unmask]).T\n\n # EQpick\n EQpick_P = np.zeros(data_length)\n EQpick_S = np.zeros(data_length)\n EQ_unpick = np.ones(data_length) - EQpick_P - EQpick_S\n tar_EQpick = np.array([EQpick_P, EQpick_S, EQ_unpick]).T\n\n # EQmask\n EQmask = np.zeros(data_length)\n EQ_unmask = np.ones(data_length) - EQmask\n tar_EQmask = np.array([EQmask, EQ_unmask]).T\n\n net_data.append([\n trc_3C, spectrogram, tar_EQpick, tar_EQmask, tar_RFmask])\n\n # write tfrecord of general order data\n ordered_net_data = np.array(net_data, dtype=object)\n stack_net_data = np.hstack(ordered_net_data)\n write_TFRecord_RF_network(stack_net_data, tar_rf_occ, tar_eq_occ,\n outfile=os.path.join(outpath, f\"{tfr_idx}.tfrecord\"))\n # write tfrecord of random order data\n if gen_type != 'test':\n r_net_order = np.random.permutation(np.arange(4))\n random_net_data = ordered_net_data[r_net_order]\n r_stack_net_data = np.hstack(random_net_data)\n write_TFRecord_RF_network(r_stack_net_data, tar_rf_occ, tar_eq_occ,\n outfile=os.path.join(outpath, f\"{tfr_idx}_random.tfrecord\"))\n\n # plot figures\n sta_trc_Z = np.array([Z.T[2] for Z in stack_net_data[::5]])\n sta_rf_mask = np.array([Z.T[0] for Z in stack_net_data[4::5]])\n rf_occ = tar_rf_occ.T[0]\n x = np.arange(len(rf_occ))/100\n fig, ax = plt.subplots(5, 1, figsize=(10, 8))\n for a in range(4):\n ax[a].plot(x, sta_trc_Z[a], linewidth=1, color='k')\n ax_t = ax[a].twinx()\n ax_t.plot(x, sta_rf_mask[a], linewidth=1, color='r')\n ax_t.set_ylim(-0.1, 1.1)\n ax[a].set_ylabel(sta_order[a])\n ax[a].set_xticks([])\n ax[a].set_xlim(0, data_length*0.01)\n \n ax[4].plot(x, rf_occ, linewidth=1, color='b')\n ax[4].set_xlim(0, data_length*0.01)\n ax[4].set_ylabel('RF\\ndetect')\n ax[4].set_ylim(-0.1, 1.1)\n ax[4].set_xlabel('Time (s)')\n plt.tight_layout()\n plt.savefig(os.path.join(outfigpath, f'{tfr_idx}.png'))\n plt.close()\n #plt.show()","sub_path":"data/gen_TFRecord/P06.2_network_RF_val.py","file_name":"P06.2_network_RF_val.py","file_ext":"py","file_size_in_byte":10518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"490002126","text":"try:\n from setuptools import setup, find_packages\nexcept ImportError:\n from ez_setup import use_setuptools\n use_setuptools()\n from setuptools import setup, find_packages\n\nrequires = [\n 'Fabric',\n 'Flask',\n 'Flask-Login',\n 'SQLAlchemy',\n 'WTForms',\n 'oauth2client',\n 'requests',\n 'MySQL-python',\n]\n\nsetup(\n name='fullerene',\n version='0.1',\n description='',\n requires=requires,\n author='Matt Vliet',\n author_email='',\n packages=find_packages(),\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"246691723","text":"from pygame.constants import MOUSEBUTTONDOWN\nimport constants as c\nimport pygame as pg\nimport numpy as np\nimport math\n\nclass TurnArrow(c.Constants):\n def __init__(self, n_player):\n super().__init__()\n self.radius = self.size[0] * 0.1\n self.circle = [self.size / 2, self.radius]\n\n self.surface_size = self.size * 0.04\n self.surface = pg.Surface(self.surface_size, pg.SRCALPHA)\n\n self.n_player = n_player\n self.deg = 0\n\n w, h = self.surface_size[0], self.surface_size[1]\n p = [[(0, 0), (w / 2, h / 3), (w / 2, h)], [(w, 0), (w / 2, h / 3), (w / 2, h)]]\n pg.draw.polygon(self.surface, self.L_ORANGE, p[0], 0)\n pg.draw.polygon(self.surface, self.ORANGE, p[1], 0)\n \n def update_turn(self, n):\n self.deg = n * 360 / self.n_player\n self.pos = np.array([self.circle[0][0] + self.radius * math.sin(math.radians(self.deg)), \\\n self.circle[0][1] + self.radius * math.cos(math.radians(self.deg))])\n\n self.rotated_surface = pg.transform.rotate(self.surface, self.deg)\n\n def visualize(self, t):\n self.dynamic_movement(t)\n rect = self.rotated_surface.get_rect(center = self.pos)\n self.screen.blit(self.rotated_surface, rect)\n \n def dynamic_movement(self, t):\n dir = (self.pos - self.circle[0]) / np.linalg.norm(self.pos - self.circle[0])\n self.pos += dir * np.sign((t % 30) - 14.5)\n","sub_path":"turnArrow.py","file_name":"turnArrow.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"506022174","text":"\nclass Employee:\n raise_amt = 1.04\n num_of_emps = 0\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.email = first + '.' + last + '@email.com'\n self.pay = pay\n Employee.num_of_emps +=1\n\n def fullname(self):\n return '{} {}'.format(self.first, self.last)\n def apply_raise(self):\n# class variables can only be applied throgh instance of the object or class itself\n self.pay = self.pay * self.raise_amt\n\n \nprint(\"number_of_employees_before\",Employee.num_of_emps)\nemp_1 = Employee('Corey', 'Schafer', 50000)\nemp_2 = Employee('Test', 'Employee', 60000)\nprint(\"number_of_employees_after\",Employee.num_of_emps)\nemp_1.raise_amt = 5\nprint(emp_1.raise_amt)\nprint(Employee.raise_amt)\n\n\nprint(emp_1.__dict__)\nprint(Employee.__dict__)\n\n","sub_path":"Object-Oriented/2-Class-Instance-Variables/oop.py","file_name":"oop.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"220584919","text":"\"\"\"\n Functions intended to be used to make comparisons between different sources\n or to be used to analyze something from a single clip.\n\"\"\"\nimport random\nfrom typing import List, Optional\n\nimport vapoursynth as vs\nfrom vsutil import depth, get_subsampling, get_w, split\n\nfrom .util import get_prop\n\ncore = vs.core\n\n\ndef compare(clip_a: vs.VideoNode, clip_b: vs.VideoNode,\n frames: Optional[List[int]] = None,\n rand_total: Optional[int] = None,\n force_resample: bool = True, print_frame: bool = True,\n mismatch: bool = False) -> vs.VideoNode:\n \"\"\"\n Allows for the same frames from two different clips to be compared by interleaving them into a single clip.\n Clips are automatically resampled to 8 bit YUV -> RGB24 to emulate how a monitor shows the frame.\n This can be disabled by setting `disable_resample` to True.\n\n Alias for this function is `lvsfunc.comp`.\n\n Dependencies: mvsfunc\n\n :param clip_a: Clip to compare\n :param clip_b: Second clip to compare\n :param frames: List of frames to compare (Default: None)\n :param rand_total: Number of random frames to pick (Default: None)\n :param force_resample: Forcibly resamples the clip to RGB24 (Default: True)\n :param print_frame: Print frame numbers (Default: True)\n :param mismatch: Allow for clips with different formats and dimensions to be compared (Default: False)\n\n :return: Interleaved clip containing specified frames from clip_a and clip_b\n \"\"\"\n try:\n from mvsfunc import GetMatrix\n except ModuleNotFoundError:\n raise ModuleNotFoundError(\"compare: missing dependency 'mvsfunc'\")\n\n def _resample(clip: vs.VideoNode) -> vs.VideoNode:\n # Resampling to 8 bit and RGB to properly display how it appears on your screen\n return depth(clip.resize.Point(format=vs.RGB24, matrix_in_s=str(GetMatrix(clip))), 8)\n\n # Error handling\n if frames and len(frames) > clip_a.num_frames:\n raise ValueError(\"compare: 'More comparisons requested than frames available'\")\n\n if force_resample:\n clip_a, clip_b = _resample(clip_a), _resample(clip_b)\n else:\n if clip_a.format is None or clip_b.format is None:\n raise ValueError(\"compare: 'Variable-format clips not supported'\")\n if clip_a.format.id != clip_b.format.id:\n raise ValueError(\"compare: 'The format of both clips must be equal'\")\n\n if print_frame:\n clip_a, clip_b = clip_a.text.FrameNum(), clip_b.text.FrameNum()\n\n if frames is None:\n if not rand_total:\n # More comparisons for shorter clips so you can compare stuff like NCs more conveniently\n rand_total = int(clip_a.num_frames / 1000) if clip_a.num_frames > 5000 else int(clip_a.num_frames / 100)\n frames = sorted(random.sample(range(1, clip_a.num_frames - 1), rand_total))\n\n frames_a = core.std.Splice([clip_a[f] for f in frames])\n frames_b = core.std.Splice([clip_b[f] for f in frames])\n return core.std.Interleave([frames_a, frames_b], mismatch=mismatch)\n\n\ndef stack_compare(*clips: vs.VideoNode,\n make_diff: bool = False,\n height: Optional[int] = None,\n warn: bool = True) -> vs.VideoNode:\n \"\"\"\n A simple wrapper that allows you to compare two clips by stacking them.\n You can stack an infinite amount of clips.\n\n Best to use when trying to match two sources frame-accurately, however by setting height to the source's\n height (or None), it can be used for comparing frames.\n\n Alias for this function is `lvsfunc.scomp`.\n\n :param clips: Clips to compare\n :param make_diff: Create and stack a diff (only works if two clips are given) (Default: False)\n :param height: Output height, determined automatically if None (Default: None)\n :param warn: Warns if the length of given clips don't align (Default: True)\n\n :return: Clip with clips stacked\n \"\"\"\n if len(clips) < 2:\n raise ValueError(\"stack_compare: 'Too few clips supplied'\")\n\n if len(clips) != 2 and make_diff:\n raise ValueError(\"stack_compare: 'You can only create a diff for two clips'\")\n\n formats = set()\n for c in clips:\n if c.format is None:\n raise ValueError(\"stack_compare: 'Variable-format clips not supported'\")\n formats.add(c.format.id)\n if len(formats) != 1:\n raise ValueError(\"stack_compare: 'The format of every clip must be equal'\")\n\n if make_diff:\n diff = core.std.MakeDiff(clips[0], clips[1])\n diff = core.resize.Spline36(diff, get_w(576), 576).text.FrameNum(8)\n resize = [core.resize.Spline36(c, int(diff.width / 2), int(diff.height / 2)) for c in clips]\n resize[0], resize[1] = resize[0].text.Text(\"Clip A\", 3), resize[1].text.Text(\"Clip B\", 1)\n stack = core.std.StackVertical([core.std.StackHorizontal([resize[0], resize[1]]), diff])\n else:\n stack = core.std.StackHorizontal(clips)\n if warn:\n if len(set([c.num_frames for c in clips])) != 1:\n stack = core.text.Text(stack,\n \"Clip Length Mismatch Detected!\\nPlease make sure the lengths of all clips match!\\n\"\n + \"\".join(f\"\\nClip {i+1}: {c.num_frames} Frames\" for i, c in enumerate(clips)), 2)\n return stack\n\n\ndef stack_planes(clip: vs.VideoNode,\n stack_vertical: bool = False) -> vs.VideoNode:\n \"\"\"\n Stacks the planes of a clip.\n\n :param clip: Input clip\n :param stack_vertical: Stack the planes vertically (Default: False)\n\n :return: Clip with stacked planes\n \"\"\"\n\n planes = split(clip)\n subsampling = get_subsampling(clip)\n\n if subsampling == '420':\n if stack_vertical:\n stack = core.std.StackHorizontal([planes[1], planes[2]])\n return core.std.StackVertical([planes[0], stack])\n else:\n stack = core.std.StackVertical([planes[1], planes[2]])\n return core.std.StackHorizontal([planes[0], stack])\n elif subsampling == '444':\n return core.std.StackVertical(planes) if stack_vertical else core.std.StackHorizontal(planes)\n else:\n raise ValueError(\"stack_planes: 'Input clip must be in YUV format with 444 or 420 chroma subsampling'\")\n\n\ndef tvbd_diff(tv: vs.VideoNode, bd: vs.VideoNode,\n thr: float = 72,\n return_array: bool = False) -> vs.VideoNode:\n \"\"\"\n Creates a standard `stack_compare` between frames from two clips that have differences.\n Useful for making comparisons between TV and BD encodes, as well as clean and hardsubbed sources.\n\n There are two methods used here to find differences.\n If thr is below 1, PlaneStatsDiff is used to figure out the differences.\n Else, if thr is equal than or higher than 1, PlaneStatsMin/Max are used.\n\n Recommended is PlaneStatsMin/Max, as those seem to catch\n more outrageous differences more easily and not return\n too many starved frames.\n\n Note that this might catch artifacting as differences!\n Make sure you verify every frame with your own eyes!\n\n Alias for this function is `lvsfunc.diff`.\n\n :param tv: TV clip\n :param bd: BD clip\n :param thr: Threshold, <= 1 uses PlaneStatsDiff, >1 uses Max/Min. Max is 128 (Default: 72)\n :param return_array: Return frames as an interleaved comparison (using py:func:`lvsfunc.comparison.compare`)\n (Default: False)\n \"\"\"\n if thr > 128:\n raise ValueError(\"tvbd_diff: \\\"thr\\\" should neither be nor exceed 128!'\")\n\n tv, bd = depth(tv, 8), depth(bd, 8)\n\n if thr <= 1:\n diff = core.std.PlaneStats(tv, bd)\n frames = [i for i, f in enumerate(diff.frames()) if get_prop(f, \"PlaneStatsDiff\", float) > thr]\n else:\n diff = core.std.MakeDiff(tv, bd).std.PlaneStats()\n if diff.format is None:\n raise ValueError(\"tvbd_diff: 'Variable-format clips not supported'\")\n t = float if diff.format.sample_type == vs.FLOAT else int\n frames = [i for i, f in enumerate(diff.frames())\n if get_prop(f, \"PlaneStatsMin\", t) <= thr\n or get_prop(f, \"PlaneStatsMax\", t) >= 255 - thr]\n\n if not frames:\n raise ValueError(\"tvbd_diff: 'No differences found'\")\n\n if return_array:\n return compare(tv.text.FrameNum().text.Text('Clip A', 9),\n bd.text.FrameNum().text.Text('Clip B', 9),\n frames)\n else:\n if thr <= 1:\n diff = core.std.MakeDiff(tv, bd)\n diff = core.resize.Spline36(diff, get_w(576), 576).text.FrameNum(8)\n tv = core.resize.Spline36(tv, int(diff.width / 2), int(diff.height / 2)).text.Text(\"Clip A\", 3)\n bd = core.resize.Spline36(bd, int(diff.width / 2), int(diff.height / 2)).text.Text(\"Clip B\", 3)\n stacked = core.std.StackVertical([core.std.StackHorizontal([tv, bd]), diff])\n return core.std.Splice([stacked[f] for f in frames])\n\n\n# TODO: Write a comparison function that displays parts of clips side-by-side, similar to a slider.\n# It should theoretically accept an infinite amount of clips\n# and accurately split the width among all clips.\n# Odd-resolution clips will also need to be taken into account.\n","sub_path":"lvsfunc/comparison.py","file_name":"comparison.py","file_ext":"py","file_size_in_byte":9467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"163036427","text":"from rest_framework.permissions import BasePermission, SAFE_METHODS, IsAuthenticatedOrReadOnly\n\n\nclass IsTweetAuthorOrReadOnly(IsAuthenticatedOrReadOnly):\n \"\"\"\n The request is authenticated as a user, or is a read-only request.\n \"\"\"\n\n def has_object_permission(self, request, view, tweet):\n if request.method in SAFE_METHODS:\n return True\n return bool(\n request.user and\n request.user.is_authenticated and\n tweet.author == request.user\n )","sub_path":"tutorial/quickstart/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"165547948","text":"import numpy as np \nimport matplotlib.pyplot as plt \nfrom scipy.interpolate import interp1d\nimport misc_utils as mu\nfrom matplotlib import colors, ticker, cm\nfrom orbit_class import Orbit\n# -----------------------------------------------------------------\n# Note that you must have 5 files in correct paths/formats/units for this\n# to work correctly\n# 1) contrast table for the coronagraph design\n# 2) solar spectrum\n# 3) geometric albedo spectrum for modeled planet\n# 4) stellar spectrum for host star\n# 5) quantum efficiency for e2_v detector\n# may want to add something with phase function as function of wavlength...\n# -----------------------------------------------------------------\ndef planet_star_fluxratio(wavelength, params):\n # input wavelength unit: microns \n return params['Ag'](wavelength)*params['phi']*(params['rp']*params['rjup'] \\\n / (params['sep']*params['au_to_m']))**2.0\n\ndef stellar_photon_flux(wavelength, params):\n # input wavelength unit: microns\n # units of flux returned are photons/m^2/second in bins centered at input wavelength\n # with resolving power R specified in params dictionary\n mstar = params['Mstar'] +5.0*np.log10(params['d_obs']/10.0) # distance modulus to get apparent V band magnitude\n flux = (wavelength*10.0**-6.0)/(params['h']*params['c']) \\\n * params['fstar_lambda'](wavelength) * wavelength/params['R']\\\n * 10.0**(-mstar/2.5) # modify flux from apparent mag of 0 to target's apparent mag\n return flux\n\ndef zodi_photon_flux(wavelength, params):\n # input wavelength unit: microns\n # units of flux returned are photons/m^2/second in bins centered at input wavelength\n # with resolving power R specified in params dictionary\n ratio = params['fstar_lambda'](wavelength)*10.0**(-params['Mstar']/2.5) \\\n *(10.0*params['pc_to_m']/au_to_m)**2.0 / params['FsolV']\n exozodi_photon_flux_density = params['Nez']*ratio*params['F0V']*wavelength/params['R'] \\\n *10.0**(-params['MezV']/2.5)*params['sep']**-2.0 \\\n * (wavelength*10.0**-6.0)/(params['h']*params['c']) #\\\n #* (10.0/params['d_obs'])**2.0 \n ratio = params['fsun_lambda'](wavelength) / params['FsolV']\n zodi_photon_flux_density = ratio*params['F0V']* wavelength/params['R'] \\\n *10.0**(-params['MzV']/2.5) \\\n * (wavelength*10.0**-6.0)/(params['h']*params['c']) \n return (exozodi_photon_flux_density + zodi_photon_flux_density)*calc_psf_area(wavelength,params)\n\ndef calc_mpix(wavelength, params):\n # input wavelength unit: microns\n mpix = params['mpix']*(wavelength/params['wl_c'])**2.0 \n return mpix\n\ndef calc_mpixTable(wavelength, params):\n mpix = params['mpixTable']#*(wavelength/params['wl_d'])**2.0 \n return mpix\n\ndef calc_psf_area(wavelength,params):\n # wavelength in microns\n # output area in square arcseconds\n return np.median(params['area_sqarcsec'])*(wavelength/params['wl_d'])**2.0\n\n# -----------------------------------------------------------------\ndef calc_rplanet(wavelength, params):\n # input wavelength unit: microns\n # returns photons/second in bins centered at input wavelength\n # with resolving power R specified in params dictionary\n wa_lamD = params['wa']/(wavelength*10.0**-6.0/params['D'])\n tau_pla = params['tau_ref']*params['tau_fil']*params['tau_core'](wa_lamD)*params['tau_pol']\n rpl = stellar_photon_flux(wavelength, params)*planet_star_fluxratio(wavelength, params) \\\n *params['Apm']*tau_pla*params['eta'](wavelength)*params['cte_cr_hot']*params['phc']\n return rpl \n\ndef calc_rzodi(wavelength, params):\n # input wavelength unit: microns\n # returns photons/second in bins centered at input wavelength\n # with resolving power R specified in params dictionary \n wa_lamD = params['wa']/(wavelength*10.0**-6.0/params['D'])\n tau_zod = params['tau_occ'](wa_lamD)*params['tau_ref']*params['tau_fil']*params['tau_pol']\n rzodi = zodi_photon_flux(wavelength, params)*params['Apm']*tau_zod* \\\n params['eta'](wavelength)*params['cte_cr_hot']*params['phc']\n return rzodi\n\ndef calc_rspeckle(wavelength, params): \n # input wavelength unit: microns\n # returns photons/second in bins centered at input wavelength\n # with resolving power R specified in params dictionary\n wa_lamD = params['wa']/(wavelength*10.0**-6.0/params['D'])\n tau_spe = params['tau_ref']*params['tau_fil']*params['tau_pol']\n rsp = stellar_photon_flux(wavelength, params) \\\n *params['contrast_func'](wa_lamD)*params['Ipk_func'](wa_lamD)\\\n *calc_mpixTable(wavelength,params)\\\n *params['Apm']*tau_spe*params['eta'](wavelength)*params['cte_cr_hot']*params['phc'] \n return rsp\n\ndef calc_rdark(wavelength, params):\n # input wavelength unit: microns\n # returns photons/second in bins centered at input wavelength\n # with resolving power R specified in params dictionary\n return params['idark']*calc_mpix(wavelength,params)*params['cte_cr_hot']*params['phc']\n\ndef calc_rcic(wavelength, params):\n # input wavelength unit: microns\n # returns photons/second in bins centered at input wavelength\n # with resolving power R specified in params dictionary\n return params['qcic']*calc_mpix(wavelength,params)/params['tfr']*params['cte_cr_hot']*params['phc']\n\ndef calc_rread(wavelength, params):\n # input wavelength unit: microns\n # returns photons/second in bins centered at input wavelength\n # with resolving power R specified in params dictionary\n return params['sig_read']*calc_mpix(wavelength,params)/params['tfr']*params['cte_cr_hot']\n\n# -----------------------------------------------------------------\ndef calc_rates(wavelength,params):\n rp = calc_rplanet(wavelength, params)\n rz = calc_rzodi(wavelength, params)\n rs = calc_rspeckle(wavelength,params)\n rd = calc_rdark(wavelength, params)\n rcic = calc_rcic(wavelength, params)\n rr = calc_rread(wavelength, params)\n rn = rp + (rz + rs)*params['zodi_multiplier'] + (rd + rcic + rr)*params['detector_multiplier']\n return rp,rz,rs,rd,rcic,rr,rn\n \ndef calc_snr(texp,wavelength,params):\n # input wavelength unit: microns\n # input texp unit: seconds\n rp,rz,rs,rd,rcic,rr,rn = calc_rates(wavelength,params)\n signal = rp*texp\n variance = np.sqrt(rn*texp + (params['fpp']*rs*texp)**2.0)\n return signal/variance\n\ndef calc_texp(SNR,wavelength,params):\n # input wavelength unit: microns\n # time returned in seconds\n rp,rz,rs,rd,rcic,rr,rn = calc_rates(wavelength,params)\n return SNR**2.0*rn / (rp**2.0 - (SNR*params['fpp']*rs)**2.0)\n\ndef calc_tSNRmax(wavelength,params,percent=0.9):\n # returns time in seconds to reach percent*SNRmax (recall time to 100% SNRmax is infinite)\n rp,rz,rs,rd,rcic,rr,rn = calc_rates(wavelength,params)\n SNRmax = rp/(params['fpp']*rs)\n return rn*(percent*SNRmax)**2.0/(rp**2.0*(1.0-percent**2.0))\n\ndef generate_noisey_data(TEXP, wavelengths, params):\n SNR = calc_snr(TEXP*60.0*60.0,wavelengths,params)\n noiseless_signal = planet_star_fluxratio(wavelengths,params)\n noise = noiseless_signal/SNR \n noisy_signal = [np.random.normal(noiseless_signal[k],noise[k]) for k in range(len(wavelengths))]\n noisy_signal = np.array(noisy_signal)\n return noiseless_signal, noisy_signal, noise\n \ndef planet_star_fluxratio_rayleigh(wavelength, params): \n ratio = params['Ag'](wavelength)*params['phi_func'](wavelength)*(params['rp']\\\n *params['rjup']/(params['sep']*params['au_to_m']))**2.0\n return ratio\n\ndef generate_noisey_data_rayleigh(TEXP, wavelengths, params):\n SNR = calc_snr(TEXP*60.0*60.0,wavelengths,params)\n noiseless_signal = planet_star_fluxratio_rayleigh(wavelengths,params)\n noise = noiseless_signal/SNR \n noisy_signal = [np.random.normal(noiseless_signal[k],noise[k]) for k in range(len(wavelengths))]\n noisy_signal = np.array(noisy_signal)\n return noiseless_signal, noisy_signal, noise\n# -----------------------------------------------------------------\n# ASTROPHYSICAL CONSTANTS AND CONVERSIONS\nrad_to_arcsec = mu.rad_to_arcsec \npc_to_m = mu.pc_to_m\nau_to_m = mu.au_to_m\nrsun = mu.rsun # radius of the sun in meters\nrjup = mu.rjup # radius of jupiter in meters\nh = mu.h # planck constant m^2 kg s^-1\nkb = mu.kb # Boltzman constant m^2 kg s^-2 K^-1\nsb = mu.sb # steffan boltzman constant W m^-2 K^-4\nc = mu.c # speed of light m s^-1\nF0V = mu.F0V # 3.6*10.0**-8.0 # zero mag V band flux W/m^2/um\nsolar_spec = mu.solar_spec # specific flux density W / m^2 / micron, at 1AU\nref_wl, ref_flambda = np.loadtxt(solar_spec,unpack=True,usecols=(0,1))\nfsun_lambda = interp1d(ref_wl,ref_flambda) # units still specific flux density\nMsunV = mu.MsunV # 4.83\nFsolV = mu.FsolV # solar V band flux W/m^2/um at 1AU\nMzV = mu.MzV # 23.0\nMezV = mu.MezV #22.0\n\n# -----------------------------------------------------------------\nif __name__ == '__main__':\n\n # ------------------------ EXAMPLE ---------------------------------\n # SET UP TARGET SYSTEM\n d_obs = 10.0\n mstar = 5.0 #APPARENT vband magnitude\n Mstar = mstar - 5.0*np.log10(d_obs/10.0) # distance modulus to get ABSOLUTE V band magnitude\n stellartype = 'g0v'\n stellar_spec = 'AuxiliaryData/'+stellartype+'.dat' # specific flux density W / m^2 / micron, for zero mag star\n ref_wl, ref_flambda = np.loadtxt(stellar_spec,unpack=True,usecols=(0,1))\n fstar_lambda = interp1d(ref_wl,ref_flambda) # units still specific flux density\n sep = 3.8\n rp = 1.0\n Nez = 1.0\n ## set phi*Ag = 0.25\n Ag = mu.fixed_albedo # this function just returns 0.25 for every wavelength\n alpha = 65.0 # will only be used for wa, not Phi(alpha)\n phi = 1.0 \n wa = mu.calc_wa(sep,alpha,d_obs) # working angle in radians, consistent with alpha, sep, and circular orbit\n # PUT IT ALL IN DICTIONARY \n params = {'fstar_lambda':fstar_lambda,'d_obs':d_obs,'Nez':Nez,\n 'rp':rp,'sep':sep,'Ag':Ag,'phi':phi,'wa':wa,'Mstar':Mstar}\n # ADD CORONAGRAPH, DETECTOR AND TELESCOPE TO DICTIONARY\n # available coronagraph versions are:\n # org_hlc_pars, org_spc_pars, cbe_hlc_pars, \n # cbe_spc_pars, req_spc_pars, req_hlc_pars\n cversion_dict = mu.cbe_spc_pars.copy()\n params.update(cversion_dict)\n\n\n # COMPUTE + PRINT SOME RATES AND TIMES \n wavelength = np.linspace(0.575,1.0,1000) \n times = np.arange(10.0,420.0,20.0)\n rp, rz, rs, rd, rcic, rr, rn = calc_rates(wavelength, params)\n times = calc_texp(5.0,wavelength,params)\n # index 435 is 0.76 microns, lets look at the center of that band\n SNRmax = rp[435]/(params['fpp']*rs[435])\n con = planet_star_fluxratio(0.76,params) \n print('Planet-Star flux ratio: ', con)\n print('SNR max: ', SNRmax)\n print('wa (arcsec): ', wa*rad_to_arcsec)\n print('exposure time to SNR 5.0: %f hours' % (times[435]/60.0/60.0))\n print('count rates rp: %f rz: %f rs: %f rd: %f rclk: %f rr: %f rn: %f all e-/sec/signalregion' %\\\n (rp[435], rz[435], rs[435], rd[435], rcic[435], rr[435],rn[435]))\n\n\n\n","sub_path":"WFIRST_SIM/ifs_noise_model.py","file_name":"ifs_noise_model.py","file_ext":"py","file_size_in_byte":11246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"393088306","text":"\n# coding: utf-8\n\n# In[1]:\n\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport unicodedata\n\nimport scipy.io\nimport numpy as np\n\nfrom PIL import Image\nimport progressbar\n\nfrom sklearn.cross_validation import StratifiedShuffleSplit\nimport skimage.transform\nimport cv2\n\nfrom time import sleep\n\nimport tensorflow as tf\n\n\n# In[2]:\n\nDIR = 'data'\nCAT_DIR = os.path.join(DIR, 'cat')\ncat_files = os.listdir(CAT_DIR)\n\nDOG_DIR = os.path.join(DIR,'dog')\ndog_files = os.listdir(DOG_DIR)\n \ndogs = len(dog_files) \ncats = len(cat_files)\n\nshape = np.shape(cv2.imread(os.path.join(CAT_DIR,cat_files[0])))\nprint (shape)\n\ndata = np.ndarray((cats+dogs,shape[0],shape[1],shape[2]),dtype = np.float32)\nlabel = np.ndarray((cats+dogs),dtype = np.uint8)\n\n\nprint (np.shape(data[0]))\n\nbar = progressbar.ProgressBar(maxval=cats+dogs, widgets=[progressbar.Bar('=','[',']'), ' ', \n progressbar.Percentage()])\nbar.start()\nimage_number = 0\nfor f in cat_files:\n temp = cv2.imread(os.path.join(CAT_DIR,f))\n data[image_number,:,:,:] = temp\n label[image_number] = 0 \n image_number +=1\n bar.update(image_number)\n\nfor f in dog_files:\n temp = cv2.imread(os.path.join(DOG_DIR,f))\n data[image_number,:,:,:] = temp\n label[image_number] = 1\n \n image_number +=1 \n \n bar.update(image_number)\nbar.finish() \n\n\n# In[3]:\n\nsss = StratifiedShuffleSplit(label, 1, 0.2)\nfor train_index, test_index in sss:\n print (len(train_index))\n print ((len(test_index)))\n print (train_index)\n train_images = data[train_index]\n test_images = data[test_index]\n \n train_labels = label[train_index]\n test_labels = label[test_index]\n\nsss= StratifiedShuffleSplit(test_labels,1,0.5)\nfor test_index, valid_index in sss:\n valid_images = test_images[valid_index]\n valid_labels = test_labels[valid_index]\n \n test_images = test_images[test_index]\n test_labels = test_labels[test_index]\n\nprint (len(train_images))\nprint (len(train_labels))\n\nprint (len(test_images))\nprint (len(test_labels))\n\nprint (len(valid_images))\nprint (len(valid_labels))\n\n\n# In[5]:\n\ndata =1\nlabel =1 \n\n\n# In[8]:\n\n\n\n\n# In[7]:\n\ndef convert_TFR(dataset, name):\n images = dataset[0]\n labels = dataset[1]\n assert len(images) == len(labels)\n num_examples = len(images)\n rows = images.shape[1]\n cols = images.shape[2]\n depth = images.shape[3]\n\n def _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n def _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n filename = os.path.join(DIR, name + '.tfrecords')\n print ('Writing', filename)\n writer = tf.python_io.TFRecordWriter(filename)\n for index in range(num_examples):\n image_raw = images[index].tostring()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'height': _int64_feature(rows),\n 'width': _int64_feature(cols),\n 'depth': _int64_feature(depth),\n 'label': _int64_feature(int(labels[index])),\n 'image_raw': _bytes_feature(image_raw)}))\n writer.write(example.SerializeToString())\n writer.close()\n\n\n# In[ ]:\n\nconvert_TFR((train_images, train_labels), 'train')\nconvert_TFR((valid_images, valid_labels), 'valid')\nconvert_TFR((test_images, test_labels), 'test') \n\n","sub_path":"QueueRunners.py","file_name":"QueueRunners.py","file_ext":"py","file_size_in_byte":3403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"610147102","text":"from __future__ import print_function\nimport itertools\nimport numpy\nimport copy\noptions = ['active','standby','being repaired']\nunitNum = [3,4,3,3]\n#unitNum = [2,3,2,3]\nfailureModes = [['rotor','bearing','Gearbox','LubeOil','motorBearing','motor'],#MAC\n['generalFailure'],#PPF\n['rotor','bearing','Gearbox','LubeOil','motorBearing','motor'],#BAC\n['generalFailure']]#LO2 PUMP\n#general basic tool (public)\ndef printSquareMatrix(mat):\n output = str() \n for i in range(len(mat)):\n output += '\\t'+str(i+1)\n #output += '\\n'+'-'*len(mat)*8\n output += '\\n'\n\n for i in range(len(mat)):\n output += str(i+1)+'\\t'\n for ele in mat[i]:\n output += str(ele)+'\\t'\n output += '\\n'\n return output\n\ndef almostIs(a,b):\n if abs(a-b) < 0.000001:\n return True\n\ndef calEyeDim(k,tMatrixDimList):\n dimG = 1\n dimL = 1\n for l in range(k+1,len(tMatrixDimList)):\n dimG *= tMatrixDimList[l]\n for l in range(k):\n dimL *= tMatrixDimList[l]\n return (dimG, dimL)\n\ndef putogether(matrixList):\n length = 0\n for mat in matrixList:\n length += len(mat)\n diagMatrix = [[0]*length for i in range(length)]\n marker = 0\n for mat in matrixList:\n for row in range(len(mat)):\n for col in range(len(mat)):\n diagMatrix[marker+row][marker+col] = mat[row][col]\n marker += len(mat)\n return diagMatrix\n\ndef listMatrix(mat):\n output = str()\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n if mat[i][j] == 0:\n continue\n else:\n output += 'WM(\"%s\",\"%s\") = %.5f; \\n' %(str(i+1), str(j+1), mat[i][j])\n return output\n\n#matrix value assign (public)\ndef transit(k, stateFrom, stateTo, parameters):#locate failure mode\n def isFailure():#The transition is caused by a failure\n if not (stateFrom[:origAct] == stateTo[:origAct] \n and stateFrom[newAct+1:] == stateTo[newAct+1:]\n and stateFrom[newAct]=='standby'\n and stateTo[origAct] in failureModes[k]):\n return False\n for i in range(origAct+1,newAct):\n if not stateFrom[i] == stateTo[i]:\n return False\n return True\n\n def standbyIsRepaired():#The transition is caused by a failed unit being repaired and turn to a standby\n fromChange = []\n toChange = []\n repairedIndex = None\n for i in range(len(stateFrom)): \n if stateFrom[i] != stateTo[i]:\n fromChange.append(stateFrom[i])\n toChange.append(stateTo[i])\n repairedIndex = i\n if not (len(fromChange)==1 and fromChange[0] in failureModes[k] and toChange == ['standby']):\n return None\n else:\n return repairedIndex\n\n\n def activeIsRepaired():#The transition is caused by a failed unit being repaired and turn to active, \n if not (stateFrom[newAct] in failureModes[k] and stateTo[origAct] == 'standby'):\n return False\n stateFrom_other = stateFrom[:newAct]+stateFrom[newAct+1:origAct]+stateFrom[origAct+1:]\n stateTo_other = stateTo[:newAct]+stateTo[newAct+1:origAct]+stateTo[origAct+1:]\n if not (stateFrom_other == stateTo_other):\n return False\n return True\n #--------------------------------------------------------------------- \n\n if ('active' not in stateFrom) and ('active' not in stateTo):#Both are all-down states, not communicating\n return None\n if 'active' not in stateTo:#change to all-down state:last active went down (have to check if it turns to repair or infeasible transition)\n if 'standby' in stateFrom:\n return None\n else:\n origAct = stateFrom.index('active')\n if ((stateTo[0:origAct] == stateFrom[0:origAct]) \n and (stateTo[origAct+1:] == stateFrom[origAct+1:])):\n if stateTo[origAct] in failureModes[k]:\n failInd = failureModes[k].index(stateTo[origAct])\n return parameters['lambdas'][origAct][failInd]\n else:\n return None\n if 'active' not in stateFrom:#change from all-down state: have to check if it's repaired or infeasible transition\n if 'standby' in stateTo:\n return None\n else:\n newAct = stateTo.index('active')\n if ((stateFrom[0:newAct] == stateTo[0:newAct]) \n and (stateTo[newAct+1:] == stateFrom[newAct+1:])):\n if stateFrom[newAct] in failureModes[k]:\n failInd = failureModes[k].index(stateFrom[newAct])\n return parameters['mus'][newAct][failInd]\n else:\n return None\n elif ('active' in stateFrom and 'active' in stateTo):#other normal states\n origAct = stateFrom.index('active');newAct = stateTo.index('active')\n if origAct < newAct:#might be breakdown happens\n if isFailure():\n failInd = failureModes[k].index(stateTo[origAct])\n value = parameters['lambdas'][origAct][failInd]\n #print(stateFrom, stateTo, value)\n return value\n else:\n return None\n elif origAct == newAct:#might be a unit repaired to become standby\n repairedIndex = standbyIsRepaired()\n if repairedIndex != None:\n failInd = failureModes[k].index(stateFrom[repairedIndex])\n value = parameters['mus'][repairedIndex][failInd]\n #print(stateFrom, stateTo, value)\n return value\n else:\n return None\n elif origAct > newAct:#might be a unit repaired to become active\n if activeIsRepaired():\n failInd = failureModes[k].index(stateFrom[newAct])\n value = parameters['mus'][newAct][failInd]\n #print(stateFrom, stateTo, value)\n return value\n else:\n return None\ndef transit2(k, stateFrom, stateTo, parameters):\n def isFailure():#The transition is caused by a failure\n if not (stateFrom[:origAct] == stateTo[:origAct] \n and stateFrom[newAct+1:] == stateTo[newAct+1:]\n and stateFrom[newAct]=='standby'\n and stateTo[origAct] in failureModes[k]):\n return False\n for i in range(origAct+1,newAct):\n if not stateFrom[i] == stateTo[i]:\n return False\n return True\n\n def standbyIsRepaired():#The transition is caused by a failed unit being repaired and turn to a standby\n fromChange = []\n toChange = []\n repairedIndex = None\n for i in range(len(stateFrom)): \n if stateFrom[i] != stateTo[i]:\n fromChange.append(stateFrom[i])\n toChange.append(stateTo[i])\n repairedIndex = i\n if not (fromChange in failureModes[k] and toChange == ['standby']):\n return None\n else:\n return repairedIndex\n\n\n def activeIsRepaired():#The transition is caused by a failed unit being repaired and turn to active\n if not (stateFrom[newAct] in failureModes[k] and stateTo[origAct] == 'standby'):\n return False\n for i in range(origAct+1,len(stateFrom)):\n if not (stateFrom[i]==stateTo[i]):\n return False\n return True\n #--------------------------------------------------------------------- \n\n if (stateFrom.count('active')<2) and (stateTo.count('active')<2):#Both are fail states, not communicating\n return None\n if stateTo.count('active')<2:#jump to fail state\n if 'standby' in stateFrom:\n return None\n else:\n compare = [stateTo[i] != stateFrom[i] for i in range(len(stateTo))]\n if sum(compare) == 1:\n failUnit = compare.index(True)\n failInd = failureModes[k].index(stateTo[failUnit])\n return parameters['lambdas'][failUnit][failInd]\n else:\n return None\n if stateFrom.count('active')<2:#jump from fail state\n if 'standby' in stateTo:\n return None\n else:\n compare = [stateTo[i] != stateFrom[i] for i in range(len(stateTo))]\n if sum(compare) == 1:\n repairedUnit = compare.index(True)\n failInd = failureModes[k].index(stateFrom[repairedUnit])\n return parameters['mus'][repairedUnit][failInd]\n else:\n return None\n elif (stateFrom.count('active')>=2) and (stateTo.count('active')>=2):#other normal states\n if stateFrom.count('standby') > stateTo.count('standby'):#failure\n origAct = [index for index, value in enumerate(stateFrom) if value == 'active']\n newAct = [index for index, value in enumerate(stateTo) if value == 'active']\n compareRepair = [stateTo[i]=='generalFailure' for i in origAct]\n compareStandby = [stateFrom[i]=='standby' for i in newAct]\n #print(compareRepair)\n if (sum(compareRepair)==1 and sum(compareStandby)==1):\n return parameters['lambdas'][origAct[compareRepair.index(True)]][0]\n else:\n origAct = [index for index, value in enumerate(stateFrom) if value == 'active']\n newAct = [index for index, value in enumerate(stateTo) if value == 'active']\n compareStandby = [stateTo[i]=='standby' for i in origAct]\n compareRepair = [stateFrom[i]=='generalFailure' for i in newAct]\n if (sum(compareRepair)==1 and sum(compareStandby)==1):\n return parameters['mus'][newAct[compareRepair.index(True)]][0]\n\ndef isValidState(state):#decide whether a state is valid\n if (('standby' in state) and ('active' in state) and (state.index('standby') 1:\n return False\n if ('active' not in state and 'standby' in state):\n return False\n #if (len(state)>=3 and state[-1] == 'being repaired'):#remove low probability scenarios in single failure mode stages\n # return False\n return True\n\ndef isValidState2(state):\n if len(state) < 2:#at least 2 units\n return False\n if state.count('active') > 2:#at most 2 active units\n return False\n if state.count('being repaired') > len(state)-1:#at most 2 active units\n return False\n if (('standby' in state) and (state.count('active')<=1)):#if there's standby, at least 2 units are good\n return False\n if (('standby' in state) and (state.count('active')>=2)):\n standbyPos = state.index('standby')\n actPos = [index for index, value in enumerate(state) if value == 'active']\n for ele in actPos:\n if standbyPos < ele:\n return False\n #if (state.count('being repaired') >= len(state)):#scenario reduction\n # return False \n #if (state.count('being repaired') >= 2 and state.index('active') != 0):\n # return False \n\n return True\ndef generateTMatrix(k, design, parameter):#for selected design of stage k\n states = list()\n statesToEliminate = [state for state in \n list(itertools.product(failureModes[0], repeat = 2))+[('active','motorBearing'),('active','Gearbox'),\n ('active','LubeOil'),('active','rotor'),('active','bearing')] if state not in [('motor','motor')]]\n if k == 1:\n for state in itertools.product(options, repeat = sum(design)):\n if isValidState2(state):\n stateSuite = dict()\n if 'being repaired' not in state:\n stateSuite['name'] = state\n stateSuite['isFailure'] = 0\n #stateSuite['design'] = design\n states.append(stateSuite)\n else:#replace 'being repaired' with failure modes\n failNum = state.count('being repaired')\n replacements = itertools.product(failureModes[k], repeat = failNum)\n for replacement in replacements:\n replacement = list(replacement)\n newState = list()\n for s in state:\n if s == 'being repaired':\n newState.append(replacement.pop())\n else:\n newState.append(s)\n newState = tuple(newState)\n if newState not in statesToEliminate: \n stateSuite['name'] = newState\n stateSuite['isFailure'] = 1 if failNum==sum(design)-1 else 0\n #stateSuite['design'] = design\n states.append(stateSuite)\n else:\n for state in itertools.product(options, repeat = sum(design)):\n if isValidState(state):\n if 'being repaired' not in state:\n stateSuite = dict()\n stateSuite['name'] = state\n stateSuite['isFailure'] = 0\n #stateSuite['design'] = design\n states.append(stateSuite)\n else:#replace 'being repaired' with failure modes\n failNum = state.count('being repaired')\n replacements = itertools.product(failureModes[k], repeat = failNum)\n for replacement in replacements:\n replacement = list(replacement)\n newState = list()\n for s in state:\n if s == 'being repaired':\n newState.append(replacement.pop())\n else:\n newState.append(s)\n newState = tuple(newState)\n if newState not in statesToEliminate: \n stateSuite = dict() \n stateSuite['name'] = newState\n stateSuite['isFailure'] = 1 if failNum==sum(design) else 0\n #stateSuite['design'] = design\n states.append(stateSuite)\n\n selectParameters = dict()\n for rate in parameter:#parameter like {'lambdas':[[],[],..],'mus':[[],[],..]}\n selectParameters[rate] = list()\n for j in range(len(design)):\n if design[j] == 1:\n selectParameters[rate].append(parameter[rate][j])\n selectParameters[rate] = tuple(selectParameters[rate])\n\n matrix = [[0]*len(states) for i in range(len(states))]\n if k == 1:\n for i in range(len(states)):\n stateFrom = states[i]['name']\n for j in range(len(states)):\n stateTo = states[j]['name']\n value = transit2(k,stateFrom, stateTo, selectParameters)\n matrix[i][j] = 0 if value is None else value\n else:\n for i in range(len(states)):\n stateFrom = states[i]['name']\n for j in range(len(states)):\n stateTo = states[j]['name']\n value = transit(k,stateFrom, stateTo, selectParameters)\n matrix[i][j] = 0 if value is None else value\n return (matrix,states)\n\ndef generatePseudoTMatrix(k, level, parameter):#for stage k, total number of units = level\n numOfUnit = unitNum[k]#total number of potential units\n alters = itertools.combinations(range(numOfUnit), level)#all combinations of this level\n matrixList = list()\n stateList = list()\n for alter in alters:\n design = [0] * numOfUnit\n for element in alter:\n design[element] = 1\n print(design)\n matrix, states = generateTMatrix(k,design,parameter)\n #for stage in states:\n #print(stage)\n #print('---------------------------------------------------')\n #for i in range(len(matrix)):\n #for j in range(len(matrix[i])):\n #print(matrix[i][j],end=' ')\n #print(';\\n')\n matrixList.append(matrix)\n stateList.append(states)\n return matrixList, stateList\n\ndef calTmatrices(parameters):#include all stage\n def calTmatrix(k, parameter):#for only stage k\n largeDiagMatrix = list()\n for i in range(unitNum[k]):\n largeDiagMatrix.append(generatePseudoTMatrix(k, i+1 ,parameter))\n tmatrix = putogether(largeDiagMatrix)\n return tmatrix\n\n tMatrixList = list()\n tMatrixDimList = list()\n for k in range(len(parameters)):\n tMatrixList.append(calTmatrix(k, parameters[k]))\n tMatrixDimList.append(len(tMatrixList[k]))\n return (tMatrixList,tMatrixDimList)\n\n\ndef readDesigns(fileDesign):\n designs = [[]*1 for i in range(len(unitNum))]\n f = open(fileDesign,'r')\n designString = f.read()[:-1]\n f.close()\n designList = designString.split('\\n')\n for i in range(len(designList)):\n designList[i] = designList[i].replace('\"', '').split(',')\n stageNum = int(designList[i][0])\n y = int(float(designList[i][2]))\n designs[stageNum-1].append(y)\n return designs\n\n\n###########################################################################################\n \n###########################################################################################\n\n\ndef savePastResult(filePrime, filePrimeOld, fileCounting, var):\n f1 = open(filePrime,'r')\n toSave = f1.read()\n f1.close()\n toSaveList = toSave.split(var+'(')\n fc = open(fileCounting,'r')\n num = fc.read()\n fc.close()\n newHead = var+'(\"'+num+'\",'\n toSave = newHead.join(toSaveList)\n f2 = open(filePrimeOld,'a')\n f2.write(toSave)\n f2.close()\n\n\ndef convertResultToParameter(file,filePrime,var):\n f1 = open(file,'r')\n String = f1.read()[:-1]#remove the last '\\n'\n f1.close()\n List = String.split('\\n')\n output = str()\n for i in range(len(List)):\n List[i] = List[i].replace('\"', '').split(',')#each item becomes a list looking like k,j,value\n index1 = int(List[i][0])\n index2 = int(List[i][1])\n value = int(float(List[i][2]))\n output += var + '(\"%s\",\"%s\") = %s; \\n' %(index1, index2, value)\n f = open(filePrime, 'w')\n f.write(output)\n f.close()\n\n\n\n'''\ndef calQMatrix(tMatrixList,tMatrixDimList):\n preQMatrix = list()\n for k in range(len(tMatrixList)):\n (dimG,dimL) = calEyeDim(k, tMatrixDimList)\n preQMatrix.append(numpy.kron(numpy.identity(dimG),numpy.kron(tMatrixList[k], numpy.identity(dimL))))#matrix is too large\n for k in range(1,len(preQMatrix)):\n for row in range(len(preQMatrix[0])):\n for col in range(len(preQMatrix[0][0])):\n preQMatrix[0][row][col] += preQMatrix[k][row][col]\n qmatrix = copy.deepcopy(preQMatrix[0])\n for row in range(len(qmatrix)):\n for col in range(len(qmatrix[row])):\n qmatrix[row][col] = round(qmatrix[row][col],5)\n qmatrix[row][row] = -sum(qmatrix[row])\n return qmatrix\n'''\n\n\n\n\n'''\ndef locateTMatrix(design, options, parameter):#put the Tmatrix to its designated place in the pseudoTmatrix \n originalMatrix, originalStates = generateTMatrix(design, options, parameter)\n numOfUnit = len(parameter['lambdas'])\n alters = list() \n for level in range(1,numOfUnit+1):\n alters += list(itertools.combinations(range(numOfUnit), level))\n designs = list()\n statesBefore = list()\n for alter in alters:\n currDesign = [0] * numOfUnit\n for element in alter:\n currDesign[element] = 1\n if currDesign != design:#currDesign must have fewer or same number of units as design \n for state in itertools.product(options, repeat = sum(currDesign)):\n if isValidState(state):\n statesBefore.append(state)\n else:#once the iteration reaches the design, stop\n break\n states = [None]*len(statesBefore)+originalStates\n print('original')\n print(originalMatrix)\n for i in range(len(originalMatrix)):\n originalMatrix[i] = [0]*len(statesBefore) + originalMatrix[i]\n matrix = [[0]*(len(statesBefore)+len(originalStates)) for i in range(len(statesBefore))] + originalMatrix\n return (matrix, states) \n'''\n\n\n'''def generatePseudoTMatrix(level, options, parameters):#include all combinations in one stage with same number of units\n #generate state products for the design of certain number of units\n print(parameters)\n states = list()\n for state in itertools.product(options, repeat = level):\n if isValidState(state):\n states.append(state)\n #apply the state products for all combinations of this number of units\n numOfUnit = len(parameters['lambdas'])#total number of potential units\n alters = itertools.combinations(range(numOfUnit), level)#all combinations of this level (number of units in the design)\n matrixList = list()#prepare a matrix array\n for alter in alters:\n print(alter)\n #generate parameters for different combinations\n selectParameters = dict()\n for index in parameters:\n selectParameters[index] = []\n for i in alter:\n selectParameters[index].append(parameters[index][i])\n selectParameters[index] = tuple(selectParameters[index])\n\n matrix = [[0]*len(states) for i in range(len(states))]\n for i in range(len(states)):\n stateFrom = states[i]\n for j in range(len(states)):\n stateTo = states[j]\n value = transit(stateFrom, stateTo, selectParameters)\n matrix[i][j] = 0 if value is None else value\n matrixList.append(matrix)\n #print(matrixList)\n return putogether(matrixList)\n'''\n","sub_path":"original/research_supportFull.py","file_name":"research_supportFull.py","file_ext":"py","file_size_in_byte":21848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"321525016","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.6-x86_64/egg/bibolamazi_gui/qtauto/ui_sourcelisteditor.py\n# Compiled at: 2015-05-11 05:40:29\nfrom PyQt4 import QtCore, QtGui\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\n\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\n\n\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_SourceListEditor(object):\n\n def setupUi(self, SourceListEditor):\n SourceListEditor.setObjectName(_fromUtf8('SourceListEditor'))\n SourceListEditor.resize(377, 362)\n self.gridLayout = QtGui.QGridLayout(SourceListEditor)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.lstSources = QtGui.QListWidget(SourceListEditor)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.lstSources.sizePolicy().hasHeightForWidth())\n self.lstSources.setSizePolicy(sizePolicy)\n self.lstSources.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)\n self.lstSources.setDragDropMode(QtGui.QAbstractItemView.InternalMove)\n self.lstSources.setObjectName(_fromUtf8('lstSources'))\n self.gridLayout.addWidget(self.lstSources, 2, 0, 1, 2)\n self.gbxEditSource = QtGui.QGroupBox(SourceListEditor)\n self.gbxEditSource.setObjectName(_fromUtf8('gbxEditSource'))\n self.gridLayout_2 = QtGui.QGridLayout(self.gbxEditSource)\n self.gridLayout_2.setVerticalSpacing(12)\n self.gridLayout_2.setObjectName(_fromUtf8('gridLayout_2'))\n self.lblFile = QtGui.QLabel(self.gbxEditSource)\n self.lblFile.setObjectName(_fromUtf8('lblFile'))\n self.gridLayout_2.addWidget(self.lblFile, 0, 0, 1, 1)\n self.txtFile = QtGui.QLineEdit(self.gbxEditSource)\n self.txtFile.setObjectName(_fromUtf8('txtFile'))\n self.gridLayout_2.addWidget(self.txtFile, 1, 0, 1, 2)\n self.btnBrowse = QtGui.QPushButton(self.gbxEditSource)\n self.btnBrowse.setObjectName(_fromUtf8('btnBrowse'))\n self.gridLayout_2.addWidget(self.btnBrowse, 0, 1, 1, 1)\n self.gridLayout.addWidget(self.gbxEditSource, 6, 0, 1, 2)\n self.btnAddSource = QtGui.QPushButton(SourceListEditor)\n self.btnAddSource.setObjectName(_fromUtf8('btnAddSource'))\n self.gridLayout.addWidget(self.btnAddSource, 3, 0, 1, 1)\n self.btnRemoveSource = QtGui.QPushButton(SourceListEditor)\n self.btnRemoveSource.setObjectName(_fromUtf8('btnRemoveSource'))\n self.gridLayout.addWidget(self.btnRemoveSource, 3, 1, 1, 1)\n spacerItem = QtGui.QSpacerItem(10, 5, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)\n self.gridLayout.addItem(spacerItem, 5, 0, 1, 1)\n self.label_2 = QtGui.QLabel(SourceListEditor)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.gridLayout.addWidget(self.label_2, 4, 0, 1, 2)\n self.horizontalLayout = QtGui.QHBoxLayout()\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.label = QtGui.QLabel(SourceListEditor)\n self.label.setObjectName(_fromUtf8('label'))\n self.horizontalLayout.addWidget(self.label)\n self.btnAddFavorite = QtGui.QToolButton(SourceListEditor)\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(':/pic/bookmark.png')), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.btnAddFavorite.setIcon(icon)\n self.btnAddFavorite.setObjectName(_fromUtf8('btnAddFavorite'))\n self.horizontalLayout.addWidget(self.btnAddFavorite)\n self.gridLayout.addLayout(self.horizontalLayout, 1, 0, 1, 2)\n self.retranslateUi(SourceListEditor)\n QtCore.QMetaObject.connectSlotsByName(SourceListEditor)\n\n def retranslateUi(self, SourceListEditor):\n SourceListEditor.setWindowTitle(_translate('SourceListEditor', 'Form', None))\n self.lstSources.setToolTip(_translate('SourceListEditor', '\\n\\n

    List of sources to collect bibliographic entries. Reorder entries by Drag&Drop. Remember that the first existing file of each source list will be read.

    ', None))\n self.gbxEditSource.setTitle(_translate('SourceListEditor', 'Edit this source', None))\n self.lblFile.setText(_translate('SourceListEditor', 'File or URL:', None))\n self.btnBrowse.setText(_translate('SourceListEditor', 'browse file ...', None))\n self.btnAddSource.setText(_translate('SourceListEditor', 'Add Source', None))\n self.btnRemoveSource.setText(_translate('SourceListEditor', 'Remove this source', None))\n self.label_2.setText(_translate('SourceListEditor', '(reorder sources by drag and drop)', None))\n self.label.setText(_translate('SourceListEditor', 'Source List: (first accessible will be used)', None))\n self.btnAddFavorite.setToolTip(_translate('SourceListEditor', 'Add this source list to your favorites', None))\n return\n\n\nfrom . import bibolamazi_res_rc","sub_path":"pycfiles/bibolamazi_gui-3.0beta3-py2.7/ui_sourcelisteditor.py","file_name":"ui_sourcelisteditor.py","file_ext":"py","file_size_in_byte":5915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"239392931","text":"# Fractal Analytics\ndef arrangeCoins(coins):\n for c in coins:\n last = 1\n for i in range(c, 1, -1):\n if 2*c < i*i + i:\n last = i\n print(last - 1)\n\n\narrangeCoins([2, 5, 8, 3])\narrangeCoins([6])\n","sub_path":"arranging_coins.py","file_name":"arranging_coins.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"493346913","text":"#ajuda interativa\n#help(input)\n#outra maneira\n#print(input.__doc__)\n#docstring: string de documentação\n#def cont(i,f,p):\n #docstring cont\n #\"\"\"\n #->Faz uma contagem e mostra na tela\n #:param i: inicio da contagem\n #:param f: fim da contagem\n #:param p: progressão ou passo da contagem\n #:return: sem retorno\n #\"\"\"\n #c = i\n #while c <= f:\n #print(f\"{c} \", end='')\n #c += p\n #print(\"FIM\")\n#parâmetros opcionais:\n#def soma(a, b, c=0):\n# s = a + b + c\n # print(s)\n#def funcao():\n #global n1 usa a val global em vez de criar uma local\n# n1 = 4\n# print(\"N1 dentro vale\", n1)\n#retornar valores\n#def soma(a=0, b=0, c=0):\n# s = a + b + c\n# return s\n\n#help(cont)\n#r1 =soma(5, 6, 2)\n#r2 =soma(9, 2)\n#r3 =soma(7)\n#print(f\"Os resultados foram {r1}, {r2}, {r3}\")\n#n1 = 2\n#funcao()\n#print(\"N1 fora vale\", n1)\ndef fatorial(num=1):\n f = 1\n for c in range(num, 0, -1):\n f *= c\n return f\n\n\nn = int(input(\"Número: \"))\nprint(f\"O fatorial de {n} é {fatorial(n)}\")\n","sub_path":"ExCursoEmVídeo(Python)/aula21.py","file_name":"aula21.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"28192603","text":"from flask import Flask, request, redirect, render_template, url_for, flash\nfrom flask_sqlalchemy import SQLAlchemy\nimport os\n\napp = Flask(__name__)\n\napp.config.from_object(os.environ[\"APP_SETTINGS\"])\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\ndb = SQLAlchemy(app)\n\nfrom models import tmpUsers\nfrom forms import RegistrationForm, LoginForm\nfrom functions import user_check\n\n\n@app.route(\"/\")\ndef root():\n return redirect(url_for(\"login\"))\n\n@app.route(\"/login\", methods=['GET','POST'])\ndef login():\n failed = request.args.get('failed')\n form = LoginForm(request.form)\n if request.method == 'POST' and form.validate():\n if not user_check(form.username.data):\n return redirect(url_for('login', failed=True))\n #check\n flash(\"Logged In\")\n return redirect(url_for(\"registeredlist\"))\n return render_template('unauth/login/login.html', form=form, failed_login=failed)\n\n@app.route(\"/register\", methods=[\"GET\", \"POST\"])\ndef register():\n failed = request.args.get('failed')\n form = RegistrationForm(request.form)\n if request.method == \"POST\" and form.validate():\n if user_check(form.username.data):\n return redirect(url_for('register', failed=True))\n tmpUsers.insert(name=form.username.data)\n flash(\"Thanks for registering\")\n return redirect(url_for(\"registeredlist\"))\n return render_template(\"unauth/register/register.html\", form=form, failed_registration=failed)\n\n\n@app.route(\"/registeredlist\", methods=[\"GET\"])\ndef registeredlist():\n users = tmpUsers.get()\n users = [user.name for user in users]\n print(users)\n return render_template(\"unauth/register/list.html\", users=users)\n\n@app.route(\"/home\", methods=[\"GET\"])\ndef home():\n return render_template(\"auth/home/home.html\")\n","sub_path":"btp-web/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"497116684","text":"import resDisk\nimport os\nimport json\nimport rcStatus\nimport rcExceptions as ex\nfrom rcGlobalEnv import *\nfrom rcUtilities import justcall\nimport rcGce\n\nclass Disk(resDisk.Disk, rcGce.GceMixin):\n def __init__(self,\n rid=None,\n type=\"disk.gce\",\n names=set(),\n gce_zone=None,\n **kwargs):\n\n resDisk.Disk.__init__(self,\n rid=rid,\n type=type,\n **kwargs)\n\n self.names = names\n self.gce_zone = gce_zone\n self.label = self.fmt_label()\n\n def get_disk_names(self, refresh=False):\n data = self.get_disks(refresh=refresh)\n return [d[\"name\"] for d in data]\n\n def get_attached_disk_names(self, refresh=False):\n data = self.get_attached_disks(refresh=refresh)\n return [d[\"name\"] for d in data]\n\n def get_attached_disks(self, refresh=False):\n if hasattr(self.svc, \"gce_attached_disks\") and not refresh:\n return self.svc.gce_attached_disks\n self.wait_gce_auth()\n cmd = [\"gcloud\", \"compute\", \"instances\", \"describe\", rcEnv.nodename, \"--format\", \"json\", \"--zone\", self.gce_zone]\n out, err, ret = justcall(cmd)\n data = json.loads(out)\n data = data.get(\"disks\", [])\n for i, d in enumerate(data):\n data[i][\"name\"] = d[\"source\"].split(\"/\")[-1]\n self.svc.gce_attached_disks = data\n return self.svc.gce_attached_disks\n\n def get_disks(self, refresh=False):\n if hasattr(self.svc, \"gce_disks\") and not refresh:\n return self.svc.gce_disks\n self.wait_gce_auth()\n cmd = [\"gcloud\", \"compute\", \"disks\", \"list\", \"--format\", \"json\", \"--zone\", self.gce_zone]\n out, err, ret = justcall(cmd)\n data = json.loads(out)\n self.svc.gce_disks = data\n return data\n\n def fmt_label(self):\n s = \"gce volumes \"\n s += \", \".join(self.names)\n return s\n\n def has_it(self, name):\n data = self.get_attached_disks()\n disk_names = [d.get(\"name\") for d in data]\n if name in disk_names:\n return True\n return False\n\n def up_count(self):\n data = self.get_attached_disks()\n disk_names = [d.get(\"name\") for d in data]\n l = []\n for name in self.names:\n if name in disk_names:\n l.append(name)\n return l\n\n def validate_volumes(self):\n existing = [d.get(\"name\") for d in self.get_disks()]\n non_exist = set(self.names) - set(existing)\n if len(non_exist) > 0:\n raise Exception(\"non allocated volumes: %s\" % ', '.join(non_exist))\n\n def _status(self, verbose=False):\n try:\n self.validate_volumes()\n except Exception as e:\n self.status_log(str(e))\n return rcStatus.WARN\n l = self.up_count()\n n = len(l)\n unattached = sorted(list(set(self.names) - set(l)))\n if n == len(self.names):\n return rcStatus.UP\n elif n == 0:\n return rcStatus.DOWN\n else:\n self.status_log(\"unattached: \"+\", \".join(unattached))\n return rcStatus.DOWN\n\n def detach_other(self, name):\n existing = self.get_disks()\n for d in existing:\n if d[\"name\"] != name:\n continue\n for user in d.get(\"users\", []):\n instance = user.split('/')[-1]\n if instance != rcEnv.nodename:\n self.vcall([\n \"gcloud\", \"compute\", \"instances\", \"detach-disk\", \"-q\",\n instance,\n \"--disk\", name,\n \"--zone\", self.gce_zone\n ])\n\n def do_start_one(self, name):\n existing = self.get_disk_names()\n if name not in existing:\n self.log.info(name+\" does not exist\")\n return\n attached = self.get_attached_disk_names()\n if name in attached:\n self.log.info(name+\" is already attached\")\n return\n\n self.detach_other(name)\n self.vcall([\n \"gcloud\", \"compute\", \"instances\", \"attach-disk\", \"-q\",\n rcEnv.nodename,\n \"--disk\", name,\n \"--zone\", self.gce_zone,\n \"--device-name\", self.fmt_disk_devname(name),\n ])\n self.can_rollback = True\n\n def do_start(self):\n for name in self.names:\n self.do_start_one(name)\n self.get_attached_disks(refresh=True)\n\n def do_stop_one(self, name):\n existing = self.get_disk_names()\n if name not in existing:\n self.log.info(name+\" does not exist\")\n return\n attached = self.get_attached_disk_names()\n if name not in attached:\n self.log.info(name+\" is already detached\")\n return\n self.vcall([\n \"gcloud\", \"compute\", \"instances\", \"detach-disk\", \"-q\",\n rcEnv.nodename,\n \"--disk\", name,\n \"--zone\", self.gce_zone\n ])\n\n def do_stop(self):\n for name in self.names:\n self.do_stop_one(name)\n self.get_attached_disks(refresh=True)\n\n def fmt_disk_devname(self, name):\n index = self.names.index(name)\n if self.svc.namespace:\n return \".\".join([self.svc.namespace.lower(), self.svc.name, self.rid.replace(\"#\", \".\"), str(index)])\n else:\n return \".\".join([self.svc.name, self.rid.replace(\"#\", \".\"), str(index)])\n\n def exposed_devs(self):\n attached = self.get_attached_disks()\n return set([\"/dev/disk/by-id/google-\"+d[\"deviceName\"] for d in attached if d[\"name\"] in self.names])\n\n def exposed_disks(self):\n attached = self.get_attached_disks()\n return set([d[\"deviceName\"] for d in attached if d[\"name\"] in self.names])\n\n","sub_path":"lib/resDiskGce.py","file_name":"resDiskGce.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"26210782","text":"\"\"\"mywebsite URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import *\nfrom django.conf import settings\nfrom django.contrib import admin\n\nurlpatterns = [\n \n url(r'^media/(?P.*)$', 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT,\n 'show_indexes' : True}),\n\n url(r'^rinos/', include(admin.site.urls)),\n\n\n url(r'^blog/view/(?P[^\\.]+).html', \n 'blog.views.view_post', \n name='view_blog_post'),\n\n url(r'^blog/category/(?P[^\\.]+).html', \n 'blog.views.view_category', \n name='view_blog_category'),\n\n url(r'^project/view/(?P[^\\.]+).html',\n 'project.views.view_post',\n name='view_project_post'),\n\n url(r'^project/category/(?P[^\\.]+).html',\n 'project.views.view_category',\n name='view_project_category'),\n\n url(r'^resume/', 'blog.views.pdf_view'),\n\n url(r'^project/', 'project.views.index'),\n url(r'^projects/', 'project.views.index'),\n\n\n url(r'^blog/', 'blog.views.index'),\n\n url(r'^$', 'blog.views.home_page', name='main'),\n\n url(r\"\", 'blog.views.handler404', name='404'),\n #url(r'^$', 'blog.views.index'),\n\n]\n","sub_path":"mywebsite/mywebsite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"436823848","text":"# can we change the self parameter inside a class to other name such as 'harry' or 'jayesh'\n\n\nclass sample: \n a = \"harry\" \n def __init__(jayesh, name):\n jayesh.name = name\n\nobj = sample(\"harry\")\nprint(obj.name) \n\n#yes we can change the 'self' identifier by other name\n# self is used for better understandability\n# otherwise we can changed it to any name\n \n","sub_path":"Chap10_oops/13.prac6.py","file_name":"13.prac6.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"203930693","text":"# =======================================================================================================\n# Global constants and variables related to Training sheet headings\n# =======================================================================================================\n\n# ===============================================================================================================\n#\n# Training Key Modules\n#\n# ===============================================================================================================\n\nCONTACT_NUMBER = \"membership_number\"\n\nFORENAMES = \"forenames\"\nSURNAME = \"surname\"\nPREFERRED = \"preferred\"\n\nEMAIL = \"email\"\nROLE = \"role\"\nROLE_START_DATE = \"role_start_date\"\nROLE_STATUS = \"role_status\"\nREVIEW_DATE = \"review_date\"\n\nWOOD_BADGE_DATE = \"wood_badge_date\"\n\nCOUNTRY = \"country\"\nREGION = \"region\"\nCOUNTY = \"county\"\nCOUNTY_SECTION = \"county_section\"\nDISTRICT = \"district\"\nDISTRICT_SECTION = \"district_section\"\nSCOUT_GROUP = \"scout_group\"\nSCOUT_GROUP_SECTION = \"scout_group_section\"\n\nMODULE = \"module\"\nVALIDATED_DATE = \"validated_date\"\n\nVALIDATED_BY = \"validated_by\"\nVALIDATED_BY_NAME = \"validated_by_name\"\nLEARNING_METHOD = \"learning_method\"\nLEARNING_METHOD_DATE = \"learning_method_date\"\nVALIDATION_CRITERIA = \"validation_criteria\"\nVALIDATION_CRITERIA_DATE = \"validation_criteria_date\"\nVALIDATOR_NAME = \"validator_name\"\n\nTRAINING_ADVISER = \"training_adviser\"\nTRAINING_ADVISER_NAME = \"training_adviser_name\"\n\n\nmodule_mod_1_ex = \"Essential Information for Exec Committee Members\"\nmodule_mod_1_ex_ended = \"Essen Info for Exec Committee Mems(ENDED Sept 20)\"\nmodule_mod_1_ex_ended2 = \"Essential Info for Exec Committee Mems(ENDED Sept)\"\nmodule_mod_4 = \"Tools for the Role (Managers and Supporters)\"\nmodule_gdpr = \"General Data Protection Regulations\"\n","sub_path":"src/assistants/training/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"322076759","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns=[\n path('',views.home,name=\"author\"),\n path('login/',views.author_login,name='author_login'),\n path('signup/',views.author_signup,name='author_signup'),\n path('add_book/',views.author_add_book,name=\"author_add_book\")\n]\n","sub_path":"dummy/author/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"590314465","text":"\"\"\"util.py\n\nChamplain College CSI-235, Spring 2018\nThe following code was adapted by Joshua Auerbach (jauerbach@champlain.edu)\nfrom the UC Berkeley Pacman Projects (see license and attribution below).\n\n----------------------\nLicensing Information: You are free to use or extend these projects for\neducational purposes provided that (1) you do not distribute or publish\nsolutions, (2) you retain this notice, and (3) you provide clear\nattribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n\nAttribution Information: The Pacman AI projects were developed at UC Berkeley.\nThe core projects and autograders were primarily created by John DeNero\n(denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\nStudent side autograding was added by Brad Miller, Nick Hay, and\nPieter Abbeel (pabbeel@cs.berkeley.edu).\n\"\"\"\n\n\nimport sys\nimport inspect\nimport heapq\nimport random\nimport io\n\n\ndef raise_not_defined():\n file_name = inspect.stack()[1][1]\n line = inspect.stack()[1][2]\n method = inspect.stack()[1][3]\n\n print(\"*** Method not implemented: %s at line %s of %s\" %\n (method, line, file_name))\n sys.exit(1)\n\n\ndef lookup(name, namespace):\n \"\"\"\n Get a method or class from any imported module from its name.\n Usage: lookup(function_name, globals())\n \"\"\"\n dots = name.count('.')\n if dots > 0:\n module_name, obj_name = '.'.join(\n name.split('.')[:-1]), name.split('.')[-1]\n module = __import__(module_name)\n return getattr(module, obj_name)\n else:\n modules = [obj for obj in list(namespace.values()) if str(\n type(obj)) == \"\"]\n options = [getattr(module, name)\n for module in modules if name in dir(module)]\n options += [obj[1]\n for obj in list(namespace.items()) if obj[0] == name]\n if len(options) == 1:\n return options[0]\n if len(options) > 1:\n raise Exception('Name conflict for %s')\n raise Exception('%s not found as a method or class' % name)\n\n\ndef pause():\n \"\"\"\n Pauses the output stream awaiting user feedback.\n \"\"\"\n print(\"\")\n input()\n\n\n# code to handle timeouts\n#\n# FIXME\n# NOTE: TimeoutFuncton is NOT reentrant. Later timeouts will silently\n# disable earlier timeouts. Could be solved by maintaining a global list\n# of active time outs. Currently, questions which have test cases calling\n# this have all student code so wrapped.\n#\nimport signal\nimport time\n\n\nclass TimeoutFunctionException(Exception):\n \"\"\"Exception to raise on a timeout\"\"\"\n pass\n\n\nclass TimeoutFunction:\n def __init__(self, function, timeout):\n self.timeout = timeout\n self.function = function\n\n def handle_timeout(self, signum, frame):\n raise TimeoutFunctionException()\n\n def __call__(self, *args, **kargs):\n # If we have SIGALRM signal, use it to cause an exception if and\n # when this function runs too long. Otherwise check the time taken\n # after the method has returned, and throw an exception then.\n if hasattr(signal, 'SIGALRM'):\n old = signal.signal(signal.SIGALRM, self.handle_timeout)\n signal.alarm(self.timeout)\n try:\n result = self.function(*args, **kargs)\n finally:\n signal.signal(signal.SIGALRM, old)\n signal.alarm(0)\n else:\n start_time = time.time()\n result = self.function(*args, **kargs)\n time_elapsed = time.time() - start_time\n if time_elapsed >= self.timeout:\n self.handle_timeout(None, None)\n return result\n\n\n_ORIGINAL_STDOUT = None\n_ORIGINAL_STDERR = None\n_MUTED = False\n\n\nclass WritableNull:\n def write(self, string):\n pass\n\n\ndef mute_print():\n global _ORIGINAL_STDOUT, _ORIGINAL_STDERR, _MUTED\n if _MUTED:\n return\n _MUTED = True\n\n _ORIGINAL_STDOUT = sys.stdout\n #_ORIGINAL_STDERR = sys.stderr\n sys.stdout = WritableNull()\n #sys.stderr = WritableNull()\n\n\ndef unmute_print():\n global _ORIGINAL_STDOUT, _ORIGINAL_STDERR, _MUTED\n if not _MUTED:\n return\n _MUTED = False\n\n sys.stdout = _ORIGINAL_STDOUT\n #sys.stderr = _ORIGINAL_STDERR\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190608795","text":"# -*- coding: utf-8 -*-\n'''\n ユーザ定義例外基底クラス\n'''\nclass UserDefinitionException(Exception):\n\tdef __init__(self):\n\t\tException.__init__(self)\n\t\tself.messageId = 'err900'\n\t\tself.params = []\n\t\t\n'''\n ファイル存在チェックエラー\n @param filePath: ファイルパス\n'''\nclass ConfNotExist(UserDefinitionException):\n def __init__(self, conf_name):\n UserDefinitionException.__init__(self)\n self.messageId = 'err001'\n self.params = [conf_name]\n\n\n\n'''\n ファイル存在チェックエラー\n @param filePath: ファイルパス\n'''\nclass FileExist(UserDefinitionException):\n\tdef __init__(self, filePath):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err001'\n\t\tself.params = [filePath]\n\n'''\n ファイル存在チェックエラー\n @param filePath: ファイルパス\n'''\nclass FileNotExist(UserDefinitionException):\n\tdef __init__(self, filePath):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err002'\n\t\tself.params = [filePath]\n\n'''\n フォルダ存在チェックエラー\n @param dirPath: フォルダパス\n'''\nclass DirNotExist(UserDefinitionException):\n\tdef __init__(self, dirPath) :\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err003'\n\t\tself.params = [dirPath]\n\n'''\n パラメータ不正\n @param targetValue: 対象\n @param result: 結果\n'''\nclass InvalidParameter(UserDefinitionException):\n\tdef __init__(self, targetValue, result):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err004'\n\t\tself.params = [targetValue, result]\n\n'''\n データベース接続エラー\n @param connectionInfo: 接続情報\n @param errorCode: エラーコード\n @param errorMessage: エラーメッセージ\n'''\nclass DBConnectError(UserDefinitionException):\n\tdef __init__(self, connectionInfo, errorCode, errorMessage):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err005'\n\t\t\n\t\t# パスワードは出力対象外とする\n\t\tif 'password' in connectionInfo:\n\t\t\tconnectionInfo = connectionInfo[0:connectionInfo.find('password')-1]\n\t\t\n\t\tself.params = [connectionInfo, errorCode, errorMessage]\n\n'''\n SQL実行エラー\n @param sqlText: 実行SQL文\n @param errorCode: エラーコード\n @param errorMessage: エラーメッセージ\n'''\nclass SQLError(UserDefinitionException):\n\tdef __init__(self, sqlText, errorCode, errorMessage):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err006'\n\t\tself.params = [sqlText, errorCode, errorMessage]\n\n'''\n コマンド実行エラー\n @param commandText: 実行コマンド\n @param consoleText: 標準出力+標準エラー\n'''\nclass CommandError(UserDefinitionException):\n\tdef __init__(self, commandText, consoleText):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err007'\n\t\tself.params = [commandText, consoleText]\n\t\n'''\n 整合性チェックエラー\n @param tableCount: テーブル件数\n @param fileCount: レコード件数\n'''\t\t\t\nclass IntegrityCheckCountError(UserDefinitionException):\n\tdef __init__(self, tableCount, fileCount):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err008'\n\t\tself.params = [tableCount, fileCount]\n'''\n テンプレート置換パラメータ数不正\n @param filePath: ファイルパス\n'''\nclass IllegalParameterCount(UserDefinitionException):\n\tdef __init__(self, replaceCount, paramsCount):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err009'\n\t\tself.params = [replaceCount, paramsCount]\n'''\n パラメータ不正\n @param targetValue: 対象\n @param result: 結果\n'''\nclass InvalidValue(UserDefinitionException):\n\tdef __init__(self, targetValue, result):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err010'\n\t\tself.params = [targetValue, result]\t\n'''\n 設定ファイル読み込みエラー\n @param configFilePath: configファイルパス\n @param message: 結果\n'''\nclass ConfigFileLoadError(UserDefinitionException):\n\tdef __init__(self, configFilePath, message):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err011'\n\t\tself.params = [configFilePath, message]\n'''\n 複数ファイル存在エラー\n @param files: ファイル名をカンマ区切り\n'''\nclass MultipleFiles(UserDefinitionException):\n\tdef __init__(self, files):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err012'\n\t\tself.params = [files]\n\t\t\n'''\n 文字コード変換エラー\n @param sourceFilePath: ファイル名\n @param errCnt: エラー行数\n'''\nclass CharCodeConvError(UserDefinitionException):\n\tdef __init__(self, sourceFilePath, errCnt):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err013'\n\t\tself.params = [sourceFilePath, errCnt]\n\t\t\n'''\n ユーザ定義警告基底クラス\n'''\nclass UserDefinitionWarning(Exception):\n\tdef __init__(self):\n\t\tException.__init__(self)\n\t\tself.messageId = 'wrn900'\n\t\tself.params = []\n\t\t\n'''\n テンプレート置換パラメータ数不正\n @param connectionInfo: 接続情報\n @param errorCode: エラーコード\n @param errorMessage: エラーメッセージ\n'''\nclass DBconnectWarning(UserDefinitionWarning):\n\tdef __init__(self, connectionInfo, errorCode, errorMessage):\n\t\tUserDefinitionWarning.__init__(self)\n\t\tself.messageId = 'wrn001'\n\t\tself.params = [connectionInfo, errorCode, errorMessage]\n\n'''\n ログインセッション削除エラー\n @param connectionInfo: 接続情報\n @param tokenId: トークンID\n @param errorMessage: エラーメッセージ\n'''\t\nclass DestroySessionError(UserDefinitionWarning):\n\tdef __init__(self, tokenId, errorMessage):\n\t\tUserDefinitionWarning.__init__(self)\n\t\tself.messageId = 'wrn003'\n\t\tself.params = [tokenId, errorMessage]\n\n'''\n ログインセッション削除エラー\n @param jobLogic: モジュール名\n'''\t\nclass TimeoutException(UserDefinitionException):\n\tdef __init__(self):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err014' \n \n'''\n ログインセッション制限エラー\n @param jobLogic: モジュール名\n'''\t\nclass LimitExceeded(UserDefinitionException):\n\tdef __init__(self,limitCnts,inputCnts):\n\t\tUserDefinitionException.__init__(self)\n\t\tself.messageId = 'err015'\n\t\tself.params = [limitCnts, inputCnts]\n\n","sub_path":"lib/EtlException.py","file_name":"EtlException.py","file_ext":"py","file_size_in_byte":6159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"301809488","text":"from numpy import *\nfrom SVM import *\n\nclass WeightedLinearSVM(SVM):\n def __init__(self, trainattr, label, comid, label1, label2, weight):\n SVM.__init__(self, trainattr, label, comid, label1, label2)\n self.weight = weight\n self.coe = 0.01\n self.T = int(1 * self.instancenum)\n self.w = zeros(self.attrnum)\n self.b = 0.0\n self.training()\n\n def training(self):\n for t in range(1, self.T + 1):\n randomindex = random.randint(self.instancenum)\n yt = 1.0 / (self.coe * t)\n trainitem = self.trainattr[self.comid[randomindex]]\n weight = self.weight[self.comid[randomindex]] * len(self.trainattr)\n innerproduct = dot(self.w, trainitem)\n tmplabel = self.labeldict[self.label[self.comid[randomindex]]]\n if innerproduct * tmplabel < 1:\n self.w = (1.0 - yt * self.coe) * self.w + yt * tmplabel * trainitem * weight\n self.b = (1.0 - yt * self.coe) * self.b + yt * tmplabel * weight\n else:\n self.w = (1.0 - yt * self.coe) * self.w\n self.b = (1.0 - yt * self.coe) * self.b\n\n def predict(self, testattr):\n flag = self.b\n flag += dot(self.w, testattr)\n result = self.label1 if flag >= 0 else self.label2\n return result\n","sub_path":"WeightedLinearSVM.py","file_name":"WeightedLinearSVM.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"513014345","text":"\"\"\"\nServer\n======\n\nRun the iceprod server.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport logging\nfrom functools import partial\nimport importlib\nimport subprocess\n\nfrom tornado.ioloop import IOLoop\n\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom iceprod.core.logger import set_log_level\nfrom iceprod.server.config import IceProdConfig\n\n\nlogger = logging.getLogger('Server')\n\nclass Server(object):\n \"\"\"\n The actual server.\n\n \"\"\"\n def __init__(self, config_params=None):\n self.io_loop = IOLoop.current()\n self.executor = ThreadPoolExecutor(max_workers=10)\n self.cfg = IceProdConfig(override=config_params)\n self.modules = {}\n self.services = {'daemon': {'restart': self.restart,\n 'reload': self.reload,\n 'stop': self.stop,\n 'kill': self.kill,\n 'get_running_modules': lambda: self.modules.keys(),\n },\n }\n\n set_log_level(self.cfg['logging']['level'])\n\n if 'blocking_threshold' in self.cfg['logging']:\n self.io_loop.set_blocking_log_threshold(self.cfg['logging']['blocking_threshold'])\n\n for mod_name in self.cfg['modules']:\n if self.cfg['modules'][mod_name]:\n try:\n m = importlib.import_module('iceprod.server.modules.'+mod_name)\n mod = getattr(m, mod_name)(cfg=self.cfg,\n io_loop=self.io_loop,\n executor=self.executor,\n modules=self.services)\n self.modules[mod_name] = mod\n self.services[mod_name] = mod.service\n mod.start()\n except Exception:\n logger.critical('cannot start module', exc_info=True)\n self.kill()\n raise\n\n def run(self):\n try:\n self.io_loop.start()\n except Exception:\n logger.critical('exception not caught', exc_info=True)\n self.kill()\n\n def restart(self):\n env = os.environ.copy()\n extra_path = os.path.join(os.environ['I3PROD'],'bin')\n env['PATH'] = extra_path+(':'+env['PATH'] if 'PATH' in env else '')\n subprocess.Popen(['iceprod_server.py','restart'],\n cwd=os.environ['I3PROD'], env=env)\n\n def reload(self):\n for m in self.modules.values():\n m.stop()\n m.start()\n\n def stop(self):\n for m in self.modules.values():\n m.stop()\n self.io_loop.stop()\n\n def kill(self):\n for m in self.modules.values():\n m.kill()\n self.io_loop.stop()\n","sub_path":"iceprod/server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"206244505","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport LatticeDefinitions as ld\nimport GeometryFunctions as gf\nimport GeneralLattice as gl\nimport LAMMPSTool as LT\nimport sys\nfrom mpl_toolkits.mplot3d import Axes3D\nprint(gf.CubicCSLGenerator(np.array([1,1,0]), 5))\n#fig = plt.figure()\n#ax = fig.add_subplot(111, projection='3d')\n#strDirectory = str(sys.argv[1])\n#intSigma = int(sys.argv[2])\n#intMax = int(sys.argv[3])\n#strDirectory = '../PythonLAMMPS/'\narrAxis = np.array([1,0,1])\n#intSigma = 3\nobjSigma = gl.SigmaCell(arrAxis,ld.FCCCell)\nobjSigma.MakeCSLCell(3)\n#gf.CubicCSLGenerator(arrAxis, 5)\n#arrRotation = np.zeros(3)\n#arrRotation[1:3] = objSigma.GetLatticeRotations()\n#arrRotation[0] = -arrRotation[1]\narrSigmaBasis = objSigma.GetBasisVectors()\nprint(arrSigmaBasis)\na1 = 4.05 ##lattice parameter\na2 = a1*np.sqrt(3) #periodic cell repeat multiple\nh= 1\ns = np.linalg.norm(arrSigmaBasis, axis=1)[0]\nz = a2*np.array([0,0,h])\n#intStart = np.ceil(max(4, s)).astype('int')\nintIncrement = np.ceil(1/s).astype('int')\nfltAngle, arrVector = gf.FindRotationVectorAndAngle(arrAxis, np.array([0,0,1]))\narr111BasisVectors = gf.RotatedBasisVectors(fltAngle, arrVector)\nfor j in range(intIncrement,intMax +1+intIncrement):\n l = j*s*intIncrement\n arrHorizontalVector = l*a1*arrSigmaBasis[0]\n arrDiagonalVector = l*a1*arrSigmaBasis[1]\n MySimulationCell = gl.SimulationCell(np.array([3*arrHorizontalVector,3*arrDiagonalVector, z]))\n objHex1 = gl.ExtrudedRegularPolygon(l*a1*s, (h-0.1)*a2, 6, gf.RotateVectors(arrRotation[0],z,arr111BasisVectors), ld.FCCCell, np.array([a1,a1,a1]), arrHorizontalVector + arrDiagonalVector)\n objHex2 = gl.ExtrudedRegularPolygon(l*a1*s, (h-0.1)*a2, 6, gf.RotateVectors(arrRotation[1],z,arr111BasisVectors), ld.FCCCell, np.array([a1,a1,a1]),np.zeros(3))\n objHex3 = gl.ExtrudedRegularPolygon(l*a1*s, (h-0.1)*a2, 6, gf.RotateVectors(arrRotation[2],z, arr111BasisVectors), ld.FCCCell, np.array([a1,a1,a1]),-arrDiagonalVector+2*arrHorizontalVector)\n MySimulationCell.AddGrain(objHex1,'Hex1')\n MySimulationCell.AddGrain(objHex2,'Hex2')\n MySimulationCell.AddGrain(objHex3, 'Hex3')\n MySimulationCell.RemoveTooCloseAtoms(a1/(4*np.sqrt(2)))\n MySimulationCell.WrapAllAtomsIntoSimulationCell()\n MySimulationCell.SetFileHeader('Sigma ' + str(intSigma) + ' about ' + str(arrAxis) + ' with Hexagonal grains 1,2 and 3 with angle array ' + str(arrRotation) + ' and length multiple of ' + str(j))\n strFileName = 'Hex' + '123' + 'Sigma' + str(intSigma) + 'length' + str(j) + '.dat'\n MySimulationCell.WriteLAMMPSDataFile(strDirectory + strFileName)\n\n\n\n\n1\n\n","sub_path":"CSLHexExpander.py","file_name":"CSLHexExpander.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"159382755","text":"#!/usr/bin/env python\n\nfrom typing import OrderedDict\nimport pandas as pd\nimport numpy as np\nimport subprocess as subp\nfrom io import StringIO\nimport xmltodict\nimport sgetk\nfrom pprint import pprint\nimport xml.dom.minidom\nimport lxml.etree as etree\n\n\ndef combine_string(str_old, str_list=[\n '-xml', '-ext', '-r', '-t', '-pri']):\n str_new = str_old\n for i in str_list:\n if i not in str_new:\n str_new += f\" {i}\"\n\n return str_new\n\n\ndef qstat2xml(qstat_cmd, str_list=[\n '-xml', '-ext', '-r', '-t', '-pri']):\n \"\"\"\n Returns\n -------\n qstatxml : string\n The xml stdout string of the 'qstat -xml' call\n\n -xml: display the information in XML format\n -ext: view additional attributes\n -r: show requested resources of job(s)\n -t: show task information (implicitly -g t)\n -pri: display job priority information\n\n [\"-xml\", \"-ext\", \"-r\", \"-t\", \"-pri\"]\n \"\"\"\n qstat_cmd_new = combine_string(qstat_cmd, str_list)\n try:\n qstatxml = subp.check_output(qstat_cmd_new,\n shell=True, stderr=(subp.STDOUT))\n except subp.CalledProcessError as e:\n try:\n print('qstat returncode: ', e.returncode)\n print('qstat std output: ', e.output)\n raise\n finally:\n e = None\n del e\n\n return qstatxml\n\n\ndef xml2data_frame(xml_str, query_key='job_list'):\n \"\"\"\n xml_str is string, xmltodict.parse can parse: string, a file-like object, or a generator of strings\n when search job info, use \"job_list\"\n when search query info, use \"Queue-List\"\n \"\"\"\n x = xmltodict.parse(xml_str)\n\n queue_info = x['job_info']['queue_info']\n job_info = x['job_info']['job_info']\n\n queue_df = pd.DataFrame()\n job_df = pd.DataFrame()\n\n if queue_info is not None:\n if query_key in queue_info:\n if isinstance(queue_info[query_key], list):\n queue_df = pd.DataFrame(queue_info[query_key])\n else:\n queue_df = pd.DataFrame([queue_info[query_key]])\n else:\n print(f\"{query_key} is not in xml output, please check\")\n if job_info is not None:\n if query_key in job_info:\n if isinstance(job_info[query_key], list):\n job_df = pd.DataFrame(job_info[query_key])\n else:\n job_df = pd.DataFrame([job_info[query_key]])\n else:\n print(f\"{query_key} is not in xml output, please check\")\n\n type_dict = {\n '@state': str,\n 'cpu_usage': float,\n 'mem_usage': float,\n 'io_usage': float,\n 'slots': float,\n 'JAT_prio': float,\n 'hard_req_queue': str,\n 'JB_owner': str,\n 'JB_department': str,\n 'JB_project': str\n }\n type_dict_ = {}\n all_df = pd.concat([queue_df, job_df])\n for i in type_dict:\n if i in all_df.columns:\n type_dict_[i] = type_dict[i]\n all_df = all_df.astype(type_dict_)\n return all_df\n\n\ndef qhost(q):\n xml_str = qstat2xml(qstat_cmd, str_list)\n return xml2data_frame(xml_str, query_key)\n\n\ndef extract_mem_core(x):\n \"\"\"\n Args:\n x:\n [OrderedDict([('@name', 'num_proc'),\n ('@resource_contribution', '800.000000'),\n ('#text', '8')])\n\n OrderedDict([('@name', 'virtual_free'),\n ('@resource_contribution', '0.000000'),\n ('#text', '5g')])]\n\n [OrderedDict([('@name', 'high_priority'),\n ('@resource_contribution', '100000.000000'),\n ('#text', 'TRUE')]),\n OrderedDict([('@name', 'num_proc'),\n ('@resource_contribution', '400.000000'),\n ('#text', '4')]),\n OrderedDict([('@name', 'virtual_free'),\n ('@resource_contribution', '0.000000'),\n ('#text', '10.5g')])]\n \"\"\"\n core = 0\n mem = 0\n if isinstance(x, list):\n for i in x:\n if isinstance(i, OrderedDict):\n if i['@name'] == 'num_proc':\n core = int(i['#text'])\n elif i['@name'] == 'virtual_free':\n mem_str = str(i['#text'])\n if mem_str[(-1)].isdigit():\n mem_str += 'B'\n mem = sgetk.sge_summary.human2bytes(mem_str)\n else:\n print('detect non ordered dict')\n pprint(i)\n\n elif isinstance(x, OrderedDict):\n if x['@name'] == 'num_proc':\n core = int(x['#text'])\n elif x['@name'] == 'virtual_free':\n mem_str = str(x['#text'])\n if mem_str[(-1)].isdigit():\n mem_str += 'B'\n mem = sgetk.sge_summary.human2bytes(mem_str)\n return (\n mem, core)\n\n\ndef extract_mem_core_v2(x):\n core = 0\n mem = ''\n for i in x:\n if i['@name'] == 'num_proc':\n core = int(i['#text'])\n if i['@name'] == 'virtual_free':\n mem = str(i['#text'])\n\n return (\n mem, core)\n\n\ndef user_running_job_info(x):\n job_count = 0.0\n for i in x['slots']:\n job_count += float(i)\n\n job_host = []\n for i in x['queue_name']:\n job_host.append(i)\n\n cpu_usage = sum(x['cpu_usage'])\n cpu_usage_average = cpu_usage / job_count\n mem_usage = sum(x['mem_usage'])\n mem_usage_average = mem_usage / job_count\n io_usage = sum(x['io_usage'])\n io_usage_average = io_usage / job_count\n JAT_prio_average = sum(x['JAT_prio']) / job_count\n mem_request = 0.0\n core_request = 0.0\n for i in x['hard_request']:\n mem, core = extract_mem_core(i)\n core_request += core\n mem_request += mem\n\n mem_request_average = mem_request / job_count\n core_request_average = core_request / job_count\n core_binding = 0.0\n for i in x['binding']:\n if i is not None:\n try:\n str_int = float(i.split(':')[(-1)])\n except:\n print(f'''error core binnind: {x[\"JB_owner\"]} {x[\"JB_job_number\"]} {i}''')\n core_binding += 1\n else:\n core_binding += 1\n\n core_binding_average = core_binding / job_count\n return pd.Series({'job_count': job_count, 'job_host': job_host,\n 'JAT_prio_average': JAT_prio_average,\n 'cpu_usage_total(hour)': cpu_usage / 3600,\n 'cpu_usage_per_job(hour)': cpu_usage_average / 36000,\n 'cpu_usage_average_per_job_per_core(hour)': cpu_usage_average / core_request_average / 3600,\n 'mem_usage_total': sgetk.sge_summary.bytes2human(mem_usage) if not pd.isna(mem_usage) else 0,\n 'mem_usage_average': sgetk.sge_summary.bytes2human(mem_usage_average) if not pd.isna(mem_usage_average) else 0,\n 'mem_request_total': sgetk.sge_summary.bytes2human(mem_request) if not pd.isna(mem_request) else 0,\n 'mem_request_average': sgetk.sge_summary.bytes2human(mem_request_average) if not pd.isna(mem_request_average) else 0,\n 'core_request_total': core_request,\n 'core_request_average': core_request_average,\n 'core_binding': core_binding,\n 'core_binding_average': core_binding_average,\n 'io_usage_total': io_usage,\n 'io_usage_average': io_usage_average})\n\n\ndef pretty_xml(xml_str):\n x = etree.fromstring(xml_str)\n print(etree.tostring(x, pretty_print=True))\n\n\ndef print_xml(xml_str):\n print(xml.dom.minidom.parseString(xml_str).toprettyxml())\n# okay decompiling sgetk/__pycache__/qstat.cpython-37.pyc\n","sub_path":"sgetk/qhost.py","file_name":"qhost.py","file_ext":"py","file_size_in_byte":7747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"599561815","text":"import numpy as np\r\nimport pandas as pd\r\n\r\nclass Game(object):\r\n def __init__(self, n=3, player_sym='x'):\r\n self.board = None\r\n self.reset_board(n)\r\n self.stale = False\r\n self.sym_o = {'mark': 'O','value': 1 }\r\n self.sym_x = {'mark': 'X','value': 2}\r\n self.sym_empty = {'mark': ' ','value': 0}\r\n self.player_sym, self.bot_sym = (self.sym_x, self.sym_o) \\\r\n if player_sym.lower() == 'x' \\\r\n else (self.sym_o, self.sym_x)\r\n self.winner = None\r\n\r\n def reset_board(self, n=3):\r\n self.board = np.zeros((n, n)).astype(int)\r\n self.winner = None\r\n\r\n def draw_char_for_item(self, item):\r\n if item == self.sym_x.get('value'):\r\n return self.sym_x.get('mark')\r\n elif item == self.sym_o.get('value'):\r\n return self.sym_o.get('mark')\r\n else:\r\n return self.sym_empty.get('mark')\r\n\r\n def draw_board(self):\r\n elements_in_board = self.board.size\r\n items = [\r\n self.draw_char_for_item(self.board.item(item_idx))\r\n for item_idx in range(elements_in_board)\r\n ]\r\n board = \"\"\"\r\n {} | {} | {}\r\n -----------\r\n {} | {} | {}\r\n -----------\r\n {} | {} | {}\r\n \"\"\".format(*items)\r\n print(board)\r\n\r\n def have_same_val(self, axis, item, item_x, item_y):\r\n max_limit, _ = self.board.shape\r\n result = True\r\n row_idx = col_idx = 0\r\n main_idx, fixed_idx, ignore_idx = (col_idx, item_x, item_y) \\\r\n if axis == 0 \\\r\n else (row_idx, item_y, item_x)\r\n while main_idx < max_limit:\r\n if main_idx != ignore_idx:\r\n board_item = self.board[fixed_idx][main_idx] \\\r\n if axis == 0 \\\r\n else self.board[main_idx][fixed_idx]\r\n if board_item != item or board_item == 0:\r\n result = False\r\n break\r\n main_idx += 1\r\n return result\r\n\r\n def left_diagonal_has_same_values(self, item, item_x, item_y):\r\n i = j = 0\r\n result = True\r\n max_limit, _ = self.board.shape\r\n while i < max_limit:\r\n if i != item_x:\r\n if self.board[i][j] != item or self.board[i][j] == 0:\r\n result = False\r\n break\r\n i += 1\r\n j += 1\r\n return result\r\n\r\n def right_diagonal_has_same_values(self, item, item_x, item_y):\r\n result = True\r\n max_limit, _ = self.board.shape\r\n i = 0\r\n j = max_limit - 1\r\n while i < max_limit:\r\n if i != item_x:\r\n if self.board[i][j] != item or self.board[i][j] == 0:\r\n result = False\r\n break\r\n i += 1\r\n j -= 1\r\n return result\r\n\r\n def cols_have_same_values(self, item, item_x, item_y):\r\n axis = 1\r\n return self.have_same_val(axis, item, item_x, item_y)\r\n\r\n def rows_have_same_values(self, item, item_x, item_y):\r\n axis = 0\r\n return self.have_same_val(axis, item, item_x, item_y)\r\n\r\n def element_diagonal_has_same_value(self, item, item_x, item_y):\r\n max_limit, _ = self.board.shape\r\n if item_x == item_y and item_x + item_y == max_limit - 1:\r\n return self.left_diagonal_has_same_values(item, item_x, item_y) or \\\r\n self.right_diagonal_has_same_values(item, item_x, item_y)\r\n\r\n if item_x == item_y:\r\n return self.left_diagonal_has_same_values(item, item_x, item_y)\r\n\r\n if item_x + item_y == max_limit - 1:\r\n return self.right_diagonal_has_same_values(item, item_x, item_y)\r\n return False\r\n\r\n def is_game_over(self, player, item, item_x, item_y):\r\n return self.cols_have_same_values(item, item_x, item_y) or \\\r\n self.rows_have_same_values(item, item_x, item_y) or \\\r\n self.element_diagonal_has_same_value(item, item_x, item_y)\r\n\r\n def is_winning_move(self, player, item, item_x, item_y):\r\n if self.is_game_over(player, item, item_x, item_y):\r\n self.winner = player\r\n return True\r\n return False\r\n\r\n def is_stale(self):\r\n x, y = np.where(self.board == 0)\r\n if len(x) == 0 and len(y) == 0:\r\n self.stale = True\r\n log('is game stale? ', self.stale)\r\n return self.stale\r\n\r\n def player_move(self, input_symbol, item_x, item_y):\r\n symbol = None\r\n if input_symbol == self.sym_o.get('mark'):\r\n symbol = self.sym_o\r\n\r\n elif input_symbol == self.sym_x.get('mark'):\r\n symbol = self.sym_x\r\n\r\n else:\r\n return\r\n if self.board[item_x][item_y] == 0:\r\n self.board[item_x][item_y] = symbol.get('value')\r\n self.draw_board()\r\n\r\n if self.is_winning_move(symbol.get('mark'), symbol.get('value'), item_x, item_y):\r\n print('Winner is: {}'.format(self.winner))\r\n return self.winner\r\n elif self.is_stale():\r\n print('Draw')\r\n return 'draw'\r\n\r\n def play(self, item_x, item_y):\r\n\r\n max_limit, _ = self.board.shape\r\n if item_x > max_limit - 1 or item_y > max_limit:\r\n return\r\n self.player_move(self.player_sym.get('mark'), item_x, item_y)\r\n\r\n def bot_play(self, item_x, item_y):\r\n\r\n max_limit, _ = self.board.shape\r\n if item_x > max_limit - 1 or item_y > max_limit:\r\n return\r\n self.player_move(self.bot_sym.get('mark'), item_x, item_y)\r\n\r\nclass Agent():\r\n def __init__(self, exploration_rate=0.33, learning_rate=0.5, discount_factor=0.01):\r\n self.states = {}\r\n self.state_order = []\r\n self.learning_rate = learning_rate\r\n self.discount_factor = discount_factor\r\n self.exploration_rate = exploration_rate\r\n\r\n def serialize_board(board):\r\n serialized_board = board.flatten()\r\n return ''.join([str(i) for i in serialized_board.flatten().tolist()])\r\n\r\n def get_serious(self):\r\n self.exploration_rate = 0\r\n\r\n def learn_by_temporal_difference(self, reward, new_state_key, state_key):\r\n old_state = self.states.get(state_key, np.zeros((3, 3)))\r\n return self.learning_rate * ((reward * self.states[new_state_key]) - old_state)\r\n\r\n def set_state(self, old_board, action):\r\n state_key = Agent.serialize_board(old_board)\r\n self.state_order.append((state_key, action))\r\n\r\n def on_reward(self, reward):\r\n if len(self.state_order) == 0:\r\n return None\r\n new_state_key, new_action = self.state_order.pop()\r\n self.states[new_state_key] = np.zeros((3, 3))\r\n self.states[new_state_key].itemset(new_action, reward)\r\n while self.state_order:\r\n state_key, action = self.state_order.pop()\r\n reward *= self.discount_factor\r\n if state_key in self.states:\r\n reward += self.learn_by_temporal_difference(reward, new_state_key, state_key).item(new_action)\r\n self.states[state_key].itemset(action, reward)\r\n else:\r\n self.states[state_key] = np.zeros((3, 3))\r\n reward = self.learn_by_temporal_difference(reward, new_state_key, state_key).item(new_action)\r\n self.states[state_key].itemset(action, reward)\r\n new_state_key = state_key\r\n new_action = action\r\n def exploit_board(self, state_key):\r\n state_values = self.states[state_key]\r\n print('State rewards')\r\n print(state_values)\r\n best_actions_x, best_actions_y = np.where(state_values == state_values.max())\r\n best_value_indices = [(x, y) for x, y in zip(best_actions_x, best_actions_y)]\r\n select_index = np.random.choice(len(best_value_indices))\r\n return best_value_indices[select_index]\r\n\r\n def select_move(self, board):\r\n explore_message = 'No experience for this state: explore'\r\n state_key = Agent.serialize_board(board)\r\n exploration = np.random.random() < self.exploration_rate\r\n log(explore_message if exploration or state_key not in self.states else 'exploit')\r\n action = self.explore_board(board) \\\r\n if exploration or state_key not in self.states \\\r\n else self.exploit_board(state_key)\r\n log('Choose cell', action)\r\n self.set_state(board, action)\r\n return action\r\n\r\n def explore_board(self, board):\r\n\r\n zero_x, zero_y = np.where(board == 0)\r\n vacant_cells = [(x, y) for x, y in zip(zero_x, zero_y)]\r\n randomly_selected_vacant_cell = np.random.choice(len(vacant_cells))\r\n return vacant_cells[randomly_selected_vacant_cell]\r\n\r\n\r\ndef optimize_bot(game, bot1, bot2):\r\n \r\n if game.winner == 'O':\r\n bot1.on_reward(1)\r\n # reward\r\n bot2.on_reward(-1)\r\n # punishment\r\n elif game.winner == 'X':\r\n bot1.on_reward(-1)\r\n bot2.on_reward(1)\r\n\r\ndef train(epochs, bot1, bot2):\r\n bots = [{'mdl': bot1,'name': 'bot1','sym': 'O','wins': 0}, {'mdl': bot2, 'name': 'bot2', 'sym': 'X', 'wins': 0 }]\r\n\r\n win_trace = pd.DataFrame(data=np.zeros((epochs, 2)), columns=['bot1', 'bot2'])\r\n for i in range(epochs):\r\n print('-' * 100)\r\n print('epoch: {}'.format(i + 1))\r\n game = Game()\r\n while not game.stale and not game.winner:\r\n for bot in bots:\r\n winner = game.player_move(bot['sym'], *bot['mdl'].select_move(game.board))\r\n log('winner found:', winner)\r\n if winner:\r\n optimize_bot(game, bot1, bot2)\r\n bot['wins'] += 1\r\n win_trace.set_value(i, bot['name'], 1)\r\n break\r\n win_trace[i] = 2\r\n elif winner == 'draw':\r\n break\r\n return win_trace, bots[0]['wins'], bots[1]['wins']\r\n\r\ndef log(*args):\r\n if True:\r\n print(*args)\r\n\r\nbot1 = Agent()\r\nbot2 = Agent()\r\nepochs = 10000\r\nwin_trace, bot1_wins, bot2_wins = train(epochs, bot1, bot2)","sub_path":"reinforcement_learning.py","file_name":"reinforcement_learning.py","file_ext":"py","file_size_in_byte":10187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"6701293","text":"import cv2\nimport numpy as np\nimport statistics\n\n####### training part ###############\nsamples = np.loadtxt('generalsamples.data',np.float32)\nresponses = np.loadtxt('generalresponses.data',np.float32)\nresponses = responses.reshape((responses.size,1))\n\nmodel = cv2.ml.KNearest_create()\nmodel.train(samples,cv2.ml.ROW_SAMPLE,responses)\n\n############################# testing part #########################\n\ncap = cv2.VideoCapture(0) # '0' is the webcam's ID. usually it is 0 or 1. 'cap' is the video object.\ncap.set(15, -5) # '15' references video's brightness. '-4' sets the brightness.\n\ncounter = 0 # script will use a counter to handle FPS.\nreadings = [-1,-1] # lists are used to track the number of pips.\ndisplay = [0, 0]\nisRunning = True\nimgSamples = 64\n\nwhile isRunning:\n if counter >= 90000: # set maximum sizes for variables and lists to save memory.\n counter = 0\n readings = [-1,-1]\n display = [0, 0]\n posx = 100\n posy = 100\n posh= 50\n\n for smpl in range(imgSamples):\n ret, im = cap.read() # 'im' will be a frame from the video.\n\n out = np.zeros(im.shape,np.uint8)\n gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray,(5,5),0)\n thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)\n\n\n contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\n\n for cnt in contours:\n if (cv2.contourArea(cnt) < 900 and cv2.contourArea(cnt) > 700):\n [x,y,w,h] = cv2.boundingRect(cnt)\n if h>28:\n posx = x\n posy = y\n posh = h\n cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)\n roi = thresh[y:y+h,x:x+w]\n roismall = cv2.resize(roi,(10,10))\n roismall = roismall.reshape((1,100))\n roismall = np.float32(roismall)\n retval, results, neigh_resp, dists = model.findNearest(roismall, k = 1)\n string = str(int((results[0][0]))) #the result parsed to a string to output an image\n readNum = int(string) #revert the result back into an int to display to console and to have a tangible number to work with\n readings.append(readNum)\n\n print(readings)\n number = statistics.mode(readings)\n readings = [-1,-1]\n if(number == -1):\n number =\"NO DICE\"\n cv2.putText(out,str(number),(posx,posy+posh),0,1,(0,255,0))\n cv2.imshow('out',out)\n cv2.imshow('im',im)\n key = cv2.waitKey(0)\n if key == 27: # (escape to quit)\n isRunning = False\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"recognize_digits.py","file_name":"recognize_digits.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"182834056","text":"def razpon_s_seznami(m, n):\n '''Vrne seznam vseh števil od m do nevključno n.'''\n razpon = []\n while m < n:\n razpon.append(m)\n m += 1\n return razpon\n\ndef razpon_z_generatorji(m, n):\n while m < n:\n yield m\n m += 1\n\n\ndef vsota_razpona_slaba(m, n):\n razpon = razpon_s_seznami(m, n)\n vsota = 0\n for x in razpon:\n vsota += x\n return vsota\n\n\ndef vsota_razpona(m, n):\n vsota = 0\n for x in razpon_z_generatorji(m, n):\n vsota += x\n return vsota\n\n\ndef fibonacci():\n a, b = 0, 1\n while True:\n yield b\n a, b = b, a + b\n\n\ndef vsota_fibonaccijevih():\n vsota = 0\n for x in fibonacci():\n vsota += x\n return vsota\n","sub_path":"datoteke-s-predavanj/2015-16/13-generatorji/financniki/razponi.py","file_name":"razponi.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"585351084","text":"from ice_service import application\n\nclass CallableI(ice.Utils.Callable):\n\n def execute(self, call, in_json, in_raw, current=None):\n print(f'execute {call} {in_json} {in_raw}')\n out_json = '{\"msg\": \"i am in kvm\"}'\n out_raw = bytes()\n return out_json, out_raw\n\n\nclass Server(application.Application):\n def run(self, args):\n adapter = self.communicator().createObjectAdapter(\"DSS.Server\")\n adapter.add(CallableI(), self.communicator().stringToIdentity(\"dss\"))\n call_prx = ice.Utils.CallablePrx.uncheckedCast(\n adapter.createProxy(self.communicator().stringToIdentity(\"callable\")))\n adapter.add(KVMI(call_prx), self.communicator().stringToIdentity(\"kvm\"))\n adapter.activate()\n self.communicator().waitForShutdown()\n return 0","sub_path":"disk_snapshot_service/ice_service/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"211828815","text":"import unittest\nfrom itertools import chain\nfrom maggma.stores import MongoStore\nfrom maggma.runner import Runner\nfrom emmet.vasp.builders.tests.test_builders import BuilderTest\nfrom emmet.vasp.builders.materials import MaterialsBuilder\nfrom emmet.vasp.builders.thermo import ThermoBuilder\n\n__author__ = \"Shyam Dwaraknath\"\n__email__ = \"shyamd@lbl.gov\"\n\nclass TestThermo(BuilderTest):\n\n def setUp(self):\n\n self.materials = MongoStore(\"emmet_test\", \"materials\")\n self.thermo = MongoStore(\"emmet_test\", \"thermo\")\n\n self.materials.connect()\n self.thermo.connect()\n\n self.mbuilder = MaterialsBuilder(\n self.tasks, self.materials, mat_prefix=\"\", chunk_size=1)\n self.tbuilder = ThermoBuilder(\n self.materials, self.thermo, chunk_size=1)\n runner = Runner([self.mbuilder])\n runner.run()\n\n def test_get_entries(self):\n self.assertEqual(len(self.tbuilder.get_entries(\"Sr\")), 7)\n self.assertEqual(len(self.tbuilder.get_entries(\"Hf\")), 4)\n self.assertEqual(len(self.tbuilder.get_entries(\"O\")), 6)\n self.assertEqual(len(self.tbuilder.get_entries(\"Hf-O-Sr\")), 44)\n self.assertEqual(len(self.tbuilder.get_entries(\"Sr-Hf\")), 11)\n\n def test_get_items(self):\n self.thermo.collection.drop()\n comp_systems = list(self.tbuilder.get_items())\n self.assertEqual(len(comp_systems), 1)\n self.assertEqual(len(comp_systems[0]), 44)\n\n def test_process_item(self):\n\n tbuilder = ThermoBuilder(self.materials, self.thermo, query={\n \"elements\": [\"Sr\"]}, chunk_size=1)\n entries = list(tbuilder.get_items())[0]\n self.assertEqual(len(entries), 7)\n\n t_docs = self.tbuilder.process_item(entries)\n e_above_hulls = [t['thermo']['e_above_hull'] for t in t_docs]\n sorted_t_docs = list(\n sorted(t_docs, key=lambda x: x['thermo']['e_above_hull']))\n self.assertEqual(sorted_t_docs[0][\"task_id\"], \"mp-76\")\n\n def test_update_targets(self):\n self.thermo.collection.drop()\n\n tbuilder = ThermoBuilder(self.materials, self.thermo, query={\n \"elements\": [\"Sr\"]}, chunk_size=1)\n entries = list(tbuilder.get_items())[0]\n self.assertEqual(len(entries), 7)\n\n t_docs = self.tbuilder.process_item(entries)\n self.tbuilder.update_targets([t_docs])\n self.assertEqual(len(list(self.thermo.query())), len(t_docs))\n\n def tearDown(self):\n self.materials.collection.drop()\n self.thermo.collection.drop()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"emmet/vasp/builders/tests/test_thermo.py","file_name":"test_thermo.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"210882609","text":"\"\"\"The init command.\"\"\"\n\nfrom dbmisvc_stack.commands.base import Base\nfrom dbmisvc_stack.app import App\n\nimport logging\n\nlogger = logging.getLogger(\"stack\")\n\n\nclass Init(Base):\n def run(self):\n\n # Determine the app.\n app = self.options[\"\"]\n\n # Ensure it's a built app\n logger.debug(\"({}) Check for need to initialize\".format(app))\n if app is not None and App.get_repo_url(app) and App.get_repo_branch(app):\n\n # Initializer.\n logger.debug(\n \"({}) Preparing to initialize with branch: {}\".format(\n app, App.get_repo_branch(app)\n )\n )\n App.init(app)\n\n else:\n\n # Iterate through built apps\n for app in App.get_built_apps():\n\n # Ensure it's a built app\n if App.get_repo_url(app) and App.get_repo_branch(app):\n\n # Initializer.\n logger.debug(\"({}) Preparing to initialize\".format(app))\n App.init(app)\n","sub_path":"dbmisvc_stack/commands/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"235489928","text":"# -*- coding: utf-8 -*-\n# by F.H. learnt from https://blog.csdn.net/liuxiao214/article/details/74502975\n# 其中z是生成器噪声,d或dis为判别器(discriminator)的缩写,g或gen为生成器(generator)的缩写,c是图像第三维度(颜色)\n# 18.8.10\nfrom __future__ import division # 解决一下整数除法在python2和python3中不同的问题\n\nimport os # 用来加载图片及设置显卡什么的\nimport platform\n\nWINDOWS = True # 在自己的电脑上就设置为True好了\n\nif platform.system() == \"Linux\":\n WINDOWS = False # srt服务器上\n\nif not WINDOWS:\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"7\"\n\nimport tensorflow as tf\nimport numpy as np\nfrom six.moves import xrange\n# xrange与range类似,只是返回的是一个“xrange object”对象,而非数组list。要生成很大的数字序列的时候,\n# 用xrange会比range性能优很多,因为不需要一上来就开辟一块很大的内存空间,这两个基本上都是在循环的时候用\nimport time\nimport scipy.misc\n\nimage_summary = tf.summary.image\nscalar_summary = tf.summary.scalar\nhistogram_summary = tf.summary.histogram\nmerge_summary = tf.summary.merge\nSummaryWriter = tf.summary.FileWriter\n\nclass batch_norm(object):\n def __init__(self, epsilon=1e-5, momentum=0.9, name=\"batch_norm\"):\n with tf.variable_scope(name):\n self.epsilon = epsilon\n self.momentum = momentum\n self.name = name\n\n def __call__(self, x, train=True):\n return tf.contrib.layers.batch_norm(x,\n decay=self.momentum,\n updates_collections=None,\n epsilon=self.epsilon,\n scale=True,\n is_training=train,\n scope=self.name)\n\n\n\nclass DCGAN:\n def __init__(self, path=r'../common/getchu_faces_64/', input_h=64, input_w=64, batch_size=64, gf_dim=128,\n df_dim=64, z_dim=100, c_dim=3, checkpoint_dir='checkpoint',\n sample_num=64, learning_rate=0.0002, beta1=0.5, epoch=400):\n # load Data\n self.sess = tf.Session()\n self.images = []\n self.image_h, self.image_w, self.batch_size = input_h, input_w, batch_size\n self.gf_dim, self.df_dim, self.c_dim, self.z_dim = \\\n gf_dim, df_dim, c_dim, z_dim\n self.sample_num, self.learning_rate, self.beta1, self.epoch = \\\n sample_num, learning_rate, beta1, epoch\n self.checkpoint_dir = checkpoint_dir\n\n self.imagefiles = os.listdir(path)\n np.random.shuffle(self.imagefiles)\n if WINDOWS:\n self.imagefiles = self.imagefiles[:500]\n for index, i in enumerate(self.imagefiles):\n data = tf.image.decode_jpeg(tf.gfile.FastGFile(os.path.join(path, i), 'rb').read())\n data = tf.image.convert_image_dtype(data, dtype=tf.uint8)\n self.images.append(data)\n if index % 50 == 0:\n print(\"Loading image \" + str(index) + \" of \" + str(len(self.imagefiles)))\n print(\"Processing on images... May take few minutes, please wait\")\n self.images = np.asarray(self.sess.run(self.images)) / 255.0 # python2 为整除,所以需要import division\n print(\"Images ready!\")\n # batch normalization:批量标准化处理,不仅仅只对输入层的输入数据x进行标准化,还对每个隐藏层的输入进行标准化。\n self.d_bn1 = batch_norm(name='d_bn1')\n self.d_bn2 = batch_norm(name='d_bn2')\n self.d_bn3 = batch_norm(name='d_bn3')\n\n self.g_bn0 = batch_norm(name='g_bn0')\n self.g_bn1 = batch_norm(name='g_bn1')\n self.g_bn2 = batch_norm(name='g_bn2')\n self.g_bn3 = batch_norm(name='g_bn3')\n\n self.build_model()\n\n def train(self):\n # Adam 也是基于梯度下降的方法,但是每次迭代参数的学习步长都有一个确定的范围,\n # 不会因为很大的梯度导致很大的学习步长,参数的值比较稳定\n\n # 分别定义判别器和生成器的优化器\n d_optim = tf.train.AdamOptimizer(self.learning_rate, beta1=self.beta1) \\\n .minimize(self.d_loss, var_list=self.d_vars)\n g_optim = tf.train.AdamOptimizer(self.learning_rate, beta1=self.beta1) \\\n .minimize(self.g_loss, var_list=self.g_vars)\n tf.global_variables_initializer().run(session=self.sess)\n\n self.g_sum = merge_summary([self.z_sum, self.d__sum, self.G_sum, self.d_loss_fake_sum, self.g_loss_sum])\n self.d_sum = merge_summary([self.z_sum, self.d_sum, self.d_loss_real_sum, self.d_loss_sum])\n self.writer = SummaryWriter(\"./logs\", self.sess.graph)\n\n sample_z = np.random.uniform(-1, 1, size=(self.sample_num, self.z_dim))\n\n sample = self.images[0:self.sample_num]\n sample_inputs = np.array(sample).astype(np.float32)\n\n counter = 1\n start_time = time.time()\n could_load, checkpoint_counter = self.load(self.checkpoint_dir)\n if could_load:\n counter = checkpoint_counter\n print(\" [*] Load SUCCESS\")\n else:\n print(\" [!] Load failed...\")\n\n for epoch in xrange(self.epoch):\n batch_idxs = len(self.imagefiles) // self.batch_size\n\n for idx in xrange(0, batch_idxs):\n batch = self.images[idx * self.batch_size:(idx + 1) * self.batch_size]\n batch_images = np.array(batch).astype(np.float32)\n\n batch_z = np.random.uniform(-1, 1, [self.batch_size, self.z_dim]).astype(np.float32)\n\n def trainD():\n _, summary_str = self.sess.run([d_optim, self.d_sum],\n feed_dict={self.inputs: batch_images, self.z: batch_z})\n self.writer.add_summary(summary_str, counter)\n\n def trainG():\n _, summary_str = self.sess.run([g_optim, self.g_sum],\n feed_dict={self.z: batch_z})\n self.writer.add_summary(summary_str, counter)\n\n trainD()\n trainG()\n trainG() # 两次应该能好一点……要不然就崩了\n\n errD_fake = self.d_loss_fake.eval({self.z: batch_z})\n errD_real = self.d_loss_real.eval({self.inputs: batch_images})\n errG = self.g_loss.eval({self.z: batch_z})\n\n if errG > (errD_fake + errD_real) * 2:\n trainG()\n trainG()\n\n counter += 1\n print(\"Epoch: [%2d] [%4d/%4d] time: %4.4f, d_loss: %.8f, g_loss: %.8f\" \\\n % (epoch, idx, batch_idxs, time.time() - start_time, errD_fake + errD_real, errG))\n\n if np.mod(counter, 100) == 1 and counter > 100:\n try:\n samples, d_loss, g_loss = self.sess.run(\n [self.sampler, self.d_loss, self.g_loss],\n feed_dict={\n self.z: sample_z,\n self.inputs: sample_inputs,\n },\n )\n\n num_images = samples.shape[0]\n images = (samples + 1.) / 2\n size = (int(np.floor(np.sqrt(num_images))), int(np.ceil(np.sqrt(num_images))))\n h, w = images.shape[1], images.shape[2]\n img = np.zeros((h * size[0], w * size[1], self.c_dim))\n for idx, image in enumerate(images):\n i = idx % size[1]\n j = idx // size[1]\n img[j * h:j * h + h, i * w:i * w + w, :] = image\n\n scipy.misc.imsave('train_{:03d}_{:03d}.png'.format(epoch, idx), np.squeeze(img))\n print(\"[Sample] d_loss: %.8f, g_loss: %.8f\" % (d_loss, g_loss))\n\n except:\n print(\"one pic error!...\")\n\n if np.mod(counter, 500) == 2:\n self.save(self.checkpoint_dir, counter)\n\n def half(self, num):\n return int(np.ceil(num / 2))\n\n def conv2d(self, input_, output_dim, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name=\"conv2d\"):\n with tf.variable_scope(name):\n w = tf.get_variable('w', [k_h, k_w, input_.get_shape()[-1], output_dim],\n initializer=tf.truncated_normal_initializer(stddev=stddev))\n conv = tf.nn.conv2d(input_, w, strides=[1, d_h, d_w, 1], padding='SAME')\n\n biases = tf.get_variable('biases', [output_dim], initializer=tf.constant_initializer(0.0))\n conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape())\n\n return conv\n\n def deconv2d(self, input_, output_shape, k_h=5, k_w=5, d_h=2, d_w=2, stddev=0.02, name=\"deconv2d\", with_w=False):\n with tf.variable_scope(name):\n # filter : [height, width, output_channels, in_channels]\n w = tf.get_variable('w', [k_h, k_w, output_shape[-1], input_.get_shape()[-1]],\n initializer=tf.random_normal_initializer(stddev=stddev))\n\n try:\n deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape,\n strides=[1, d_h, d_w, 1])\n\n # Support for verisons of TensorFlow before 0.7.0\n except AttributeError:\n deconv = tf.nn.deconv2d(input_, w, output_shape=output_shape,\n strides=[1, d_h, d_w, 1])\n\n biases = tf.get_variable('biases', [output_shape[-1]], initializer=tf.constant_initializer(0.0))\n deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape())\n\n if with_w:\n return deconv, w, biases\n else:\n return deconv\n\n def lrelu(self, x, leak=0.2, name=\"lrelu\"):\n return tf.maximum(x, leak * x)\n\n def linear(self, input_, output_size, scope=None, stddev=0.02, bias_start=0.0, with_w=False):\n shape = input_.get_shape().as_list()\n\n with tf.variable_scope(scope or \"Linear\"):\n matrix = tf.get_variable(\"Matrix\", [shape[1], output_size], tf.float32,\n tf.random_normal_initializer(stddev=stddev))\n bias = tf.get_variable(\"bias\", [output_size],\n initializer=tf.constant_initializer(bias_start))\n if with_w:\n return tf.matmul(input_, matrix) + bias, matrix, bias\n else:\n return tf.matmul(input_, matrix) + bias\n\n def build_model(self):\n image_dims = [self.image_h, self.image_w, self.c_dim]\n\n self.inputs = tf.placeholder(\n tf.float32, [self.batch_size] + image_dims, name='real_images')\n\n inputs = self.inputs\n\n self.z = tf.placeholder(\n tf.float32, [None, self.z_dim], name='z')\n self.z_sum = histogram_summary(\"z\", self.z)\n\n self.G = self.generator(self.z)\n self.D, self.D_logits = self.discriminator(inputs)\n\n self.sampler = self.sampler(self.z)\n self.D_, self.D_logits_ = self.discriminator(self.G, reuse=True)\n\n self.d_sum = histogram_summary(\"d\", self.D)\n self.d__sum = histogram_summary(\"d_\", self.D_)\n self.G_sum = image_summary(\"G\", self.G)\n\n def sigmoid_cross_entropy_with_logits(x, y):\n try:\n return tf.nn.sigmoid_cross_entropy_with_logits(logits=x, labels=y)\n except:\n return tf.nn.sigmoid_cross_entropy_with_logits(logits=x, targets=y)\n\n self.d_loss_real = tf.reduce_mean(\n sigmoid_cross_entropy_with_logits(self.D_logits, tf.ones_like(self.D)))\n self.d_loss_fake = tf.reduce_mean(\n sigmoid_cross_entropy_with_logits(self.D_logits_, tf.zeros_like(self.D_)))\n self.g_loss = tf.reduce_mean(\n sigmoid_cross_entropy_with_logits(self.D_logits_, tf.ones_like(self.D_)))\n\n self.d_loss_real_sum = scalar_summary(\"d_loss_real\", self.d_loss_real)\n self.d_loss_fake_sum = scalar_summary(\"d_loss_fake\", self.d_loss_fake)\n\n self.d_loss = self.d_loss_real + self.d_loss_fake\n\n self.g_loss_sum = scalar_summary(\"g_loss\", self.g_loss)\n self.d_loss_sum = scalar_summary(\"d_loss\", self.d_loss)\n\n t_vars = tf.trainable_variables()\n\n self.d_vars = [var for var in t_vars if 'd_' in var.name]\n self.g_vars = [var for var in t_vars if 'g_' in var.name]\n\n self.saver = tf.train.Saver()\n\n # 生成判别器\n def discriminator(self, image, reuse=False):\n # 为了节约变量存储空间,通过共享变量作用域(variable_scope)来实现共享变量\n with tf.variable_scope(\"discriminator\") as scope:\n if reuse:\n scope.reuse_variables()\n\n # 直接上来对图片数据就是一个卷积之后激活……太简单粗暴了吧\n h0 = self.lrelu(self.conv2d(image, self.df_dim, name='d_h0_conv'))\n # 后面几层归一化一下再卷积\n h1 = self.lrelu(self.d_bn1(self.conv2d(h0, self.df_dim * 2, name='d_h1_conv')))\n h2 = self.lrelu(self.d_bn2(self.conv2d(h1, self.df_dim * 4, name='d_h2_conv')))\n h3 = self.lrelu(self.d_bn3(self.conv2d(h2, self.df_dim * 8, name='d_h3_conv')))\n h4 = self.linear(tf.reshape(h3, [self.batch_size, -1]), 1, 'd_h4_lin')\n\n return tf.nn.sigmoid(h4), h4\n\n # 生成器,直接用它和种子z生成所需图像\n def generator(self, z):\n # 在作用域中共享变量\n with tf.variable_scope(\"generator\") as scope:\n # 获取宽高及不同倍率缩放的结果\n s_h, s_w = self.image_h, self.image_w\n s_h2, s_w2 = self.half(s_h), self.half(s_w)\n s_h4, s_w4 = self.half(s_h2), self.half(s_w2)\n s_h8, s_w8 = self.half(s_h4), self.half(s_w4)\n s_h16, s_w16 = self.half(s_h8), self.half(s_w8)\n\n # 通过输入的z构建第一层线性模型\n self.z_, self.h0_w, self.h0_b = self.linear(\n z, self.gf_dim * 8 * s_h16 * s_w16, 'g_h0_lin', with_w=True)\n\n self.h0 = tf.reshape(\n # 在这里,64*64的1/16为4*4,第三维是128*8=1024\n self.z_, [-1, s_h16, s_w16, self.gf_dim * 8])\n h0 = tf.nn.relu(self.g_bn0(self.h0))\n\n self.h1, self.h1_w, self.h1_b = self.deconv2d(\n # CONV 1,第一次小卷积,结果是8*8*512\n h0, [self.batch_size, s_h8, s_w8, self.gf_dim * 4], name='g_h1', with_w=True)\n h1 = tf.nn.relu(self.g_bn1(self.h1))\n\n h2, self.h2_w, self.h2_b = self.deconv2d(\n # CONV 2,结果是16*16*256\n h1, [self.batch_size, s_h4, s_w4, self.gf_dim * 2], name='g_h2', with_w=True)\n h2 = tf.nn.relu(self.g_bn2(h2))\n\n h3, self.h3_w, self.h3_b = self.deconv2d(\n # CONV 3,结果是32*32*128\n h2, [self.batch_size, s_h2, s_w2, self.gf_dim * 1], name='g_h3', with_w=True)\n h3 = tf.nn.relu(self.g_bn3(h3))\n\n h4, self.h4_w, self.h4_b = self.deconv2d(\n # CONV 4,结果是64*64*3,就是最后的结果图\n h3, [self.batch_size, s_h, s_w, self.c_dim], name='g_h4', with_w=True)\n\n return tf.nn.tanh(h4)\n\n # 共享变量,其他和生成器差不多\n def sampler(self, z):\n with tf.variable_scope(\"generator\") as scope:\n scope.reuse_variables()\n\n s_h, s_w = self.image_h, self.image_w\n s_h2, s_w2 = self.half(s_h), self.half(s_w)\n s_h4, s_w4 = self.half(s_h2), self.half(s_w2)\n s_h8, s_w8 = self.half(s_h4), self.half(s_w4)\n s_h16, s_w16 = self.half(s_h8), self.half(s_w8)\n\n # project `z` and reshape\n h0 = tf.reshape(\n self.linear(z, self.gf_dim * 8 * s_h16 * s_w16, 'g_h0_lin'),\n [-1, s_h16, s_w16, self.gf_dim * 8])\n h0 = tf.nn.relu(self.g_bn0(h0, train=False))\n\n h1 = self.deconv2d(h0, [self.batch_size, s_h8, s_w8, self.gf_dim * 4], name='g_h1')\n h1 = tf.nn.relu(self.g_bn1(h1, train=False))\n\n h2 = self.deconv2d(h1, [self.batch_size, s_h4, s_w4, self.gf_dim * 2], name='g_h2')\n h2 = tf.nn.relu(self.g_bn2(h2, train=False))\n\n h3 = self.deconv2d(h2, [self.batch_size, s_h2, s_w2, self.gf_dim * 1], name='g_h3')\n h3 = tf.nn.relu(self.g_bn3(h3, train=False))\n\n h4 = self.deconv2d(h3, [self.batch_size, s_h, s_w, self.c_dim], name='g_h4')\n\n return tf.nn.tanh(h4)\n\n def model_dir(self):\n return \"{}_{}_{}\".format(self.batch_size, self.image_h, self.image_w)\n\n # 保存训练好的模型。创建检查点文件夹,如果路径不存在,则创建;然后将其保存在这个文件夹下。\n def save(self, checkpoint_dir, step):\n model_name = \"DCGAN.model\"\n checkpoint_dir = os.path.join(checkpoint_dir, self.model_dir())\n\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n\n self.saver.save(self.sess,\n os.path.join(checkpoint_dir, model_name),\n global_step=step)\n\n # 读取检查点,获取路径,重新存储检查点,并且计数。打印成功读取的提示;如果没有路径,则打印失败的提示。\n def load(self, checkpoint_dir):\n import re\n print(\" [*] Reading checkpoints...\")\n checkpoint_dir = os.path.join(checkpoint_dir, self.model_dir())\n\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir)\n if ckpt and ckpt.model_checkpoint_path:\n ckpt_name = os.path.basename(ckpt.model_checkpoint_path)\n self.saver.restore(self.sess, os.path.join(checkpoint_dir, ckpt_name))\n counter = int(next(re.finditer(\"(\\d+)(?!.*\\d)\", ckpt_name)).group(0))\n print(\" [*] Success to read {}\".format(ckpt_name))\n return True, counter\n else:\n print(\" [*] Failed to find a checkpoint\")\n return False, 0\n\n\nif __name__ == \"__main__\":\n dcgan = DCGAN()\n with dcgan.sess.as_default():\n dcgan.train()\n","sub_path":"201-tfDcGan/dcgan.py","file_name":"dcgan.py","file_ext":"py","file_size_in_byte":18607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"569427120","text":"import csv\nimport sys\n\nif __name__ == \"__main__\":\n\n\tnouns = open(sys.argv[1],newline='')\n\tranked = open(sys.argv[2],newline='')\n\n\tcsvNouns = csv.DictReader(nouns, fieldnames=['word','speak','writ'])\n\tcsvRanked = csv.DictReader(ranked, fieldnames=['place','rank', 'word','part'])\n\t\n\t# if we need to purify CSV\n\tif len(sys.argv) == 4:\n\t\tnewNouns = open(sys.argv[3], 'w')\n\t\twriter = csv.DictWriter(newNouns, fieldnames=['word','speak','writ'])\n\t\tfor row in csvNouns:\n\t\t\tword = row['word']\n\t\t\twriter.writerow({'word':word.strip(), 'speak':row['speak'],'writ':row['writ']})\n\n\t# work starts here\n\tl = tuple(i for i in csvRanked)\n\n\tfor row in csvNouns:\n\t\tword = row['word']\n\t\tflag = 0\n\t\tfor r in l:\n\t\t\tif word == r['word'] and r['part'] == 'adv':\n\t\t\t\tprint(\"{},{},{},{}\".format(word,row['speak'],r['place'],r['part']))\n\t\t\t\tflag = 1\n\t\tif flag == 0:\n\t\t\tprint(\"{},{}\".format(word,row['speak']))","sub_path":"partsOfSpeech.py","file_name":"partsOfSpeech.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"244369529","text":"from pmp.rules import ChamberlinCourant\nfrom pmp.preferences import Ordinal, Profile\n\n# In case of CCB default is ILP\n# Let's give a try Bruteforce implementation\n\nk = 2\norders = [\n [1, 2, 0],\n [2, 1, 0],\n [2, 0, 1],\n [1, 2, 0],\n [1, 0, 2]\n]\n\npreferences = [Ordinal(o) for o in orders]\ncandidates = [0, 1, 2]\n\nprofile = Profile(candidates, preferences)\n\n# No thresholds needed for approximation\ncc = ChamberlinCourant()\n\ncommittee_cc = list(cc.find_committee(k, profile))\ncommittee_cc_greedy = list(cc.find_committee(k, profile, method='Approx_Greedy'))\ncommittee_cc_p = list(cc.find_committee(k, profile, method='Approx_P'))\n\nscore_cc = cc.committee_score(committee_cc, profile)\nscore_ccb_greedy = cc.committee_score(committee_cc_greedy, profile)\nscore_ccb_p = cc.committee_score(committee_cc_p, profile)\n\nprint('Selected committees:')\nprint('CC: {} \\tscore: {}'.format(list(committee_cc), score_cc))\nprint('CC (Greedy): {} \\tscore: {}'.format(list(committee_cc_greedy), score_ccb_greedy))\nprint('CC (P): {} \\tscore: {}'.format(list(committee_cc_p), score_ccb_p))\n","sub_path":"examples/introspection/approx_cc.py","file_name":"approx_cc.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"167531216","text":"refresh = 3600\nversion = 20161106.01\n\nurls = ['http://www.macrumors.com',\n\t'http://feeds.macrumors.com/MacRumors-All']\nregex = [r'^https?:\\/\\/[^\\/]*macrumors\\.com\\/',\n\t r'^https?:\\/\\/[^\\/]*feedburner\\.com\\/']\t\nvideoregex = [r'^https?:\\/\\/(?:www\\.)?youtube\\.com\\/embed\\/']\nliveregex = [r'live-coverage',\n\t r'-live']\n\n\nwikidata = 'Q6722109'\n","sub_path":"services/web__macrumors_com.py","file_name":"web__macrumors_com.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"428155510","text":"# -*- coding: utf-8 -*- #\n# Copyright 2021 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Command to resume a currently running transfer operation.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.util import apis\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.transfer import name_util\n\n\nclass Resume(base.Command):\n \"\"\"Resume a currently paused transfer operation.\"\"\"\n\n detailed_help = {\n 'DESCRIPTION':\n \"\"\"\\\n Resume a currently paused transfer operation.\n \"\"\",\n 'EXAMPLES':\n \"\"\"\\\n To resume an operation, run:\n\n $ {command} OPERATION-NAME\n \"\"\",\n }\n\n @staticmethod\n def Args(parser):\n parser.add_argument(\n 'name',\n help='The name of the paused transfer operation you want to resume.')\n\n def Run(self, args):\n client = apis.GetClientInstance('transfer', 'v1')\n messages = apis.GetMessagesModule('transfer', 'v1')\n\n formatted_name = name_util.add_operation_prefix(args.name)\n client.transferOperations.Resume(\n messages.StoragetransferTransferOperationsResumeRequest(\n name=formatted_name))\n","sub_path":"lib/surface/transfer/operations/resume.py","file_name":"resume.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"565787633","text":"\"\"\" Compiled: 2020-09-18 10:38:55 \"\"\"\n\n#__src_file__ = \"extensions/ExclusionList/etc/FInstrumentExclusionList.py\"\n\"\"\"-------------------------------------------------------------------------------------------------------\nMODULE\n FInstrumentExclusionList\n\n (c) Copyright 2016 FIS FRONT ARENA. All rights reserved.\n\nDESCRIPTION\n\n-------------------------------------------------------------------------------------------------------\"\"\"\nimport acm\nimport FAssetManagementUtils\nimport csv\nimport FRunScriptGUI\n\nlogger = FAssetManagementUtils.logger\nlogDict = FAssetManagementUtils.logDict\n\nclass InstrumentExclusionListVariables(FRunScriptGUI.AelVariablesHandler):\n\n def SubGroupsRecursive(self, exclusionList):\n returnGroups = []\n if exclusionList.Terminal():\n returnGroups.append(exclusionList)\n for subList in exclusionList.SubGroups():\n returnGroups.extend(self.SubGroupsRecursive(subList))\n return returnGroups\n \n def ExclusionListPageGroups(self):\n topItem = acm.FPageGroup['ExclusionList']\n if topItem:\n leafSubgroups = self.SubGroupsRecursive(topItem)\n return leafSubgroups\n else:\n return []\n \n def AelVariables(self):\n filepathTT = 'Filepath to a csv file with an \"ISIN\" column to identify the instruments'\n pageGroupTT = 'Page Group to apply actions to'\n actionTT = 'Choose action to apply to page group'\n filter = \"CSV Files (*.csv)|*.csv\"\n pageGroups = self.ExclusionListPageGroups()\n ael_variables = [\n ['FILEPATH', 'Input File', FRunScriptGUI.InputFileSelection(filter), None, FRunScriptGUI.InputFileSelection(filter), 1, 1,\n filepathTT, None, 1],\n ['PAGE_GROUP', 'Page Group', 'FPageGroup', pageGroups, None, 1, 0, pageGroupTT, None, bool(pageGroups)],\n ['ACTION', 'Action', 'string', [\"Add Instruments\", \"Replace Instruments\", \"Remove Instruments\"], \"\", 1, 0, actionTT, None],\n ['LOG_MODE', 'Logmode_Logging', 'string', sorted(logDict), '1. Normal', 1, 0, log_tip]\n ] \n return ael_variables\n \n def __init__(self):\n FRunScriptGUI.AelVariablesHandler.__init__(self, self.AelVariables())\n\n\nclass ScriptHandler():\n\n def __init__(self, params, instruments):\n self.filepath = str(params['FILEPATH'])\n self.pageGroup = params['PAGE_GROUP']\n self.action = params['ACTION']\n self.instruments = instruments\n \n def TakeAction(self):\n if self.action == 'Add Instruments':\n self.AddInstrumentsToPageGroup()\n elif self.action == 'Replace Instruments':\n self.ReplaceInstruments()\n else:\n self.RemoveListedInstruments()\n self.CommitPageGroup(self.pageGroup)\n \n def ReplaceInstruments(self):\n self.RemoveAllInstruments()\n self.AddInstrumentsToPageGroup()\n \n def AddInstrumentsToPageGroup(self):\n for instrument in self.instruments:\n if self.instrumentInExclusionList(instrument):\n continue\n else:\n self.CreateInstrGroupMap(instrument)\n\n def CreateInstrGroupMap(self, instrument):\n instrGroupMap = acm.FInstrGroupMap()\n instrGroupMap.Instrument(instrument)\n instrGroupMap.Group(self.pageGroup)\n try:\n instrGroupMap.Commit()\n logger.LOG('Added instrument with ISIN \"%s\" to Exclusion List %s' % (instrument.Isin(), self.pageGroup.Name()))\n except RuntimeError as e:\n logger.WLOG('Failed to create FInstrGroupMap for ISIN \"%s\" in group %s: %s' %\n (instrument.Isin(), self.pageGroup.Name(), str(e)))\n \n def RemoveAllInstruments(self):\n instruments = self.pageGroup.InstrumentsRecursively()\n for instrument in instruments:\n acm.FInstrGroupMap.Select01('instrument=%s and group=%s' % (instrument.Oid(), self.pageGroup.Oid()), None).Delete()\n logger.WLOG('Deleted instrument with ISIN \"%s\" from Exclusion List %s' % (instrument.Isin(), self.pageGroup.Name()))\n \n def RemoveListedInstruments(self):\n for instrument in self.instruments:\n instrGroup = acm.FInstrGroupMap.Select01('instrument=%s and group=%s' % (instrument.Oid(), self.pageGroup.Oid()), None)\n if instrGroup:\n instrGroup.Delete()\n logger.WLOG('Deleted instrument with ISIN \"%s\" from Exclusion List %s' % (instrument.Isin(), self.pageGroup.Name()))\n \n def instrumentInExclusionList(self, instrument):\n instrGroupMap = acm.FInstrGroupMap.Select01('instrument=%s and group=%s' % (instrument.Oid(), self.pageGroup.Oid()), None)\n if instrGroupMap:\n logger.DLOG('The InstrGroupMap with ISIN \"%s\" already exists. None is created.' % instrument.Isin())\n return True\n else:\n return False\n \n def CommitPageGroup(self, pageGroup):\n imgage = pageGroup.StorageImage()\n imgage.UpdateTime = acm.Time.TimeNow()\n imgage.Commit()\n if pageGroup.SuperGroup():\n self.CommitPageGroup(pageGroup.SuperGroup())\n \n\n# Run Script GUI Setup\nlog_tip = 'Logmode 0 shows WARNING and ERROR messages. Logmode 1 shows INFORMATION messages, and also includes the ' \\\n 'messages from Logmode 0. Logmode 2 shows DEBUG messages and includes all other message types. '\nael_variables = InstrumentExclusionListVariables()\n\ndef InitLogger(logMode):\n logger.Reinitialize(level=logDict[logMode],\n keep=None,\n logOnce=None,\n logToConsole=1,\n logToPrime=None,\n logToFileAtSpecifiedPath=None,\n filters=None,\n lock=None\n )\n\ndef ValidParams(params):\n if params['FILEPATH'] and params['PAGE_GROUP']:\n return True\n else:\n logger.WLOG('Missing Inputs')\n return False\n\ndef InstrumentsFromCsv(filepath):\n try:\n instruments = []\n with open(filepath, 'rb') as inputfile:\n exclusionListReader = csv.DictReader(inputfile)\n for row in exclusionListReader:\n instrument = InstrumentFromRow(row)\n if instrument:\n instruments.append(instrument)\n return instruments\n except IOError as e:\n logger.WLOG('Failed to open file %s' % (e))\n except KeyError as e:\n logger.WLOG('Failed find field %s in file' % (e))\n return None\n \ndef InstrumentFromRow(row):\n isin = row['ISIN'].strip()\n if isin:\n instrument = acm.FInstrument.Select01('isin = {0}'.format(isin), None)\n if instrument:\n return instrument\n else:\n logger.WLOG('Failed to find instrument %s' % (row))\n return None\n\ndef ael_main(params):\n\n InitLogger(params['LOG_MODE'])\n\n if params['PAGE_GROUP']:\n instruments = InstrumentsFromCsv(str(params['FILEPATH']))\n if ValidParams(params) and instruments:\n scriptHandler = ScriptHandler(params, instruments)\n scriptHandler.TakeAction()\n else:\n logger.LOG('No page group found')\n raise IOError('No page group found. Create a page definition folder called ExclusionList and store your page groups there.')\n","sub_path":"Extensions/ExclusionList/FPythonCode/FInstrumentExclusionList.py","file_name":"FInstrumentExclusionList.py","file_ext":"py","file_size_in_byte":7304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"11952554","text":"# Using a function check the list for duplicate names. Create a new list by removing the duplicates.\nnames = ['Alex', 'John', 'Mary', 'Steve', 'John', 'Steve']\nnew_names = []\ndef remove_duplicates(names):\n for duplicates in names:\n if duplicates not in new_names:\n new_names.append(duplicates)\n return new_names\n\nprint(remove_duplicates(names))","sub_path":"02-week/4-friday/labs/angelo/coding-challenge-1.py","file_name":"coding-challenge-1.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"189694089","text":"\"\"\"This is the module :py:mod:`unified_plotting.config `.\n\nIt provides a central configuration system for the\npackage :py:mod:`unified_plotting`.\n\nIts main purpose is to provide **global package settings** that\ndetermine the **basic style used in every plot**.\nEach individual setting comes with a sensible default value that is\nloaded during import of the package but can be altered by the user\nduring runtime. Once some settings were modified, they can also be\nexported as JSON file and loaded again whenever desired.\nIn this way, user-defined styles can be created and reused.\n\n\nChange the settings\n-------------------\n\nThe current settings are stored in the object\n:py:obj:`unified_plotting.config.settings`.\n\n- Its members can be accessed and modified via dot notation,\n for example:\n\n .. code-block:: python\n\n import unified_plotting as up\n up.config.settings.x_labels_color = \"#008800\"\n up.config.settings.x_labels_fontname = \"Arial\"\n up.config.settings.y_labels_color = \"#008800\"\n up.config.settings.y_labels_fontname = \"Arial\"\n\n\nReport the current settings\n---------------------------\n\n- The function :py:func:`unified_plotting.config.report`\n can be used to get a list of available options as well as their\n currently assigned values.\n\n .. code-block:: python\n\n import unified_plotting as up\n up.config.report()\n\n\nSave and restore settings\n-------------------------\n\nThe module :py:mod:`unified_plotting.config` contains following\nfunctions that interact with the global package settings.\n\"\"\"\n\nimport json as _json\nimport sys as _sys\nfrom pprint import pprint as _pprint\n\nfrom pkg_resources import resource_string as _resource_string\n\nfrom ..utilities import operating_system as _operating_system\n\n\nclass _GenericSettings:\n \"\"\"Helper class for automatical conversion between nested JSON data and nested Python objects.\n\n This allows to load settings from a JSON file and provide it as a\n nested object whose members can be accessed and set via simple\n dot notation.\n\n References\n ----------\n - https://stackoverflow.com/questions/43776223/converting-nested-json-into-python-object\n\n \"\"\"\n\n @classmethod\n def _from_dict(cls, given_dict):\n obj = cls()\n obj.__dict__.update(given_dict)\n return obj\n\n @staticmethod\n def _to_dict(settings_obj):\n settings_json = _json.dumps(settings_obj, sort_keys=True, default=lambda obj: obj.__dict__)\n settings_dict = _json.loads(settings_json)\n return settings_dict\n\n def __str__(self):\n return str(self.__class__._to_dict(self))\n\n\ndef load_defaults():\n \"\"\"Load default settings of this package.\n\n This function is called automatically when the package is loaded.\n\n \"\"\"\n data_json_str = _resource_string(__name__, 'settings.json').decode()\n data = _json.loads(data_json_str, object_hook=_GenericSettings._from_dict)\n _THIS_MODULE.settings = data\n\n\ndef save_defaults_to_json(filepath):\n \"\"\"Save the default settings of this package to a JSON file.\n\n It may be used as starting point to create a file with user-defined settings.\n Only the contained keys will be recognized and the values have to be valid JSON\n (e.g. true instead of Python's True, null instead of Python's None).\n\n Parameters\n ----------\n filepath : str\n Filepath of the created JSON file.\n If the file exists it will be overwritten without warning.\n If the path does not end with '.json' it will be changed to do so.\n If the parent directory does not exist it will be created.\n\n Returns\n -------\n filepath : str\n Filepath of the generated JSON file, guaranteed to end with \".json\".\n\n \"\"\"\n # Precondition\n filepath = _operating_system.ensure_file_extension(filepath, 'json')\n _operating_system.ensure_parent_directory(filepath)\n\n # Transformation\n data_json_str = _resource_string(__name__, 'settings.json').decode()\n with open(filepath, 'w') as file_handle:\n file_handle.write(data_json_str)\n return filepath\n\n\ndef load_from_json(filepath):\n \"\"\"Load settings from a JSON file.\n\n Parameters\n ----------\n filepath : str\n Filepath of the JSON file that contains the settings.\n\n \"\"\"\n with open(filepath, 'r') as file_handle:\n data = _json.load(file_handle, object_hook=_GenericSettings._from_dict)\n _THIS_MODULE.settings = data\n\n\ndef save_to_json(filepath):\n \"\"\"Save the current settings to a JSON file.\n\n It can be used to load the same settings in another session.\n\n Parameters\n ----------\n filepath : str\n Filepath of the created JSON file.\n If the file exists it will be overwritten without warning.\n If the path does not end with '.json' it will be changed to do so.\n If the parent directory does not exist it will be created.\n\n Returns\n -------\n filepath : str\n Filepath of the generated JSON file, guaranteed to end with \".json\".\n\n \"\"\"\n # Precondition\n filepath = _operating_system.ensure_file_extension(filepath, 'json')\n _operating_system.ensure_parent_directory(filepath)\n\n # Transformation\n data = _THIS_MODULE.settings\n with open(filepath, 'w') as file_handle:\n _json.dump(data, file_handle, indent=4, sort_keys=True, default=lambda obj: obj.__dict__)\n return filepath\n\n\ndef report():\n \"\"\"Print a report of the current settings.\"\"\"\n settings_obj = _THIS_MODULE.settings\n settings_dict = _GenericSettings._to_dict(settings_obj)\n _pprint(settings_dict)\n\n\n# https://stackoverflow.com/questions/1977362/how-to-create-module-wide-variables-in-python\n_THIS_MODULE = _sys.modules[__name__]\n_THIS_MODULE.settings = None\nload_defaults()\n","sub_path":"unified_plotting/_config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"190127532","text":"# 自定义一个 python 函数,实现 map() 函数的功能。\n\n# class CustomIt():\n# def __init__(self, default_val, limit_val, custom_func):\n# self.val = default_val\n# self.limit = limit_val\n# self.func = custom_func\n# def __iter__(self):\n# return self.val\n# def __next__(self):\n# if self.val <= self.limit:\n# self.val = self.func(self.val)\n# return self.val\n# else: \n# raise StopIteration\n\ndef test(item):\n print(item)\n return item + 2\n\ndef customMap(custom_func, custom_coll):\n tempList = []\n for item in custom_coll:\n tempList.append(custom_func(item))\n return iter(tempList)\n\n\nif __name__ == '__main__': \n print(list(map(test, [1,2,3,4,5])))\n # pass\n print(list(customMap(test, [1,2,3,4,5])))\n","sub_path":"week08/homework2.py","file_name":"homework2.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"512563247","text":"# This file keeps track of what objects we have, and is responsible for\n# calculating positions and enforcing constraints on those objects.\n# Eventually, the core solver should be moved to a new file.\n# Actually, the solver should be entirely rewritten.\n\nfrom math import sqrt\nfrom numpy import array, dot, vdot, matrix\nfrom numpy.linalg import inv\n\n\nclass ObjectManager(object):\n def __init__(self):\n # Points are each assigned a number; next_point_idx contains the number\n # to assign to the next point we allocate.\n self._next_point_idx = 0\n # The set of indices of points that are active.\n # This won't necessarily be the interval [0, next_point_idx) because\n # points may be removed.\n self._all_points = set()\n # The current coordinates of each point. Maps point indices to\n # (x, y) tuples.\n self._point_coords = {}\n # LRU of point indices. This is used to be a bit smarter when we're\n # dragging points: we'll try harder to keep more recently moved\n # points where they are.\n self._point_lru = []\n # Caches of various internal things I should really document\n # at some point.\n self._cached_matrix = None\n self._cached_target = None\n self._cached_point_to_matrix = None\n self._target_map_x = {}\n self._target_map_y = {}\n # All primitives we have.\n self.primitives = []\n # All primitives that should be drawn on the screen.\n self.draw_primitives = []\n\n def closest(self, x, y):\n '''\n Determine the primitive \"closest\" to the given coordinates.\n '''\n dist = None\n p = None\n for primitive in self.primitives:\n this_dist = primitive.dist((x, y))\n if this_dist is not None and (p is None or this_dist < dist):\n dist = this_dist\n p = primitive\n return (p, dist)\n\n def add_primitive(self, primitive, draw=True):\n self.primitives.append(primitive)\n if draw:\n self.draw_primitives.append(primitive)\n\n def point_dist(self, p1, p2):\n dx = p1[0] - p2[0]\n dy = p1[1] - p2[1]\n return (dx*dx + dy*dy)\n\n def alloc_point(self, x, y):\n old = self._next_point_idx\n self._next_point_idx += 1\n self._all_points.add(old)\n self._point_lru.append(old)\n self._cached_matrix = None\n self._cached_target = None\n self._point_coords[old] = (x, y)\n\n return old\n\n def free_point(self, point_idx):\n self._all_points.remove(self.point_idx)\n\n def _lru_update(self, p):\n for i in range(len(self._point_lru)):\n if self._point_lru[i] == p:\n self._point_lru = ([p] + self._point_lru[0:i]\n + self._point_lru[i+1:])\n break\n\n def set_point_coords(self, point, x, y):\n self._lru_update(point)\n self._point_coords[point] = (x, y)\n self._update_point(point, x, y)\n\n def point_x(self, point):\n return self._point_coords[point][0]\n\n def point_y(self, point):\n return self._point_coords[point][1]\n\n def point_coords(self, point):\n return (self.point_x(point), self.point_y(point))\n\n # TODO: most stuff below here is absolutely terrible and inefficient\n # and should be rewritten.\n\n def add_ortho_row(self, ortho_m, new_row):\n cur_row = matrix(new_row)\n\n for other_row in ortho_m:\n dot_prod = vdot(new_row, other_row)\n cur_row = cur_row - dot_prod * matrix(other_row)\n magnitude = sqrt(vdot(cur_row.tolist(), cur_row.tolist()))\n cur_row = cur_row / magnitude\n ortho_m.append(cur_row.tolist()[0])\n\n def build_ortho(self, m):\n m = matrix(m)\n new_matrix = []\n for row in m:\n self.add_ortho_row(new_matrix, row)\n return new_matrix\n\n def can_add(self, ortho_m, idx):\n new_row = sum(om[idx] * matrix(om) for om in ortho_m)\n for i, j in enumerate(new_row.tolist()[0]):\n if i == idx and round(j, 5) != 1:\n return True\n if i != idx and round(j, 5) != 0:\n return True\n return False\n\n def build_matrix(self, constraints, point_to_matrix):\n n = len(self._all_points)\n targets = []\n matrix = []\n\n for (coeffs, target) in constraints:\n row = [0] * 2 * n\n for (pt, coeffx, coeffy) in coeffs:\n row[2 * point_to_matrix[pt]] = coeffx\n row[2 * point_to_matrix[pt] + 1] = coeffy\n matrix.append(row)\n targets.append(target)\n\n ortho_matrix = self.build_ortho(matrix)\n\n self._target_map_x = {}\n self._target_map_y = {}\n for pt in self._point_lru:\n coords = self._point_coords[pt]\n row1 = [0] * 2 * n\n row2 = [0] * 2 * n\n row1[2 * point_to_matrix[pt]] = 1\n row2[2 * point_to_matrix[pt] + 1] = 1\n\n if self.can_add(ortho_matrix, 2 * point_to_matrix[pt]):\n self._target_map_x[pt] = len(targets)\n targets.append(coords[0])\n matrix.append(row1)\n self.add_ortho_row(ortho_matrix, row1)\n\n if self.can_add(ortho_matrix, 2 * point_to_matrix[pt] + 1):\n self._target_map_y[pt] = len(targets)\n targets.append(coords[1])\n matrix.append(row2)\n self.add_ortho_row(ortho_matrix, row2)\n\n if len(matrix) == 2 * n:\n break\n\n # TODO: optimize this\n return (array(matrix), array(targets))\n\n def update_points(self):\n constraints = []\n for p in self.primitives:\n constraints = constraints + p.constraints()\n\n point_to_matrix = {}\n idx = 0\n for point in self._all_points:\n point_to_matrix[point] = idx\n idx += 1\n assert idx == len(self._all_points)\n m, t = self.build_matrix(constraints, point_to_matrix)\n self._cached_matrix = inv(m)\n self._cached_target = t\n self._cached_point_to_matrix = point_to_matrix\n sol = dot(self._cached_matrix, t)\n sol = zip(sol[::2], sol[1::2])\n for point, mat_point in point_to_matrix.iteritems():\n self._point_coords[point] = sol[mat_point]\n\n def _update_point(self, p, x, y):\n if p in self._target_map_x:\n self._cached_target[self._target_map_x[p]] = x\n if p in self._target_map_y:\n self._cached_target[self._target_map_y[p]] = y\n\n sol = dot(self._cached_matrix, self._cached_target)\n sol = zip(sol[::2], sol[1::2])\n for point, mat_point in self._cached_point_to_matrix.iteritems():\n self._point_coords[point] = sol[mat_point]\n","sub_path":"object_manager.py","file_name":"object_manager.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"485435374","text":"# No.16 3 sum closest\n# https://leetcode.com/problems/3sum-closest/\n\n\nclass Solution(object):\n def threeSumClosest(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n return solution1(nums, target)\n\n\ndef solution1(num, target):\n num.sort()\n distance = 100000\n res = 0\n\n for i in range(len(num) - 2):\n if i == 0 or num[i] > num[i - 1]:\n left = i + 1\n right = len(num) - 1\n\n while left < right:\n sum = num[left] + num[right] + num[i]\n\n if sum == target:\n return sum\n\n if abs(target - sum) < distance:\n distance = abs(target - sum)\n res = sum\n\n if sum < target:\n while left < right:\n left += 1\n if num[left] > num[left - 1]:\n break\n else:\n while left < right:\n right -= 1\n if num[right] < num[right + 1]:\n break\n return res\n","sub_path":"leetcode_py/16_3sum_closest/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"217627512","text":"#coding:utf-8\nimport uuid\nimport logging\nimport json\n\nimport constants\n\nclass Session(object):\n \"\"\"\n session数据工具类\n \"\"\"\n def __init__(self, request_handler):\n self.request_handler = request_handler\n session_id = self.request_handler.get_secure_cookie(\"session_id\")\n if not session_id:\n #用户第一次访问\n #生成唯一的session_id\n self.session_id = uuid.uuid4().get_hex()\n self.data = {}\n else:\n #取redis内的session_id数据\n try:\n data = self.redis.get(\"sess_%s\" % session_id)\n except Exception as e:\n logging.error(e)\n self.data = {}\n #判断取出的值是否为空\n if not data:\n self.data = {}\n else:\n self.data = json.loads(data)\n\n #保存session信息\n def save(self):\n json_data = json.dumps(self.data)\n try:\n self.redis.setex(\"sess_%s\" % self.session_id, constants.SESSION_EXPIRES_TIME, json_data)\n except Exception as e:\n logging.error(e)\n raise Exception(\"保存session失败\")\n self.request_handler.set_secure_cookie(\"session_id\")\n #删除session信息\n def clear(self):\n #删除浏览器端cookie信息\n self.request_handler.clear_cookie(\"session_id\", self.session_id)\n #删除后端匹配的session信息\n try:\n self.redis.delete(\"sess_%s\" % self.session_id)\n except Exception as e:\n logging.error(e)\n\n\n","sub_path":"tornado/ihome/utils/Session.py","file_name":"Session.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"503971466","text":"# -*- coding: utf-8 -*-\n# CREAR XML SIN FIRMA\n\nimport requests\nimport simplejson as json\nimport base64\nimport xmltodict\nfrom .Logs.RegistroEventos import *\n\n\nclass ENVIAR_MH:\n \"\"\"enviar xml\"\"\"\n #regEvento = RegistroEventos()\n\n def Enviar(self, _obj, _task, _body, _url_token, _url_recepcion):\n regEvento.AgregarNotificacion(_obj, \"Se envio XML a MH\")\n\n id = _obj.env['ola.mh.factura.envio'].create({\n 'task': str(_task),\n 'body': str(_body),\n 'id_account_invoice_parent': _obj.ids[0]\n })\n\n task = _task\n \n #resp = requests.post('https://idp.comprobanteselectronicos.go.cr/auth/realms/rut-stag/protocol/openid-connect/token', data=task)\n resp = requests.post(_url_token, data=task)\n\n if resp.ok:\n js = json.loads(resp._content)\n\n token = \"Bearer \" + js['access_token']\n headers = {\"Authorization\": token,\n \"Accept\": \"application/json\"\n }\n\n _obj.env['ola.mh.factura.envio'].browse(id.ids[0]).write({\n 'headers': str(headers)\n })\n\n body = _body\n resp = requests.post(_url_recepcion, headers = headers, json = body)\n #resp = requests.post('https://api.comprobanteselectronicos.go.cr/recepcion-sandbox/v1/recepcion', headers = headers, json = body)\n\n if resp.ok:\n #sms = resp.headers[\"Location\"]\n #sms = sms.encode('ascii','ignore').decode('ascii')\n _obj.env['ola.mh.factura.envio'].browse(id.ids[0]).write({\n 'respuesta': self.String(resp.reason) + \" | \" + self.String(resp.headers[\"Location\"]),\n 'activo': True\n })\n _obj.proceso_mh = \"Enviado Correctamente a MH\"\n regEvento.AgregarNotificacion(_obj, \"Enviado Correctamente a MH\")\n _obj.is_envio_xml_mh = True\n else:\n #error = resp.headers[\"X-Error-Cause\"]\n #error = error.encode('utf8','ignore').decode('ascii')\n _obj.proceso_mh = \"Error en Envio\"\n \n if 'X-Error-Cause' in resp.headers:\n _obj.env['ola.mh.factura.envio'].browse(id.ids[0]).write({\n 'error': self.String(resp.headers[\"X-Error-Cause\"])\n })\n regEvento.AgregarNotificacion(_obj, \"Error en Envio | \" + self.String(resp.headers[\"X-Error-Cause\"]))\n elif resp.content:\n _obj.env['ola.mh.factura.envio'].browse(id.ids[0]).write({\n 'error': self.String(resp.content)\n })\n regEvento.AgregarNotificacion(_obj, \"Error en Envio
    \" + self.String(resp.content))\n else:\n _obj.env['ola.mh.factura.envio'].browse(id.ids[0]).write({\n 'error': self.String(\"Servidor no disponible\")\n })\n regEvento.AgregarNotificacion(_obj, \"Error en Envio
    \" + self.String(\"Servidor no disponible\"))\n else: \n _obj.env['ola.mh.factura.envio'].browse(id.ids[0]).write({\n 'error': self.String(str(resp.status_code)) + \" | \" + self.String(str(resp._content))\n #'error': self.String(str(resp.status_code)) + \" | \" + self.String(resp._content)\n })\n _obj.proceso_mh = \"Error en el Token\"\n regEvento.AgregarNotificacion(_obj, \"Error en el Token\")\n \n def Consultar(self, _obj, _task, _clave_numerico_mh, _url_token, _url_consulta):\n id = _obj.env['ola.mh.factura.consulta'].create({\n 'task': str(_task),\n 'clave': str(_clave_numerico_mh),\n 'id_account_invoice_parent': _obj.ids[0]\n })\n \n regEvento.AgregarNotificacion(_obj, \"Consultar Comprobante\")\n\n task = _task\n\n #resp = requests.post('https://idp.comprobanteselectronicos.go.cr/auth/realms/rut-stag/protocol/openid-connect/token', data=task) \n resp = requests.post(_url_token, data=task)\n\n if resp.ok:\n js = json.loads(resp._content)\n\n token = \"Bearer \" + js['access_token']\n headers = {\"Authorization\": token,\n \"Accept\": \"application/json\"\n }\n\n _obj.env['ola.mh.factura.consulta'].browse(id.ids[0]).write({\n 'headers': str(headers)\n })\n\n #resp = requests.get('https://api.comprobanteselectronicos.go.cr/recepcion-sandbox/v1/recepcion/' + _clave_numerico_mh , headers = headers) \n resp = requests.get(_url_consulta + _clave_numerico_mh , headers = headers)\n\n if resp.ok:\n json_body = json.loads(resp._content)\n _obj.proceso_mh = \"Comprobante procesado por HM\"\n _obj.estado_hacienda_mh = str(json_body['ind-estado']).upper()\n \n _obj.env['ola.mh.factura.consulta'].browse(id.ids[0]).write({\n 'estado': self.String(json_body['ind-estado'])\n })\n \n regEvento.AgregarNotificacion(_obj, \"Estado: \" + str(json_body['ind-estado']).upper())\n\n if json_body['ind-estado'] == 'aceptado':\n if _obj.partner_id.email:\n _obj.is_enviar_correo = True\n\n if json_body['ind-estado'] == 'aceptado' or json_body['ind-estado'] == 'rechazado':\n _obj.env['ola.mh.factura.consulta'].browse(id.ids[0]).write({\n 'activo': True\n }) \n _obj.is_comprobar_xml_mh = True\n\n if 'respuesta-xml' in json_body:\n sms = base64.b64decode(json_body['respuesta-xml']);\n\n _obj.xml_mh_respuesta_binary = json_body['respuesta-xml']\n _obj.xml_mh_respuesta = sms\n\n js = json.loads(json.dumps(xmltodict.parse(sms)))\n\n _obj.env['ola.mh.factura.consulta'].browse(id.ids[0]).write({\n 'respuesta': self.String(js['MensajeHacienda']['DetalleMensaje'])\n }) \n regEvento.AgregarNotificacion(_obj, self.String(js['MensajeHacienda']['DetalleMensaje']))\n else:\n _obj.env['ola.mh.factura.consulta'].browse(id.ids[0]).write({\n 'error': self.String(resp.headers[\"X-Error-Cause\"])\n })\n _obj.proceso_mh = \"Comprobante no aceptado\"\n regEvento.AgregarNotificacion(_obj, \"Comprobante no aceptado\")\n\n else: \n _obj.env['ola.mh.factura.consulta'].browse(id.ids[0]).write({\n 'error': self.String(str(resp.status_code)) + \" | \" + self.String(str(resp._content))\n }) \n _obj.proceso_mh = \"Error en el Token\"\n regEvento.AgregarNotificacion(_obj, \"Error en el Token\")\n\n def String(self, _str):\n #_str = str(_str)\n if _str:\n if isinstance(_str, str):\n grupos = [('á','a'),('é','e'),('í','i'),('ó','o'),('ú','u'),\n ('Á','A'),('É','E'),('Í','I'),('Ó','O'),('Ú','U'),\n ('ñ','n'),('Ñ','n')]\n for grupo in grupos:\n _str = _str.replace(grupo[0],grupo[1])\n # _str = _str.decode('ascii', 'ignore').encode('ascii')\n elif isinstance(_str, unicode):\n grupos = [(u'á',u'a'),(u'é',u'e'),(u'í',u'i'),(u'ó',u'o'),(u'ú',u'u'),\n (u'Á',u'A'),(u'É',u'E'),(u'Í',u'I'),(u'Ó',u'O'),(u'Ú',u'U'),\n (u'ñ',u'n'),(u'Ñ',u'n')]\n for grupo in grupos:\n _str = _str.replace(grupo[0],grupo[1])\n # _str = _str.encode('ascii','ignore').decode('ascii')\n return _str\n \n \nenviar_mh = ENVIAR_MH()\n\n","sub_path":"OLA_MH/models_herencia/MH/ENVIAR_MH.py","file_name":"ENVIAR_MH.py","file_ext":"py","file_size_in_byte":8159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"282729781","text":"# 설치가 필요한 파이썬 라이브러리 정보.\n# pip install clickhouse-driver==0.1.3\n# pip install clickhouse-sqlalchemy==0.1.4\n# conda install sqlalchemy==1.3.16\n# pip install ipython-sql==0.4.0\n\nfrom sqlalchemy import create_engine, text\nimport numpy as np\nimport pandas as pd\nimport datetime\nfrom datetime import timedelta\nimport time\nimport sys\nimport os\n\nsys_path_list = sys.path\nprint(sys_path_list)\n# ML_Train_Framework directory의 절대 경로를 환경 변수에 추가.\nif sys_path_list.count(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))))) == 0 :\n sys.path.append(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))))))\n\nprint(sys.path)\n\nfrom ML_Framework_Applications.ETC.Logger import Logger\nfrom clickhouse_driver import Client\nimport argparse\n\nclass CLICK_YN_LABELING_CONTEXT :\n\n def __init__( self, clickhouse_id, clickhouse_password, maria_id, maria_password, local_clickhouse_id,\n local_clickhouse_password, local_clickhouse_db_name, logger_name = \"test\", logger_file=\"inner_logger.json\",Maria_DB = False ):\n\n self.clickhouse_id = clickhouse_id\n self.clickhouse_password = clickhouse_password\n\n self.maria_id = maria_id\n self.maria_password = maria_password\n\n self.local_clickhouse_id = local_clickhouse_id\n self.local_clickhouse_password = local_clickhouse_password\n self.local_clickhouse_db_name = local_clickhouse_db_name\n self.logger = Logger(logger_name)\n\n self.Click_House_Engine = None\n self.Click_House_Conn = None\n\n self.MariaDB_Engine = None\n self.MariaDB_Engine_Conn = None\n\n self.Maria_DB = Maria_DB\n\n self.connect_db()\n\n def connect_db(self) :\n self.Click_House_Engine = create_engine('clickhouse://{0}:{1}@192.168.3.230:8123/'\n 'MOBON_ANALYSIS'.format(self.clickhouse_id, self.clickhouse_password))\n self.Click_House_Conn = self.Click_House_Engine.connect()\n \n if self.Maria_DB : \n self.MariaDB_Engine = create_engine('mysql+pymysql://{0}:{1}@192.168.100.108:3306/dreamsearch'\n .format(self.maria_id, self.maria_password))\n self.MariaDB_Engine_Conn = self.MariaDB_Engine.connect()\n\n self.Local_Click_House_Engine = create_engine(\n 'clickhouse://{0}:{1}@localhost/{2}'.format(self.local_clickhouse_id, self.local_clickhouse_password,\n self.local_clickhouse_db_name))\n self.Local_Click_House_Conn = self.Local_Click_House_Engine.connect()\n return True\n\n def create_local_table(self, table_name):\n client = Client(host='localhost')\n DDL_sql = \"\"\"\n CREATE TABLE IF NOT EXISTS {0}.{1}\n (\n LOG_DTTM DateTime('Asia/Seoul'),\n STATS_DTTM UInt32,\n STATS_HH UInt8,\n STATS_MINUTE UInt8, \n MEDIA_SCRIPT_NO String,\n SITE_CODE String,\n ADVER_ID String,\n REMOTE_IP String,\n ADVRTS_PRDT_CODE Nullable(String),\n ADVRTS_TP_CODE Nullable(String),\n PLTFOM_TP_CODE Nullable(String),\n PCODE Nullable(String),\n PNAME Nullable(String), \n BROWSER_CODE Nullable(String),\n FREQLOG Nullable(String),\n T_TIME Nullable(String),\n KWRD_SEQ Nullable(String),\n GENDER Nullable(String),\n AGE Nullable(String),\n OS_CODE Nullable(String),\n FRAME_COMBI_KEY Nullable(String),\n CLICK_YN UInt8,\n BATCH_DTTM DateTime\n ) ENGINE = MergeTree\n PARTITION BY ( STATS_DTTM, STATS_MINUTE)\n ORDER BY (STATS_DTTM, STATS_HH)\n SAMPLE BY ( STATS_DTTM, STATS_MINUTE )\n TTL BATCH_DTTM + INTERVAL 90 DAY\n SETTINGS index_granularity=8192\n \"\"\".format(self.local_clickhouse_db_name, table_name)\n result = client.execute(DDL_sql)\n return result\n\n def create_new_local_table(self, table_name):\n client = Client(host='localhost')\n DDL_sql = \"\"\"\n CREATE TABLE IF NOT EXISTS {0}.{1}\n (\n LOG_DTTM DateTime('Asia/Seoul'),\n RANDOM_SAMPLE Float32,\n STATS_DTTM UInt32,\n STATS_HH UInt8,\n STATS_MINUTE UInt8, \n MEDIA_SCRIPT_NO String,\n SITE_CODE String,\n ADVER_ID String,\n REMOTE_IP String,\n ADVRTS_PRDT_CODE Nullable(String),\n ADVRTS_TP_CODE Nullable(String),\n PLTFOM_TP_CODE Nullable(String),\n PCODE Nullable(String),\n BROWSER_CODE Nullable(String),\n FREQLOG Nullable(String),\n T_TIME Nullable(String),\n KWRD_SEQ Nullable(String),\n GENDER Nullable(String),\n AGE Nullable(String),\n OS_CODE Nullable(String),\n FRAME_COMBI_KEY Nullable(String),\n CLICK_YN UInt8,\n BATCH_DTTM DateTime\n ) ENGINE = MergeTree\n PARTITION BY ( STATS_DTTM, STATS_MINUTE )\n PRIMARY KEY (STATS_DTTM, STATS_MINUTE)\n ORDER BY (STATS_DTTM, STATS_MINUTE)\n SAMPLE BY ( STATS_MINUTE )\n TTL BATCH_DTTM + INTERVAL 90 DAY\n SETTINGS index_granularity=8192\n \"\"\".format(self.local_clickhouse_db_name, table_name)\n result = client.execute(DDL_sql)\n return True\n\n def migrate_old_to_new_table(self, stats_dttm, old_table_name, new_table_name):\n self.connect_db()\n create_table_result = self.create_new_local_table(new_table_name)\n self.logger.log(\"create new table{0}\".format(new_table_name), create_table_result)\n media_script_list_sql = \"\"\"\n select \n distinct MEDIA_SCRIPT_NO\n from \n TEST.{0}\n where 1=1\n and STATS_DTTM= {1}\n \"\"\".format(old_table_name,str(stats_dttm))\n media_script_list_sql = text(media_script_list_sql)\n media_script_list = pd.read_sql(media_script_list_sql, self.Local_Click_House_Conn)['MEDIA_SCRIPT_NO']\n for MEDIA_SCRIPT_NO in media_script_list :\n log_data_sql = \"\"\"\n select \n *\n from TEST.{0}\n where 1=1\n and STATS_DTTM = {1}\n and MEDIA_SCRIPT_NO = '{2}'\n \"\"\".format(old_table_name, str(stats_dttm), MEDIA_SCRIPT_NO)\n log_data_sql = text(log_data_sql)\n try :\n log_data_df = pd.read_sql(log_data_sql, self.Local_Click_House_Conn)\n log_data_df.to_sql(new_table_name, con=self.Local_Click_House_Engine, index=False, if_exists='append')\n except Exception as e :\n self.logger.log(\"Error happend\",e)\n self.connect_db()\n log_data_df = pd.read_sql(log_data_sql, self.Local_Click_House_Conn)\n log_data_df.to_sql(new_table_name, con=self.Local_Click_House_Engine, index=False, if_exists='append')\n return True\n\n def create_entire_log_table(self, table_name):\n client = Client(host='localhost')\n DDL_sql = \"\"\"\n CREATE TABLE IF NOT EXISTS {0}.{1}\n (\n mediaId String,\n inventoryId String,\n frameId String,\n logType String,\n adType String,\n adProduct String,\n adCampain String,\n adverId String,\n productCode String,\n cpoint Decimal(13, 2),\n mpoint Decimal(13, 2),\n auid String,\n remoteIp String,\n platform String,\n device String,\n browser String,\n createdDate DateTime default now(),\n freqLog Nullable(String),\n tTime Nullable(String),\n kno Nullable(String),\n kwrdSeq Nullable(String),\n gender Nullable(String),\n age Nullable(String),\n osCode Nullable(String),\n price Nullable(Decimal(13, 2)),\n frameCombiKey Nullable(String)\n ) engine = MergeTree() \n PARTITION BY toYYYYMMDD(createdDate)\n PRIMARY KEY (mediaId, inventoryId, adverId) \n ORDER BY (mediaId, inventoryId, adverId) \n SAMPLE BY mediaId \n TTL createdDate + INTERVAL 90 DAY\n SETTINGS index_granularity = 8192\n \"\"\".format(self.local_clickhouse_db_name, table_name)\n result = client.execute(DDL_sql)\n return result\n\n def check_local_table_name(self, table_name):\n self.connect_db()\n check_table_name_sql = \"\"\"\n SHOW TABLES FROM {0}\n \"\"\".format(self.local_clickhouse_db_name)\n sql_text = text(check_table_name_sql)\n sql_result = list(pd.read_sql(sql_text, self.Local_Click_House_Conn)['name'])\n print(sql_result)\n if table_name in sql_result:\n return True\n else:\n return False\n\n def Extract_Click_Stats_Date(self, stats_dttm_hh, hours=1):\n str_stats_dttm = str(stats_dttm_hh)\n stats_date = datetime.datetime(int(str_stats_dttm[:4]), int(str_stats_dttm[4:6]), int(str_stats_dttm[6:8]),\n int(str_stats_dttm[8:]))\n hour_delta = timedelta(hours=hours)\n previus_date = stats_date + hour_delta\n previus_date = previus_date.strftime('%Y%m%d%H')\n return int(stats_dttm_hh), int(previus_date)\n\n def Extract_Click_Df(self, stats_dttm_hh) :\n self.connect_db()\n try :\n Click_Date_List = [self.Extract_Click_Stats_Date(stats_dttm_hh,1)[0],self.Extract_Click_Stats_Date(stats_dttm_hh,1)[1]]\n Click_Data_Df_List = []\n for Click_Date_Key in Click_Date_List:\n Click_Df_sql = \"\"\"\n select toTimeZone(createdDate, 'Asia/Seoul') as KOREA_DATE,\n inventoryId as MEDIA_SCRIPT_NO,\n adCampain as SITE_CODE,\n remoteIp as REMOTE_IP\n from MOBON_ANALYSIS.MEDIA_CLICKVIEW_LOG\n where 1 = 1\n and inventoryId <> ''\n and adCampain <> ''\n and remoteIp <> ''\n and logType = 'C'\n and toYYYYMMDD(createdDate) = {0}\n and toHour(createdDate) = {1}\n \"\"\".format(str(Click_Date_Key)[:-2], str(Click_Date_Key)[-2:])\n Click_Df_sql = text(Click_Df_sql)\n Click_Df = pd.read_sql_query(Click_Df_sql, self.Click_House_Conn)\n Click_Data_Df_List.append(Click_Df)\n self.Click_Df = pd.concat(Click_Data_Df_List)\n self.logger.log(\"Extract_click_Df_{0}\".format(stats_dttm_hh),\"success\")\n return True\n except Exception as e :\n self.logger.log(\"Error happend\",e)\n return False\n \n def Extract_Date_Range_From_DB(self) : \n self.connect_db()\n try : \n maria_db_sql = \"\"\"\n select min(stats_dttm) as initial_date, max(stats_dttm) as last_date from BILLING.MOB_CAMP_MEDIA_HH_STATS\n \"\"\"\n maria_db_sql = text(maria_db_sql)\n result = pd.read_sql(maria_db_sql,self.MariaDB_Engine_Conn)\n self.maria_initial_date = result['initial_date'].values[0]\n self.maria_last_date = result['last_date'].values[0]\n except Exception as e: \n\n self.logger.log(\"Error happend\",e)\n pass\n \n try :\n clickhouse_db_sql = \"\"\"\n select\n min(toYYYYMMDD(createdDate)) as initial_date\n max(toYYYYMMDD(createdDate)) as last_date \n from MOBON_ANALYSIS.MEDIA_CLICKVIEW_LOG\n where 1=1\n limit 10;\n \"\"\"\n clickhouse_db_sql = text(clickhouse_db_sql)\n result = pd.read_sql(clickhouse_db_sql, self.Click_House_Conn)\n self.clickhouse_initial_date = result['initial_date'].values[0]\n self.clickhouse_last_date = result['last_date'].values[0]\n except Exception as e: \n self.logger.log(\"Error happend\",e)\n pass\n return True\n\n def Extract_Media_Script_List(self, stats_dttm_hh, min_click_cnt = 5) :\n self.connect_db()\n Ms_List_Sql = \"\"\"\n SELECT\n tb.inventoryId as MEDIA_SCRIPT_NO, tb.cnt\n from\n (SELECT\n inventoryId, count(*) as cnt\n FROM MOBON_ANALYSIS.MEDIA_CLICKVIEW_LOG\n where 1 = 1\n and inventoryId <> ''\n and adCampain <> ''\n and remoteIp <> ''\n and logType = 'C'\n and toYYYYMMDD(createdDate) = {0}\n and toHour(createdDate) = {1}\n group by inventoryId\n order by count() desc) as tb\n where tb.cnt >= {2}\n \"\"\".format(str(stats_dttm_hh)[:-2], str(stats_dttm_hh)[-2:], min_click_cnt)\n try :\n Ms_List_Sql = text(Ms_List_Sql)\n Ms_result = pd.read_sql_query(Ms_List_Sql, self.Click_House_Conn)\n self.Ms_List = Ms_result['MEDIA_SCRIPT_NO']\n self.logger.log(\"Extract_Media_Script_list function\",\"Success\")\n return True\n except Exception as e :\n self.logger.log(\"Extract_Media_Script_list function\", e)\n return False\n\n def Extract_View_Df(self,\n stats_dttm_hh,\n table_name,\n Maximum_Data_Size = 2000000,\n Sample_Size = 500000) :\n \n Media_Script_No_Dict = self.Extract_Media_Script_List(stats_dttm_hh)\n i = 0\n if Media_Script_No_Dict == False :\n while i < 5 :\n i += 1\n Media_Script_No_Dict = self.Extract_Media_Script_List(stats_dttm_hh)\n if Media_Script_No_Dict == False:\n return \"Extract_Media_Script_List Function error\"\n Media_Script_cnt = self.Ms_List.shape[0]\n if Media_Script_cnt == 0 :\n return False\n print(\"Media_Script_Cnt shape is \", Media_Script_cnt )\n i = 0\n Total_Data_Cnt = 0\n Merged_Df_List = []\n for MEDIA_SCRIPT_NO in self.Ms_List :\n i += 1\n # print(\"{0}/{1} start\".format(i, Media_Script_List_Shape))\n View_Df_sql = \"\"\"\n select \n createdDate as LOG_DTTM,\n toYYYYMMDD(toTimeZone(createdDate, 'Asia/Seoul') ) as STATS_DTTM,\n toHour(toTimeZone(createdDate, 'Asia/Seoul') ) as STATS_HH,\n toMinute(toTimeZone(createdDate, 'Asia/Seoul') ) as STATS_MINUTE,\n inventoryId as MEDIA_SCRIPT_NO,\n adType as ADVRTS_TP_CODE,\n multiIf(\n adProduct IN ('mba', 'nor', 'banner', 'mbw'), '01',\n adProduct IN ('sky', 'mbb', 'sky_m'), '02',\n adProduct IN ('ico', 'ico_m'), '03',\n adProduct IN ('scn'), '04',\n adProduct IN ('nct', 'mct'), '05',\n adProduct IN ('pnt', 'mnt'), '07',\n 'null'\n ) as ADVRTS_PRDT_CODE,\n multiIf(\n platform IN ('web', 'w', 'W'), '01',\n platform IN ('mobile', 'm', 'M'), '02',\n 'null'\n ) as PLTFOM_TP_CODE,\n adCampain as SITE_CODE,\n adverId as ADVER_ID,\n productCode as PCODE,\n remoteIp as REMOTE_IP,\n visitParamExtractRaw(browser, 'code') as BROWSER_CODE,\n freqLog as FREQLOG,\n tTime as T_TIME,\n kwrdSeq as KWRD_SEQ,\n gender as GENDER,\n age as AGE,\n osCode as OS_CODE,\n frameCombiKey as FRAME_COMBI_KEY,\n now() as BATCH_DTTM\n from MOBON_ANALYSIS.MEDIA_CLICKVIEW_LOG\n where 1 = 1\n and inventoryId = '{0}'\n and adCampain <> ''\n and adType <> ''\n and remoteIp <> ''\n and logType = 'V'\n and toYYYYMMDD(createdDate) = {1}\n and toHour(createdDate) = {2}\n \"\"\".format(MEDIA_SCRIPT_NO, str(stats_dttm_hh)[:-2], str(stats_dttm_hh)[-2:])\n View_Df_sql = text(View_Df_sql)\n try:\n View_Df = pd.read_sql_query(View_Df_sql, self.Click_House_Conn)\n Click_View_Df = pd.merge(View_Df, self.Click_Df, on=['MEDIA_SCRIPT_NO', 'SITE_CODE', 'REMOTE_IP'],\n how='left')\n Merged_Df_List.append(Click_View_Df)\n except Exception as e:\n self.logger.log(\"Error happend\",e)\n self.connect_db()\n View_Df = pd.read_sql_query(View_Df_sql, self.Click_House_Conn)\n Click_View_Df = pd.merge(View_Df, self.Click_Df, on=['MEDIA_SCRIPT_NO', 'SITE_CODE', 'REMOTE_IP'],\n how='left')\n Merged_Df_List.append(Click_View_Df)\n time.sleep(15)\n Total_Data_Cnt += Click_View_Df.shape[0]\n if Total_Data_Cnt >= Maximum_Data_Size :\n break\n try : \n self.logger.log(\"extract log data {0}\".format(stats_dttm_hh), \"success\")\n Concated_Df = pd.concat(Merged_Df_List)\n Concated_Df['CLICK_YN'] = Concated_Df['KOREA_DATE'].apply(lambda x: 0 if pd.isnull(x) else 1)\n if Concated_Df.shape[0] <= Sample_Size:\n final_df = Concated_Df.drop(columns=['KOREA_DATE'])\n else:\n final_df = Concated_Df.drop(columns=['KOREA_DATE']).sample(Sample_Size)\n random_array = np.random.rand(final_df.shape[0],)\n final_df['RANDOM_SAMPLE'] = random_array\n self.connect_db()\n self.logger.log(\"Add data to df\",\"success\")\n print(final_df.head())\n print(final_df.shape)\n final_df.to_sql(table_name,con = self.Local_Click_House_Engine, index=False, if_exists='append')\n self.logger.log(\"Insert Data to local db\",\"success\")\n return True\n except Exception as e :\n self.logger.log(\"something error happened\",e)\n return False\n\n def Extract_All_Log_Data(self, stats_dttm, table_name):\n self.connect_db()\n log_sql = \"\"\"\n SELECT * \n FROM \n MOBON_ANALYSIS.MEDIA_CLICKVIEW_LOG\n where 1 = 1\n and toYYYYMMDD(createdDate) = {0}\n \"\"\".format( str(stats_dttm))\n print(log_sql)\n log_sql = text(log_sql)\n try:\n View_Df = pd.read_sql_query(log_sql, self.Click_House_Conn)\n print(View_Df.shape)\n View_Df.to_sql(table_name, con=self.Local_Click_House_Engine, index=False, if_exists='append')\n except Exception as e:\n self.logger.log(\"Error happend\",e)\n self.connect_db()\n View_Df = pd.read_sql_query(log_sql, self.Click_House_Conn)\n View_Df.to_sql(table_name, con=self.Local_Click_House_Engine, index=False, if_exists='append')\n self.logger.log(\"Extract view log to df\", \"success\")\n return True\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--auto\",help=\"(auto : Y, manual : N, migration : M, Test : T ) \", default='T')\n parser.add_argument(\"--create_table\", help=\"--add_table ~~ \", default = None )\n args = parser.parse_args()\n\n # for service\n logger_name = input(\"logger name is : \")\n logger_file = input(\"logger file name is : \")\n\n clickhouse_id = input(\"click house id : \")\n clickhouse_password = input(\"clickhouse password : \")\n maria_id = input(\"maria id : \")\n maria_password = input(\"maria password : \")\n local_clickhouse_id = input(\"local clickhouse id : \" )\n local_clickhouse_password = input(\"local clickhouse password : \" )\n local_clickhouse_DB_name = input(\"local clickhouse DB name : \" )\n local_table_name = input(\"local cllickhouse table name : \" )\n\n data_cnt_per_hour = input(\"the number of data to extract per hour : \" )\n sample_size = input(\"Sampling size : \" )\n\n logger = Logger(logger_name, logger_file)\n logger.log(\"auto mode\", args.auto.upper())\n\n # logger.log(\"extract start\", 'Y')\n\n # clickhouse data extract context 생성\n click_house_context = CLICK_YN_LABELING_CONTEXT(clickhouse_id, clickhouse_password,\n maria_id, maria_password,\n local_clickhouse_id,local_clickhouse_password,\n local_clickhouse_DB_name)\n\n logger.log(\"clickhouse context load\", \"success\")\n if args.create_table == 'click_yn' :\n table_name = input(\"click_yn table name : \" ) \n click_house_context.create_new_local_table(table_name)\n logger.log(\"create clickhouse table {0} success\".format(table_name), 'True')\n elif args.create_table == 'entire_log_yn' : \n table_name = input(\"entire_log_yn table : \" ) \n click_house_context.create_entire_log_table(table_name)\n logger.log(\"create entire_log_yn table\", \"True\")\n\n\n if args.auto.upper() == 'Y' :\n # automatic extracting logic start\n batch_date = datetime.datetime.now()\n click_house_context.Extract_Date_Range_From_DB()\n date_delta = timedelta(days=10)\n extract_date = batch_date - date_delta\n extract_date = extract_date.strftime('%Y%m%d')\n # automatic extracting logic end\n\n elif args.auto.upper() == 'N' :\n # manual extracting logic start\n start_dttm = input(\"extract start dttm is (ex) 20200801 ) : \" )\n from_hh = input(\"start hour is (ex) 00 hour : 00 ) : \")\n last_dttm = input(\"extract last dttm is (ex) 20200827 ) : \" )\n dt_list = pd.date_range(start=start_dttm, end=last_dttm).strftime(\"%Y%m%d\").tolist()\n \n for stats_dttm in dt_list : \n logger.log(\"manual_stats_dttm\",stats_dttm)\n stats_dttm_list = [stats_dttm + '0{0}'.format(i) if i < 10 else stats_dttm + str(i) for i in range(int(from_hh), 24)]\n for Extract_Dttm in stats_dttm_list :\n extract_click_df_result = click_house_context.Extract_Click_Df(Extract_Dttm)\n extract_view_df_result = click_house_context.Extract_View_Df(Extract_Dttm, local_table_name, int(data_cnt_per_hour),\n int(sample_size))\n logger.log(\"Manual_extracting {0} result \".format(Extract_Dttm), extract_view_df_result)\n # manual extracting logic end\n\n if args.auto.upper() == 'M' :\n old_table_name = input(\"old log table name is :\")\n new_table_name = input(\"new log table name is :\")\n start_dttm = input(\"extract start dttm is (ex) 20200801 ) : \")\n last_dttm = input(\"extract last dttm is (ex) 20200827 ) : \")\n dt_list = pd.date_range(start=start_dttm, end=last_dttm).strftime(\"%Y%m%d\").tolist()\n\n for stats_dttm in dt_list:\n logger.log(\"Migration stats_dttm\", stats_dttm)\n migrate_log_df_result = click_house_context.migrate_old_to_new_table(stats_dttm, old_table_name, new_table_name)\n logger.log(\"Migration {0} result \".format(stats_dttm), migrate_log_df_result)\n\n elif args.auto.upper() == 'T' :\n return_value = click_house_context.Extract_Product_Property_Info()\n print(return_value)\n else :\n pass\n","sub_path":"FIRST_ETL_folder/CLICK_YN_LABELING_CONTEXT.py","file_name":"CLICK_YN_LABELING_CONTEXT.py","file_ext":"py","file_size_in_byte":24708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"117734940","text":"\"\"\"\nThis script can be used to tokenize a line dataset of code.\nit uses gigantic-codeprep library that leverages Pygments to parse languages.\n\"\"\"\n\nimport argparse\nfrom pathlib import Path\nimport os\nimport json\nimport logging\n\nimport codeprep.api.text as cp\nfrom tqdm import tqdm\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, default=None, required=True,\n help='Path to the data files to be preprocessed.')\n parser.add_argument('--ext', type=str, default=None, required=True,\n help='Extension of the files.')\n parser.add_argument('--merge_single_file', type=bool, default=False,\n help='Output the results in a single file or in separate files.')\n parser.add_argument('--output_path', type=str, default=None,\n help='If merge_single_file is True, then choose a path to output the results.')\n args = parser.parse_args()\n\n if args.merge_single_file:\n output_file = args.output_path\n with open(output_file, 'w'): pass\n\n for path in Path(args.data_dir).rglob(f'*.{args.ext}'):\n if not args.merge_single_file:\n output = os.path.splitext(path)\n output_file = f'{output[0]}_cleaned{output[1]}'\n with open(output_file, 'w'): pass\n\n logger.info(f'Parsing file: {path}')\n with open(path, encoding='utf-8') as f, open(output_file, encoding='utf-8', mode='a') as f2:\n if args.ext == 'jsonl':\n data = [json.loads(jline) for jline in f.readlines()]\n else:\n data = f.readlines()\n\n for line in tqdm(data):\n if args.ext == 'jsonl':\n tokens = cp.nosplit(\n line['code'],\n no_com=True,\n no_spaces=True,\n return_metadata=True\n )\n else:\n tokens = cp.nosplit(line)\n while '' in tokens:\n tokens.remove('')\n f2.write(' '.join(tokens))\n f2.write('\\n')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"411990838","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 26 16:54:50 2015\n\n@author: Andrew Bedard\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport numpy.random as rnd\nimport matplotlib.pyplot as plt\n\nrnd.seed(10)\n\ndata = pd.read_csv('training_set_VU_DM_2014.csv')\ndata = data.drop('date_time',1)\ndatasize = len(data)\n\ncol_list = list(data.columns.values)\n\ndesc = data.describe()\ndf = desc.copy()\n\nsum_list = []\n\nfor i in range(len(col_list)):\n dummy = df[col_list[i]]\n sum_list.append(dummy[0])\n \n \ndiff = [np.abs(sum_list[i] - sum_list[0]) for i in range(len(col_list))]\ndiff_pct = np.zeros((1,len(col_list)))\n\nfor i in range(len(col_list)):\n if diff[i] != 0:\n diff_pct[0,i] = (diff[i]/sum_list[0])\n \npos = np.arange(len(sum_list))\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.barh(pos, np.array(diff_pct*100), align='center', height=0.1)\nax.set_yticks(pos, ('srch_id','site_id','visitor_location_country_id','visitor_hist_starrating','visitor_hist_adr_usd','prop_country_id','prop_id','prop_starrating','prop_review_score','prop_brand_bool','prop_location_score1','prop_location_score2','prop_log_historical_price','position','price_usd','promotion_flag','srch_destination_id','srch_length_of_stay','srch_booking_window','srch_adults_count','srch_children_count','srch_room_count','srch_saturday_night_bool','srch_query_affinity_score','orig_destination_distance','random_bool','comp1_rate','comp1_inv','comp1_rate_percent_diff','comp2_rate','comp2_inv','comp2_rate_percent_diff','comp3_rate','comp3_inv','comp3_rate_percent_diff','comp4_rate','comp4_inv','comp4_rate_percent_diff','comp5_rate','comp5_inv','comp5_rate_percent_diff','comp6_rate','comp6_inv','comp6_rate_percent_diff','comp7_rate','comp7_inv','comp7_rate_percent_diff','comp8_rate','comp8_inv','comp8_rate_percent_diff','click_bool','gross_bookings_usd','booking_bool'))\n\nax.axvline(0, color='k', lw=3)\n\nax.set_xlabel('Percent missing')\nax.set_title('Percentage of data missing')\nax.gird(True)\nplt.show()\n\nplt.barh()","sub_path":"assignment_2/data_explore/DE_1.py","file_name":"DE_1.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"626093412","text":"from ROOT import TLorentzVector, TVector3, TRotation\r\nfrom math import asin, atan2, sin, cos, acos, sqrt\r\n\r\ndef getResVars_neil(parent, lab_lamc, lab_p, lab_h1, lab_h2):\r\n '''\r\n Takes the Lc decay and outputs a list containing the resonant variables.\r\n All arguments should be TLorentzVectors. If the Lc is prompt 'parent' is\r\n just the beam direction.\r\n '''\r\n \r\n lab_ph1 = lab_p + lab_h1\r\n lab_h1h2 = lab_h1 + lab_h2\r\n lab_ph2 = lab_p + lab_h2\r\n\r\n # Invariant mass combinations\r\n Lambdac_sph1 = sqrt(lab_ph1.M2())/1000.0\r\n Lambdac_sh1h2 = sqrt(lab_h1h2.M2())/1000.0\r\n Lambdac_sph2 = sqrt(lab_ph2.M2())/1000.0\r\n \r\n # Now set the parent direction.\r\n lab_beam = parent #TLorentzVector()\r\n #lab_beam.SetXYZM(0.0, 0.0, 1.0, 1.0) # Beam direction\r\n\r\n lab_xhat = TLorentzVector(1.0, 0.0, 0.0, 1.0)\r\n lab_yhat = TLorentzVector(0.0, 1.0, 0.0, 1.0)\r\n lab_zhat = TLorentzVector(0.0, 0.0, 1.0, 1.0)\r\n \r\n # Rotation angles\r\n zeta = atan2(lab_lamc.Z(), lab_lamc.X() )\r\n r2_lamc = TLorentzVector( lab_lamc )\r\n r2_lamc.RotateY( zeta )\r\n eta = -asin( r2_lamc.Y() / r2_lamc.Rho() )\r\n \r\n R_lab = TRotation()\r\n R_lab.RotateY( zeta )\r\n R_lab.RotateZ( eta )\r\n\r\n lab_R1_p = TLorentzVector(lab_p)\r\n lab_R1_h1 = TLorentzVector(lab_h1)\r\n lab_R1_h2 = TLorentzVector(lab_h2)\r\n lab_R1_lamc = TLorentzVector(lab_lamc)\r\n lab_R1_beam = TLorentzVector(lab_beam)\r\n lab_R1_xhat = TLorentzVector(lab_xhat)\r\n lab_R1_yhat = TLorentzVector(lab_yhat)\r\n lab_R1_zhat = TLorentzVector(lab_zhat)\r\n \r\n lab_R1_p.Transform(R_lab)\r\n lab_R1_h1.Transform(R_lab)\r\n lab_R1_h2.Transform(R_lab)\r\n lab_R1_lamc.Transform(R_lab)\r\n lab_R1_beam.Transform(R_lab)\r\n lab_R1_xhat.Transform(R_lab)\r\n lab_R1_yhat.Transform(R_lab)\r\n lab_R1_zhat.Transform(R_lab)\r\n\r\n # Boost into the Lc rest frame.\r\n lcRest_R1_p = TLorentzVector(lab_R1_p)\r\n lcRest_R1_h1 = TLorentzVector(lab_R1_h1)\r\n lcRest_R1_h2 = TLorentzVector(lab_R1_h2)\r\n lcRest_R1_lamc = TLorentzVector(lab_R1_lamc)\r\n lcRest_R1_beam = TLorentzVector(lab_R1_beam)\r\n \r\n lcRest_boost = -lab_R1_lamc.BoostVector()\r\n lcRest_R1_p.Boost(lcRest_boost)\r\n lcRest_R1_h1.Boost(lcRest_boost)\r\n lcRest_R1_h2.Boost(lcRest_boost)\r\n lcRest_R1_lamc.Boost(lcRest_boost)\r\n lcRest_R1_beam.Boost(lcRest_boost)\r\n \r\n # One final transformation to bring the polarization axis,\r\n # p_beam X xhat, along the z-axis.\r\n t3_lcRest_R1_polarize = lcRest_R1_beam.Vect().Cross( TVector3(1.0, 0.0, 0.0) )\r\n xi = atan2(t3_lcRest_R1_polarize.Y(), t3_lcRest_R1_polarize.Z())\r\n \r\n lcRest_R1_p.RotateX( xi )\r\n lcRest_R1_h1.RotateX( xi )\r\n lcRest_R1_h2.RotateX( xi )\r\n lcRest_R1_lamc.RotateX( xi )\r\n lcRest_R1_beam.RotateX( xi )\r\n \r\n # Proton rest frame angles defining the phase space\r\n proton_LcRest_theta = lcRest_R1_p.Theta()\r\n proton_LcRest_costheta = lcRest_R1_p.CosTheta()\r\n proton_LcRest_phi = lcRest_R1_p.Phi()\r\n proton_LcRest_cosphi = cos(lcRest_R1_p.Phi())\r\n proton_LcRest_sinphi = sin(lcRest_R1_p.Phi())\r\n \r\n # Decay plane angles\r\n t3_lcRest_R1_p = lcRest_R1_p.Vect()\r\n t3_lcRest_R1_h1 = lcRest_R1_h1.Vect()\r\n t3_lcRest_R1_h2 = lcRest_R1_h2.Vect()\r\n t3_lcRest_R1_polarize = lcRest_R1_beam.Vect().Cross( TVector3(1.0, 0.0, 0.0) )\r\n \r\n pz_norm_hat = (t3_lcRest_R1_p.Cross(t3_lcRest_R1_polarize)).Unit()\r\n h1h2_norm_hat = (t3_lcRest_R1_h1.Cross(t3_lcRest_R1_h2)).Unit()\r\n Lambdac_LcRest_costhetah1h2 = pz_norm_hat.Dot(h1h2_norm_hat)\r\n\r\n sense_vector = h1h2_norm_hat.Cross(pz_norm_hat)\r\n Lambdac_LcRest_thetah1h2 = acos(Lambdac_LcRest_costhetah1h2)\r\n if( sense_vector.Dot( t3_lcRest_R1_polarize ) < 0.0) :\r\n Lambdac_LcRest_thetah1h2 = -Lambdac_LcRest_thetah1h2\r\n \r\n# return ( Lambdac_sph1,\r\n # Lambdac_sh1h2,\r\n # Lambdac_sph2,\r\n # proton_LcRest_costheta,\r\n # proton_LcRest_cosphi,\r\n # Lambdac_LcRest_thetah1h2 )\r\n \r\n return ( proton_LcRest_costheta,\r\n proton_LcRest_cosphi,\r\n Lambdac_LcRest_thetah1h2 )\r\n","sub_path":"scripts/neil_scripts/getResVars_neil.py","file_name":"getResVars_neil.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"310445874","text":"import tensorflow as tf\nfrom robamine.algo.ddpg import DDPG, Actor, Critic, Target\nfrom robamine.algo.util import seed_everything, Logger\nimport numpy as np\nimport logging\n\n\nif __name__ == '__main__':\n # with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess:\n with tf.Session() as sess:\n\n # log = logging.getLogger('tensorflow')\n # log.setLevel(logging.DEBUG)\n # formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n # fh = logging.FileHandler('tensorflow.log')\n # fh.setLevel(logging.DEBUG)\n # fh.setFormatter(formatter)\n # log.addHandler(fh)\n\n seed_everything(999)\n\n logger = Logger(sess, '/home/iason/robamine_logs/example', 'none', 'lol', True)\n # actor = Actor.create(sess, 2, [100, 100], 3)\n\n inp = tf.placeholder(tf.float64, [None, 10])\n out, net_params = Actor.architecture(inp, [100, 200], 10, [-3e-6, 3e-6])\n grad = tf.gradients(out, net_params)\n gradients = list(map(lambda x: tf.div(x, 10, name='div_by_N'), grad))\n optimizer = tf.train.AdamOptimizer(1e-4, name='optimizer').apply_gradients(zip(gradients, net_params))\n sess.run(tf.global_variables_initializer())\n for i in range(100):\n # logger.console.debug('initial:' + actor.get_params().__str__())\n\n state_batch = np.random.rand(10, 10)\n outt = np.random.rand(10, 5)\n logger.console.debug('state_batch:' + state_batch.__str__())\n\n sess.run(optimizer, feed_dict={inp: state_batch})\n params= sess.run(net_params)\n logger.console.debug('result:' + params.__str__())\n\n\n ######## grad = np.random.rand(10, 3)\n ######## logger.console.debug('grad:' + grad.__str__())\n ######## # actor.learn(state_batch, grad)\n ######## logger.console.debug('final:' + actor.get_params().__str__())\n\n","sub_path":"examples/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"370808804","text":"#cool\nimport serial # import the serial library\nimport time # import the time library\nfrom time import sleep\nimport RPi.GPIO as GPIO\nfrom tkinter import * #import Tkinter GUI library\n\n\n\n#Variable declarations\nDIR = 20 # Direction GPIO Pin\nSTEP = 21 # Step GPIO Pin\nDIR2 = 22\nSTEP2 = 27\nDIR3 = 19\nSTEP3 = 26\n\n\n\n\nCW = 1 # Clockwise Rotation\nCCW = 0 # Counterclockwise Rotation\nSPR = 180 # Steps per Revolution (360 / 7.5)\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(DIR, GPIO.OUT)\nGPIO.setup(STEP, GPIO.OUT)\nGPIO.output(DIR, CW)\nGPIO.setup(DIR2, GPIO.OUT)\nGPIO.setup(STEP2, GPIO.OUT)\nGPIO.output(DIR2, CW)\nGPIO.setup(DIR3, GPIO.OUT)\nGPIO.setup(STEP3, GPIO.OUT)\nGPIO.output(DIR3, CW)\n\n\nMODE = (14, 15, 18) # Microstep Resolution GPIO Pins\nGPIO.setup(MODE, GPIO.OUT)\nRESOLUTION = {'Full': (0, 0, 0),\n 'Half': (1, 0, 0),\n '1/4': (0, 1, 0),\n '1/8': (1, 1, 0),\n '1/16': (0, 0, 1),\n '1/32': (1, 0, 1)}\nGPIO.output(MODE, RESOLUTION['Full'])\n\n\nstep_count = SPR * 1\ndelay = .0208 / 1\n\n\n\nclass StepperActions:\n \n def __init__(self):\n self.logicLeft = False\n self.logicRight = False\n self.logicUp = False\n self.logicDown = False\n self.logicForward = False\n self.logicBackward = False\n self.trigger = 0\n\n\n\n## self.GPIO.setmode(self.GPIO.BCM)\n## self.GPIO.setup(DIR, self.GPIO.OUT)\n## self.GPIO.setup(STEP, self.GPIO.OUT)\n## self.GPIO.output(DIR, CW)\n## self.GPIO.setup(DIR2, self.GPIO.OUT)\n## self.GPIO.setup(STEP2, self.GPIO.OUT)\n## self.GPIO.output(DIR2, CW)\n## self.GPIO.setup(DIR3, self.GPIO.OUT)\n## self.GPIO.setup(STEP3, self.GPIO.OUT)\n## self.GPIO.output(DIR3, CW)\n \n def angle_2_step(self, floatNum):\n self.angle = floatNum\n \n def getKey(item): #wrapper function to sort tuple\n return item[0]\n \n#defining the functions\n def movement(self, direction1, direction2, direction3, angle1, angle2, angle3):\n global DIRECTION1\n DIRECTION1 = 0\n global DIRECTION2\n DIRECTION2 = 0\n global DIRECTION3\n DIRECTION3 = 0\n \n if direction1 is \"Left\":\n DIRECTION1 = CCW\n elif direction1 is \"Right\":\n DIRECTION1 = CW\n\n if direction2 is \"Down\":\n DIRECTION2 = CCW\n elif direction2 is \"Up\":\n DIRECTION2 = CW\n\n if direction3 is \"Foward\":\n DIRECTION3 = CCW\n elif direction3 is \"Backward\":\n DIRECTION3 = CW\n\n angleList = [angle1, angle2, angle3]\n\n stepperDirList = [DIR3, DIR, DIR2]\n stepperList = [STEP3, STEP, STEP2]\n dirList = [DIRECTION1, DIRECTION2, DIRECTION3]\n tupleList = list(zip(angleList, stepperDirList, dirList, stepperList))\n sorted(tupleList, key=lambda item: item[1])\n smallestAngle = 0\n smallestDir = 0\n smallestRotate = 0\n smallStep = 0\n \n midAngle = 0\n midDir = 0\n midRotate = 0\n midStep = 0\n \n bigAngle = 0\n bigDir = 0\n bigRotate = 0\n bigStep = 0\n \n#'''this is not how you make tuples'''\n## bigAngle = tuple[2][0]\n## bigDir = tuple[2][1]\n## bigRotate = tuple[2][2]\n## bigStep GPIO.setup(MODE, GPIO.OUT)= tuple[2][3]\n##\n## midAngle = tuple[1][0]\n## midDir = tuple[1][1]\n## midRotate = tuple[1][2]\n## midStep = tuple[1][3]\n##\n## smallestAngle = tuple[0][0]\n## smallestDir = tuple[0][1]\n## smallestRotate = tuple[0][2]\n## small myTuple = ([smallestAngle, smallestDir, smallestRotate, smallStep], [midAngle, midDir, midRotate, midStep], [bigAngle, bigDir, bigRotate, bigStep])Step = tuple[0][3]\n\n\n myTuple = ([smallestAngle, smallestDir, smallestRotate, smallStep], [midAngle, midDir, midRotate, midStep], [bigAngle, bigDir, bigRotate, bigStep])\n \n GPIO.output(myTuple[0][1], myTuple[0][2])\n for x in range(int(round(myTuple[0][0]/2))):\n GPIO.output((myTuple[0][3], myTuple[1][3], myTuple[2][3]), GPIO.HIGH)\n sleep(delay)\n GPIO.output((myTuple[0][3], myTuple[1][3], myTuple[2][3]), GPIO.LOW)\n sleep(delay)\n \n GPIO.output(myTuple[1][1], myTuple[1][2])\n for x in range(int(round((myTuple[1][0]-myTuple[0][0])/2))):\n GPIO.output((myTuple[1][3], myTuple[2][3]), GPIO.HIGH)\n sleep(delay)\n GPIO.output((myTuple[1][3], myTuple[2][3]), GPIO.LOW)\n sleep(delay)\n\n GPIO.output(myTuple[2][0], myTuple[2][2])\n for x in range(int(round((bigAngle-myTuple[1][0]-myTuple[0][0])/2))):\n GPIO.output((myTuple[2][3]), GPIO.HIGH)\n sleep(delay)\n GPIO.output((myTuple[2][3]), GPIO.LOW)\n sleep(delay)\n\n\n \n '''\n if angle1 > angle 2 and angle 1 > angle3:\n greatestAngle = angle1:\n greatestDir = DIRECTION1\n if angle 2 > angle3\n midAngle = angle2\n midDir = DIRECTION2\n smallestAngle = angle3\n smallestDir = DIRECTION3\n else\n\n elif angle2 > angle1 and angle2 > angle3\n greatestAngle = angle2:\n greatestDir = DIRECTION2\n if angle 1 > angle3\n midAngle = angle2\n midDir = DIRECTION2\n smallestAngle = angle3\n small GPIO.output(myTuple[0][1], myTuple[0][2])estDir = DIRECTION3\n '''\n\n\n def Right(self, resultnum):\n GPIO.output(DIR3, CW)\n print(\"CW\")\n for x in range(int(round(resultnum/2))):\n GPIO.output(STEP3, GPIO.HIGH)\n sleep(delay)\n GPIO.output(STEP3, GPIO.LOW)\n sleep(delay)\n\n def Left(self, resultnum):\n GPIO.output(DIR3, CCW)\n print(\"CCW\")\n for x in range(int(round(resultnum/2))):\n GPIO.output(STEP3, GPIO.HIGH)\n sleep(delay)\n GPIO.output(STEP3, GPIO.LOW)\n sleep(delay)\n\n def Up(self, resultnum):\n GPIO.output(DIR, CW)\n print(\"Up\")\n for x in range(int(round(resultnum/2))):\n GPIO.output(STEP, GPIO.HIGH)\n sleep(delay)\n GPIO.output(STEP, GPIO.LOW)\n sleep(delay)\n\n def Down(self, resultnum):\n GPIO.output(DIR, CCW)\n print(\"Down\")\n for x in range(int(round(resultnum/2))):\n GPIO.output(STEP, GPIO.HIGH)\n sleep(delay)\n GPIO.output(STEP, GPIO.LOW)\n sleep(delay)\n\n def Forward(self, resultnum):\n GPIO.output(DIR2, CW)\n print(\"forward\")\n for x in range(int(round(resultnum/2))):\n GPIO.output(STEP2, GPIO.HIGH)\n sleep(delay)\n GPIO.output(STEP2, GPIO.LOW)\n sleep(delay)\n\n def Backward(self, resultnum):\n GPIO.output(DIR2, CCW)\n print(\"backward\")\n for x in range(int(round(resultnum/2))):\n GPIO.output(STEP2, GPIO.HIGH)\n sleep(delay)\n GPIO.output(STEP2, GPIO.LOW)\n sleep(delay)\n \n","sub_path":"3dRobotArm/EvoArm-master/PyIK/src/stepper.py","file_name":"stepper.py","file_ext":"py","file_size_in_byte":7203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"} +{"seq_id":"89923528","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport rospy\nfrom uwds3_msgs.msg import WorldStamped\nfrom uwds3_msgs.srv import Query\nfrom pyuwds3.types.scene_node import SceneNode\nfrom pyuwds3.types.temporal_situation import TemporalPredicate\nfrom ontologenius import OntologyManipulator\n\n\nclass OntologeniusReaderNode(object):\n \"\"\" The ontologenius reader which allow to query uwds3 entities with SPARQL-like queries \"\"\"\n def __init__(self):\n \"\"\" Default constructor \"\"\"\n\n self.ontologenius_client = OntologyManipulator()\n self.ontologenius_client.close()\n rospy.loginfo(\"[ontologenius_reader] Connected to Ontologenius !\")\n\n self.created_nodes = {}\n self.scene_nodes = {}\n self.created_situations = {}\n\n self.uwds3_oro_id_map = {}\n self.oro_uwds3_id_map = {}\n\n self.support = {}\n self.graspable = {}\n self.container = {}\n self.movable = {}\n self.held_by = {}\n self.relations = {}\n\n self.query_service = rospy.Service(\"uwds3/query_knowledge_base\", Query, self.handle_query)\n\n input_world_topic = rospy.get_param(\"~input_world_topic\", \"corrected_tracks\")\n rospy.loginfo(\"[ontologenius_reader] Connecting to '\" + input_world_topic + \"'...\")\n self.world_subscriber = rospy.Subscriber(input_world_topic, WorldStamped, self.callback, queue_size=1)\n rospy.loginfo(\"[ontologenius_reader] Connected to Underworlds !\")\n\n def handle_query(self, req, agent=\"myself\"):\n \"\"\" Handle the query \"\"\"\n try:\n query_tokens = req.query.split(\",\")\n #first_variable = query_tokens[0].split(\" \")[0]\n query = req.query\n result_nodes = []\n if len(query_tokens) > 1:\n results = self.ontologenius_client.sparql.call(query)\n else:\n results = self.ontologenius_client.sparql.call(query)\n rospy.logwarn(results)\n if len(results) > 0:\n for node_id in results[0]:\n if node_id in self.scene_nodes:\n result_nodes.append(self.scene_nodes[node_id])\n return result_nodes, True, \"\"\n else:\n return [], True, \"\"\n except Exception as e:\n rospy.logwarn(\"[ontologenius_reader] Exception occurred : \"+str(e))\n return [], False, str(e)\n\n def callback(self, world_msg):\n \"\"\" World callback \"\"\"\n scene_nodes = {}\n for node_msg in world_msg.world.scene:\n node = SceneNode().from_msg(node_msg)\n scene_nodes[node.id] = node\n if node.id not in self.created_nodes:\n self.add_scene_node(node)\n self.created_nodes[node.id] = True\n\n for situation_msg in world_msg.world.timeline:\n situation = TemporalPredicate().from_msg(situation_msg)\n self.learn_affordance(situation)\n self.update_situation(situation)\n\n self.scene_nodes = scene_nodes\n\n def add_scene_node(self, scene_node, agent=\"myself\"):\n \"\"\" Add the given scene node \"\"\"\n types = []\n\n if scene_node.label == \"myself\":\n types.append(\"Robot\")\n elif scene_node.label == \"person\":\n types.append(\"Human\")\n else:\n if scene_node.has_shape():\n types.append(\"SolidObject\")\n elif scene_node.is_located():\n types.append(\"SpatialThingLocated\")\n else:\n types.append(\"PartiallyTangibleThing\")\n\n for type in types:\n rospy.loginfo(\"add: \"+scene_node.id+\" isA \"+type)\n self.ontologenius_client.feeder.addObjectProperty(scene_node.id, \"isA\", type)\n rospy.loginfo(\"add: \"+scene_node.id+\" hasName \"+scene_node.description)\n self.ontologenius_client.feeder.addObjectProperty(scene_node.id, \"hasName\", scene_node.description)\n\n def update_situation(self, situation, agent=\"myself\"):\n \"\"\" Updates the given situations \"\"\"\n if situation.predicate == \"pick\":\n if situation.object not in self.held_by:\n self.ontologenius_client.feeder.addObjectProperty(situation.object, \"isHeldBy\", situation.subject)\n self.held_by[situation.object] = situation.subject\n elif situation.predicate == \"place\":\n if situation.object in self.held_by:\n self.ontologenius_client.feeder.removeObjectProperty(situation.object, \"isHeldBy\", situation.subject)\n del self.held_by[situation.object]\n elif situation.predicate == \"release\":\n if situation.object in self.held_by:\n self.ontologenius_client.feeder.removeObjectProperty(situation.object, \"isHeldBy\", situation.subject)\n del self.held_by[situation.object]\n\n if situation.predicate == \"in\":\n if not situation.is_finished():\n if situation.subject+\"isInside\"+situation.object not in self.relations:\n rospy.loginfo(\"add: \"+situation.subject+\" isInside \"+situation.object)\n self.ontologenius_client.feeder.addObjectProperty(situation.subject, \"isInside\", situation.object)\n self.relations[situation.subject+\"isInside\"+situation.object] = True\n else:\n if situation.subject+\"isInside\"+situation.object in self.relations:\n rospy.loginfo(\"remove: \"+situation.subject+\" isInside \"+situation.object)\n self.ontologenius_client.feeder.removeObjectProperty(situation.subject, \"isInside\", situation.object)\n del self.relations[situation.subject+\"isInside\"+situation.object]\n elif situation.predicate == \"on\":\n if not situation.is_finished():\n if situation.subject+\"isOnTop\"+situation.object not in self.relations:\n rospy.loginfo(\"add: \"+situation.subject+\" isOnTop \"+situation.object)\n self.ontologenius_client.feeder.addObjectProperty(situation.subject, \"isOnTop\", situation.object)\n self.relations[situation.subject+\"isOnTop\"+situation.object] = True\n else:\n if situation.subject+\"isOnTop\"+situation.object in self.relations:\n rospy.loginfo(\"remove: \"+situation.subject+\" isOnTop \"+situation.object)\n self.ontologenius_client.feeder.removeObjectProperty(situation.subject, \"isOnTop\", situation.object)\n del self.relations[situation.subject+\"isOnTop\"+situation.object]\n elif situation.predicate == \"close\":\n if not situation.is_finished():\n if situation.subject+\"isCloseTo\"+situation.object not in self.relations:\n rospy.loginfo(\"add: \"+situation.subject+\" isCloseTo \"+situation.object)\n self.ontologenius_client.feeder.addObjectProperty(situation.subject, \"isCloseTo\", situation.object)\n self.relations[situation.subject+\"isCloseTo\"+situation.object] = True\n else:\n if situation.subject+\"isCloseTo\"+situation.object in self.relations:\n rospy.loginfo(\"remove: \"+situation.subject+\" isCloseTo \"+situation.object)\n self.ontologenius_client.feeder.removeObjectProperty(situation.subject, \"isCloseTo\", situation.object)\n del self.relations[situation.subject+\"isCloseTo\"+situation.object]\n else:\n pass\n\n def learn_affordance(self, situation, agent=\"myself\"):\n \"\"\" Learn the affordances from the physical reasoner \"\"\"\n if situation.predicate == \"pick\":\n if situation.object not in self.graspable:\n rospy.loginfo(\"add: \"+situation.object+\" isA \"+\"GraspableObject\")\n self.ontologenius_client.feeder.addObjectProperty(situation.subject, \"isA\", \"GraspableObject\")\n self.graspable[situation.object] = True\n elif situation.predicate == \"on\":\n if situation.object not in self.support:\n rospy.loginfo(\"add: \"+situation.object+\" isA \"+\"SupportObject\")\n self.ontologenius_client.feeder.addObjectProperty(situation.object, \"isA\", \"SupportObject\")\n self.support[situation.object] = True\n elif situation.predicate == \"in\":\n if situation.object not in self.container:\n rospy.loginfo(\"add: \"+situation.object+\" isA \"+\"ContainerObject\")\n self.ontologenius_client.feeder.addObjectProperty(situation.object, \"isA\", \"ContainerObject\")\n self.container[situation.object] = True\n\n def run(self):\n \"\"\" Run the component \"\"\"\n while not rospy.is_shutdown():\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"ontologenius_reader\", anonymous=True)\n recorder = OntologeniusReaderNode().run()\n","sub_path":"scripts/ontologenius_reader_node.py","file_name":"ontologenius_reader_node.py","file_ext":"py","file_size_in_byte":8909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"58"}